@ansible-flow/assets 1.2.0-rc.1 → 1.2.0-rc.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/package.json +1 -1
- package/probe/afd_lib/capture.py +40 -7
- package/probe/afd_lib/debug.py +122 -22
- package/probe/afd_lib/mask.py +6 -2
- package/probe/afd_lib/render.py +78 -11
- package/probe/afd_lib/taint.py +354 -0
- package/probe/strategy_plugins/afd_step.py +114 -16
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Ansible Flow Designer files a host passes by path: the Python probe, the run events callback, the JSON schemas, the contract with Ansible Flow Server and the sample projects.
|
|
4
4
|
|
|
5
|
-
Built from [Ansible Flow Designer](https://github.com/ChistokhinSV/ansible-flow-designer) 1.2.0-rc.
|
|
5
|
+
Built from [Ansible Flow Designer](https://github.com/ChistokhinSV/ansible-flow-designer) 1.2.0-rc.3
|
|
6
6
|
and released with it. The folders are found by path: `import { probeDir, schemaDir, contractDir, samplesDir } from '@ansible-flow/assets'`.
|
|
7
7
|
|
|
8
8
|
What is in the package, which entry points are documented and what may change:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ansible-flow/assets",
|
|
3
|
-
"version": "1.2.0-rc.
|
|
3
|
+
"version": "1.2.0-rc.3",
|
|
4
4
|
"description": "Ansible Flow Designer files a host passes by path: the Python probe, the run events callback, the JSON schemas, the contract with Ansible Flow Server and the sample projects.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://github.com/ChistokhinSV/ansible-flow-designer/blob/main/docs/packages.md",
|
package/probe/afd_lib/capture.py
CHANGED
|
@@ -18,7 +18,7 @@ import math
|
|
|
18
18
|
import re
|
|
19
19
|
from collections.abc import Mapping
|
|
20
20
|
|
|
21
|
-
from .mask import Masked, Masker
|
|
21
|
+
from .mask import SECRET_NAME, Masked, Masker
|
|
22
22
|
|
|
23
23
|
try:
|
|
24
24
|
from ansible._internal._datatag._tags import TrustedAsTemplate
|
|
@@ -52,11 +52,13 @@ MAGIC = {
|
|
|
52
52
|
"ansible_search_path", "ansible_loop_var", "ansible_index_var", "ansible_parent_role_names",
|
|
53
53
|
"ansible_parent_role_paths", "ansible_role_name", "ansible_vault_id", "vars",
|
|
54
54
|
} # fmt: skip
|
|
55
|
-
# The generator's own play variables: not inputs of the step.
|
|
56
|
-
OWN_PLAY_VARS = {"flow_node_id", "afd_sim"}
|
|
55
|
+
# The generator's own play variables: not inputs of the step (afd_repo_root, afd_* data names).
|
|
56
|
+
OWN_PLAY_VARS = {"flow_node_id", "afd_sim", "afd_repo_root"}
|
|
57
57
|
# The record inputs task marks an input the flow knows is secret with this constant (AFD-341).
|
|
58
58
|
SECRET_MARK = "__afd_secret__"
|
|
59
59
|
_MARKED = re.compile(r"'([A-Za-z_][A-Za-z0-9_]*)'\s*:\s*'" + SECRET_MARK + "'")
|
|
60
|
+
# Every input the record inputs task names: `'devices': (('__afd_vault__' ...` or a secret's mark.
|
|
61
|
+
_INPUT = re.compile(r"'([A-Za-z_][A-Za-z0-9_]*)'\s*:\s*(?:\(|'" + SECRET_MARK + "')")
|
|
60
62
|
|
|
61
63
|
|
|
62
64
|
def plain(value: object, depth: int = 0) -> object:
|
|
@@ -178,6 +180,21 @@ def nolog_registers(play) -> set[str]:
|
|
|
178
180
|
return found
|
|
179
181
|
|
|
180
182
|
|
|
183
|
+
def step_inputs(play) -> set[str]:
|
|
184
|
+
"""The step's inputs by name, as its record inputs task lists them: an input the flow data
|
|
185
|
+
gives (`devices`) is an extra variable, not a play variable, and is a step input too."""
|
|
186
|
+
found: set[str] = set()
|
|
187
|
+
|
|
188
|
+
def visit(task) -> None:
|
|
189
|
+
if str(getattr(task, "name", "") or "").endswith("] record inputs"):
|
|
190
|
+
for v in (getattr(task, "args", None) or {}).values():
|
|
191
|
+
found.update(_INPUT.findall(str.__str__(str(v))))
|
|
192
|
+
|
|
193
|
+
with contextlib.suppress(Exception):
|
|
194
|
+
_walk_tasks(list(play.tasks or []), visit)
|
|
195
|
+
return found
|
|
196
|
+
|
|
197
|
+
|
|
181
198
|
def secret_inputs(play) -> set[str]:
|
|
182
199
|
"""The inputs the flow knows are secret: the record inputs task writes them as a constant."""
|
|
183
200
|
found: set[str] = set()
|
|
@@ -204,20 +221,34 @@ class HostView:
|
|
|
204
221
|
secret: set[str],
|
|
205
222
|
masker: Masker,
|
|
206
223
|
nolog: set[str] | None = None,
|
|
224
|
+
inputs: set[str] | None = None,
|
|
207
225
|
) -> None:
|
|
208
226
|
self._vars = all_vars
|
|
209
|
-
self._play_vars = play_vars - OWN_PLAY_VARS
|
|
227
|
+
self._play_vars = {n for n in play_vars - OWN_PLAY_VARS if not str(n).startswith("afd_")}
|
|
228
|
+
self._inputs = (inputs or set()) | self._play_vars
|
|
229
|
+
self._all_play = play_vars
|
|
210
230
|
self._extra = extra
|
|
211
231
|
self._secret = secret
|
|
212
232
|
self._nolog = nolog or set()
|
|
213
233
|
self._masker = masker
|
|
214
234
|
self._scopes: dict[str, dict[str, object]] = {}
|
|
215
|
-
|
|
216
|
-
|
|
235
|
+
# A value under a secret-looking name is learned, so its copies are caught. Magic variables
|
|
236
|
+
# are not: they hold host and group names (groups: flow_<step>_ok_hosts, where a step key
|
|
237
|
+
# may look secret), and `vars` holds every variable again. Nor is a no_log register: it is
|
|
238
|
+
# masked whole by its name. Learning them masked a host's name for the rest of the run.
|
|
239
|
+
for name, v in all_vars.items():
|
|
240
|
+
if str(name) in MAGIC or str(name) in self._nolog:
|
|
241
|
+
continue
|
|
242
|
+
masker.learn(v, secret=bool(SECRET_NAME.search(str(name))))
|
|
217
243
|
|
|
218
244
|
def scope_of(self, name: str) -> str | None:
|
|
219
245
|
if name in MAGIC or name in OWN_PLAY_VARS or name.startswith("ansible_facts"):
|
|
220
246
|
return None
|
|
247
|
+
if name not in self._extra and name.startswith("afd_"):
|
|
248
|
+
# The generator's own: its play variables and the facts its code sets on a host
|
|
249
|
+
# (afd_failed_node, afd_failed_result, afd_failed_task, afd_inputs). Evaluate still
|
|
250
|
+
# reads them.
|
|
251
|
+
return None
|
|
221
252
|
if name in self._extra:
|
|
222
253
|
return "flow"
|
|
223
254
|
if name in self._play_vars:
|
|
@@ -241,7 +272,9 @@ class HostView:
|
|
|
241
272
|
out[str(name)] = plain(self._masker.mask(str(name), facts[name]))
|
|
242
273
|
else:
|
|
243
274
|
for name in sorted(self._vars, key=str):
|
|
244
|
-
|
|
275
|
+
where = self.scope_of(str(name))
|
|
276
|
+
# A step input the flow data gives is listed in both: it is the step's input.
|
|
277
|
+
if not (where == scope or (scope == "inputs" and where and name in self._inputs)):
|
|
245
278
|
continue
|
|
246
279
|
if scope == "inputs" and name in self._secret:
|
|
247
280
|
out[name] = plain(Masked("credential"))
|
package/probe/afd_lib/debug.py
CHANGED
|
@@ -15,7 +15,8 @@ from collections.abc import Mapping
|
|
|
15
15
|
|
|
16
16
|
from . import capture, render
|
|
17
17
|
from .capture import HostView, entry, plain, to_json
|
|
18
|
-
from .mask import TAGS, Masker
|
|
18
|
+
from .mask import REDACTED, TAGS, Masker
|
|
19
|
+
from .taint import MAX_HOSTS, Taint, TooMany, mask_blocks
|
|
19
20
|
|
|
20
21
|
VERSION = 1
|
|
21
22
|
# A gate's conditions and log messages, for every host: one child, at most this long.
|
|
@@ -73,6 +74,8 @@ class Gate:
|
|
|
73
74
|
self._views: dict[str, HostView] = {}
|
|
74
75
|
self._secret: set[str] | None = None
|
|
75
76
|
self._templar = None
|
|
77
|
+
self._raw: dict[str, Mapping | None] = {}
|
|
78
|
+
self._taints: dict[str, Taint] = {}
|
|
76
79
|
|
|
77
80
|
# ---- what a host has -------------------------------------------------------------------
|
|
78
81
|
def variables(self, host) -> Mapping:
|
|
@@ -84,6 +87,44 @@ class Gate:
|
|
|
84
87
|
_hosts_all=getattr(s, "_hosts_cache_all", None),
|
|
85
88
|
)
|
|
86
89
|
|
|
90
|
+
def raw(self, name: str) -> Mapping | None:
|
|
91
|
+
"""Any inventory host's variables (raw, nothing rendered), once per pause."""
|
|
92
|
+
if name not in self._raw:
|
|
93
|
+
host = self.hosts.get(name)
|
|
94
|
+
if host is None:
|
|
95
|
+
host = self.strategy._inventory.get_host(name) # noqa: SLF001
|
|
96
|
+
self._raw[name] = self.variables(host) if host is not None else None
|
|
97
|
+
return self._raw[name]
|
|
98
|
+
|
|
99
|
+
def inventory_hosts(self) -> list[str]:
|
|
100
|
+
return [h.get_name() for h in self.strategy._inventory.get_hosts("all")] # noqa: SLF001
|
|
101
|
+
|
|
102
|
+
def secret(self) -> set[str]:
|
|
103
|
+
if self._secret is None:
|
|
104
|
+
self._secret = capture.secret_inputs(self.play)
|
|
105
|
+
return self._secret
|
|
106
|
+
|
|
107
|
+
def taint(self, name: str) -> Taint:
|
|
108
|
+
"""What `name`'s expressions read, checked against the masking (AFD-373)."""
|
|
109
|
+
if name not in self._taints:
|
|
110
|
+
self.view(name) # learns the plain texts of the host's vaulted values first
|
|
111
|
+
self._taints[name] = Taint(
|
|
112
|
+
self.session.masker,
|
|
113
|
+
self.environment(),
|
|
114
|
+
self.raw,
|
|
115
|
+
self.inventory_hosts,
|
|
116
|
+
name,
|
|
117
|
+
nolog=self.session.nolog,
|
|
118
|
+
secret=self.secret(),
|
|
119
|
+
)
|
|
120
|
+
return self._taints[name]
|
|
121
|
+
|
|
122
|
+
def masked_by(self, name: str, text: str, template: bool = False) -> str | None:
|
|
123
|
+
"""Why what `text` renders for host `name` is masked whole; None when nothing it reads is
|
|
124
|
+
masked. Raises TooMany for hostvars by a host chosen at run time in a large inventory."""
|
|
125
|
+
t = self.taint(name)
|
|
126
|
+
return t.template(text) if template else t.expression(text)
|
|
127
|
+
|
|
87
128
|
def view(self, name: str) -> HostView:
|
|
88
129
|
if name not in self._views:
|
|
89
130
|
if self._secret is None:
|
|
@@ -96,15 +137,21 @@ class Gate:
|
|
|
96
137
|
secret=self._secret,
|
|
97
138
|
masker=self.session.masker,
|
|
98
139
|
nolog=self.session.nolog,
|
|
140
|
+
inputs=capture.step_inputs(self.play),
|
|
99
141
|
)
|
|
100
142
|
return self._views[name]
|
|
101
143
|
|
|
102
144
|
def environment(self):
|
|
145
|
+
# Only parsed and lexed with (names read, syntax checks), never rendered with: a Jinja
|
|
146
|
+
# environment of our own parses as Ansible's does. Templar.environment is deprecated in
|
|
147
|
+
# ansible-core 2.19 (removed in 2.23), and reading it printed a warning in debug runs.
|
|
103
148
|
if self._templar is None:
|
|
104
|
-
from
|
|
149
|
+
from jinja2.sandbox import ImmutableSandboxedEnvironment
|
|
105
150
|
|
|
106
|
-
self._templar =
|
|
107
|
-
|
|
151
|
+
self._templar = ImmutableSandboxedEnvironment(
|
|
152
|
+
extensions=["jinja2.ext.loopcontrols", "jinja2.ext.do"]
|
|
153
|
+
)
|
|
154
|
+
return self._templar
|
|
108
155
|
|
|
109
156
|
# ---- requests --------------------------------------------------------------------------
|
|
110
157
|
def serve(self, folder: str) -> int:
|
|
@@ -197,18 +244,33 @@ class Gate:
|
|
|
197
244
|
e["value"] = value
|
|
198
245
|
return e
|
|
199
246
|
|
|
200
|
-
def
|
|
201
|
-
"""The expression reads a
|
|
202
|
-
|
|
247
|
+
def _masked_row(self, host: str, expr: str) -> dict | None:
|
|
248
|
+
"""The answer for an expression that reads a masked value: masked whole, with the kind
|
|
249
|
+
of what it reads (a filter's result keeps it: reverse, list, length, hash, ==)."""
|
|
250
|
+
try:
|
|
251
|
+
why = self.masked_by(host, expr)
|
|
252
|
+
except TooMany:
|
|
253
|
+
return {
|
|
254
|
+
"host": host,
|
|
255
|
+
"expr": expr,
|
|
256
|
+
"error": (
|
|
257
|
+
f"hostvars with a host chosen at run time is not evaluated in an inventory "
|
|
258
|
+
f"of more than {MAX_HOSTS} hosts: name the host"
|
|
259
|
+
),
|
|
260
|
+
"refused": True,
|
|
261
|
+
}
|
|
262
|
+
if why:
|
|
263
|
+
return {"host": host, "expr": expr, "type": "masked", "masked": why}
|
|
264
|
+
return None
|
|
203
265
|
|
|
204
266
|
def evaluate(self, host: str, expr: str, timeout: object = None) -> dict:
|
|
205
267
|
refused = render.precheck(expr, self.environment())
|
|
206
268
|
if refused:
|
|
207
|
-
return {"host": host, "expr": expr,
|
|
208
|
-
if self._nolog_in(expr):
|
|
209
|
-
return {"host": host, "expr": expr, "type": "masked", "masked": "no_log"}
|
|
269
|
+
return {"host": host, "expr": expr, **render.refusal(refused)}
|
|
210
270
|
# The plain texts of this host's vaulted values are learned here, before the child.
|
|
211
|
-
self.
|
|
271
|
+
masked = self._masked_row(host, expr)
|
|
272
|
+
if masked:
|
|
273
|
+
return masked
|
|
212
274
|
target = self.hosts[host]
|
|
213
275
|
|
|
214
276
|
def work() -> object:
|
|
@@ -227,9 +289,7 @@ class Gate:
|
|
|
227
289
|
hosts = [str(h) for h in (req.get("hosts") or list(self.hosts)) if str(h) in self.hosts]
|
|
228
290
|
env = self.environment()
|
|
229
291
|
refused = {e: render.precheck(e, env) for e in exprs}
|
|
230
|
-
|
|
231
|
-
for h in hosts:
|
|
232
|
-
self.view(h)
|
|
292
|
+
masked = {(h, e): self._masked_row(h, e) for h in hosts for e in exprs if not refused[e]}
|
|
233
293
|
targets = {h: self.hosts[h] for h in hosts}
|
|
234
294
|
|
|
235
295
|
def work() -> object:
|
|
@@ -238,10 +298,10 @@ class Gate:
|
|
|
238
298
|
templar = self._templar_for(target)
|
|
239
299
|
for e in exprs:
|
|
240
300
|
if refused[e]:
|
|
241
|
-
rows.append({"host": h, "expr": e,
|
|
301
|
+
rows.append({"host": h, "expr": e, **render.refusal(refused[e])})
|
|
242
302
|
continue
|
|
243
|
-
if
|
|
244
|
-
rows.append(
|
|
303
|
+
if masked.get((h, e)):
|
|
304
|
+
rows.append(masked[(h, e)])
|
|
245
305
|
continue
|
|
246
306
|
try:
|
|
247
307
|
value = templar.evaluate_expression(render.trusted(e))
|
|
@@ -272,6 +332,13 @@ def point_settings(point: Mapping) -> dict:
|
|
|
272
332
|
return out
|
|
273
333
|
|
|
274
334
|
|
|
335
|
+
def _masked_by(gate: Gate, host: str, text: str, template: bool = False) -> str | None:
|
|
336
|
+
try:
|
|
337
|
+
return gate.masked_by(host, text, template=template)
|
|
338
|
+
except TooMany:
|
|
339
|
+
return "name" # hostvars by a host chosen at run time in a large inventory: not shown
|
|
340
|
+
|
|
341
|
+
|
|
275
342
|
def at_point(session: Session, strategy, play, hosts: list, node: str, point: Mapping) -> dict:
|
|
276
343
|
"""A pause point's settings at its gate, for every host:
|
|
277
344
|
- condition: Jinja per host; all hosts pause if any matches (the matched hosts are named);
|
|
@@ -288,10 +355,31 @@ def at_point(session: Session, strategy, play, hosts: list, node: str, point: Ma
|
|
|
288
355
|
if cond or log:
|
|
289
356
|
gate = Gate(session, strategy, play, hosts, "")
|
|
290
357
|
env = gate.environment()
|
|
291
|
-
bad_cond = render.precheck(cond, env) if cond else None
|
|
292
|
-
bad_log = render.check_template(log, env) if log else None
|
|
293
|
-
|
|
358
|
+
bad_cond = render.precheck(cond, env, "a condition") if cond else None
|
|
359
|
+
bad_log = render.check_template(log, env, "a log message") if log else None
|
|
360
|
+
# Before the child: the vaulted plain texts are learned, and what each host's condition
|
|
361
|
+
# and message read is checked (AFD-373). A condition that reads a masked value is not
|
|
362
|
+
# checked (true or false would tell its value); in a message, each {{ }} that reads one
|
|
363
|
+
# is masked (a {% %} that reads one masks the whole message).
|
|
364
|
+
taint: dict[str, dict] = {}
|
|
365
|
+
for h in names:
|
|
294
366
|
gate.view(h)
|
|
367
|
+
row: dict = {}
|
|
368
|
+
if cond and not bad_cond:
|
|
369
|
+
why = _masked_by(gate, h, cond)
|
|
370
|
+
if why:
|
|
371
|
+
row["cond"] = why
|
|
372
|
+
if log and not bad_log:
|
|
373
|
+
whole = _masked_by(gate, h, log, template=True)
|
|
374
|
+
if whole:
|
|
375
|
+
text, kinds = mask_blocks(
|
|
376
|
+
env,
|
|
377
|
+
log,
|
|
378
|
+
lambda e, h=h, whole=whole: _masked_by(gate, h, e) if e else whole,
|
|
379
|
+
)
|
|
380
|
+
row["log"] = text
|
|
381
|
+
row["kinds"] = sorted(kinds or {whole})
|
|
382
|
+
taint[h] = row
|
|
295
383
|
masker = session.masker
|
|
296
384
|
|
|
297
385
|
def work() -> object:
|
|
@@ -299,15 +387,27 @@ def at_point(session: Session, strategy, play, hosts: list, node: str, point: Ma
|
|
|
299
387
|
for h in hosts:
|
|
300
388
|
templar = gate._templar_for(h)
|
|
301
389
|
row: dict = {}
|
|
302
|
-
|
|
390
|
+
masked = taint.get(h.get_name(), {})
|
|
391
|
+
if cond and not bad_cond and masked.get("cond"):
|
|
392
|
+
row["cond"] = (
|
|
393
|
+
f"The condition reads a masked value ({masked['cond']}): it is not checked"
|
|
394
|
+
)
|
|
395
|
+
elif cond and not bad_cond:
|
|
303
396
|
try:
|
|
304
397
|
row["cond"] = bool(templar.evaluate_conditional(render.trusted(cond)))
|
|
305
398
|
except Exception as ex: # noqa: BLE001
|
|
306
399
|
row["cond"] = render.error_text(ex)
|
|
307
400
|
if log and not bad_log and row.get("cond", True) is True:
|
|
308
401
|
try:
|
|
309
|
-
|
|
402
|
+
# A message that reads masked values renders with those parts masked
|
|
403
|
+
# (None: masked whole).
|
|
404
|
+
source = masked.get("log", log)
|
|
405
|
+
if source is None:
|
|
406
|
+
value: object = REDACTED
|
|
407
|
+
else:
|
|
408
|
+
value = templar.template(render.trusted(source))
|
|
310
409
|
text, kinds = masker.scrub(str(value), value)
|
|
410
|
+
kinds |= set(masked.get("kinds") or [])
|
|
311
411
|
row["log"] = text
|
|
312
412
|
if kinds:
|
|
313
413
|
row["masked"] = sorted(kinds)
|
package/probe/afd_lib/mask.py
CHANGED
|
@@ -248,6 +248,12 @@ class Masker:
|
|
|
248
248
|
"""Why `value` under `name` is masked whole, or None."""
|
|
249
249
|
if is_vaulted(value) or self.from_vault_file(value):
|
|
250
250
|
return "vault"
|
|
251
|
+
# A known value (external, credential, vault) says what it truly is, also under a
|
|
252
|
+
# secret-looking name: a provider's ansible_password reads "external", not "name".
|
|
253
|
+
if isinstance(value, str):
|
|
254
|
+
known = self.known.find(str.__str__(value))
|
|
255
|
+
if known:
|
|
256
|
+
return known
|
|
251
257
|
if name and SECRET_NAME.search(str(name)):
|
|
252
258
|
return "name"
|
|
253
259
|
if isinstance(value, Mapping) and not _is_hostvars(value):
|
|
@@ -256,8 +262,6 @@ class Masker:
|
|
|
256
262
|
return "no_log"
|
|
257
263
|
except Exception: # noqa: BLE001
|
|
258
264
|
return None
|
|
259
|
-
if isinstance(value, str):
|
|
260
|
-
return self.known.find(str.__str__(value))
|
|
261
265
|
return None
|
|
262
266
|
|
|
263
267
|
def mask(self, name: str, value: object, depth: int = 0) -> object:
|
package/probe/afd_lib/render.py
CHANGED
|
@@ -42,37 +42,102 @@ def _short(name: object) -> str:
|
|
|
42
42
|
return str(name).rsplit(".", 1)[-1]
|
|
43
43
|
|
|
44
44
|
|
|
45
|
-
def precheck(expr: str, environment) -> str | None:
|
|
46
|
-
"""Why `expr` is refused before anything renders it, in plain words; None when it may run.
|
|
45
|
+
def precheck(expr: str, environment, where: str = "Evaluate") -> str | None:
|
|
46
|
+
"""Why `expr` is refused before anything renders it, in plain words; None when it may run.
|
|
47
|
+
`where` names what refuses it ("Evaluate", "a condition")."""
|
|
47
48
|
if not expr.strip():
|
|
48
49
|
return "Nothing to evaluate"
|
|
49
50
|
if len(expr) > EXPR_LIMIT:
|
|
50
51
|
return f"The expression is longer than {EXPR_LIMIT} characters"
|
|
51
52
|
if any(m in expr for m in ("{{", "}}", "{%", "%}", "{#", "#}")):
|
|
52
53
|
return "Write an expression without {{ }} or {% %}"
|
|
53
|
-
|
|
54
|
+
unclosed = not_closed(expr)
|
|
55
|
+
if unclosed:
|
|
56
|
+
return unclosed
|
|
57
|
+
return check_template("{{ " + expr + " }}", environment, where, expression=True)
|
|
54
58
|
|
|
55
59
|
|
|
56
|
-
def
|
|
57
|
-
"""
|
|
60
|
+
def refusal(text: str) -> dict:
|
|
61
|
+
"""A precheck's answer: refused (a lookup, a vault filter, a name starting with _: what
|
|
62
|
+
Evaluate does not allow), or an error (a bracket or quote not closed, not Jinja: the
|
|
63
|
+
expression is not finished, nothing was refused)."""
|
|
64
|
+
return {"error": text, "refused": True} if "not allowed" in text else {"error": text}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
PAIRS = {"(": ")", "[": "]", "{": "}"}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def not_closed(expr: str) -> str | None:
|
|
71
|
+
"""A bracket or quote the expression opens and never closes (or closes without opening), in
|
|
72
|
+
words: Jinja's own error names the `}}` the expression is wrapped in, never typed."""
|
|
73
|
+
stack: list[str] = []
|
|
74
|
+
quote = ""
|
|
75
|
+
escaped = False
|
|
76
|
+
for ch in expr:
|
|
77
|
+
if quote:
|
|
78
|
+
if escaped:
|
|
79
|
+
escaped = False
|
|
80
|
+
elif ch == "\\":
|
|
81
|
+
escaped = True
|
|
82
|
+
elif ch == quote:
|
|
83
|
+
quote = ""
|
|
84
|
+
continue
|
|
85
|
+
if ch in ("'", '"'):
|
|
86
|
+
quote = ch
|
|
87
|
+
elif ch in PAIRS:
|
|
88
|
+
stack.append(ch)
|
|
89
|
+
elif ch in PAIRS.values():
|
|
90
|
+
if not stack or PAIRS[stack[-1]] != ch:
|
|
91
|
+
return f"A {ch} has no opening bracket before it"
|
|
92
|
+
stack.pop()
|
|
93
|
+
if quote:
|
|
94
|
+
return f"A quote ({quote}) is not closed"
|
|
95
|
+
if stack:
|
|
96
|
+
return f"A bracket ({stack[-1]}) is not closed"
|
|
97
|
+
return None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _syntax(ex: BaseException, expression: bool) -> str:
|
|
101
|
+
"""Jinja's syntax error in plain words, without the parser's own terms."""
|
|
102
|
+
text = (str(ex).strip().splitlines() or [""])[0]
|
|
103
|
+
if expression:
|
|
104
|
+
text = (
|
|
105
|
+
text.replace("expected token 'end of print statement'", "expected the end")
|
|
106
|
+
.replace("'end of print statement'", "the end")
|
|
107
|
+
.replace("unexpected '}'", "unexpected end")
|
|
108
|
+
.replace("unexpected end of template", "unexpected end")
|
|
109
|
+
)
|
|
110
|
+
return text[:300]
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def check_template(
|
|
114
|
+
text: str, environment, where: str = "a log message", expression: bool = False
|
|
115
|
+
) -> str | None:
|
|
116
|
+
"""Why a template (a log message, an expression in braces) is refused; None when it may run.
|
|
117
|
+
`where` names what refuses it, in the words: "lookups are not allowed in Evaluate"."""
|
|
58
118
|
try:
|
|
59
119
|
from jinja2 import nodes
|
|
60
120
|
|
|
61
121
|
ast = environment.parse(text)
|
|
62
122
|
except Exception as ex: # noqa: BLE001
|
|
63
|
-
|
|
123
|
+
what = "Not a Jinja expression" if expression else "Not a Jinja template"
|
|
124
|
+
return f"{what}: {_syntax(ex, expression)}"
|
|
125
|
+
lookups = f"lookups are not allowed in {where}: they can read files or run commands"
|
|
64
126
|
for call in ast.find_all(nodes.Call):
|
|
65
127
|
if isinstance(call.node, nodes.Name) and call.node.name in LOOKUP_CALLS:
|
|
66
|
-
return f"{call.node.name}()
|
|
128
|
+
return f"{call.node.name}(): {lookups}"
|
|
67
129
|
for name in ast.find_all(nodes.Name):
|
|
68
130
|
if name.name in LOOKUP_CALLS:
|
|
69
|
-
return f"{name.name}
|
|
131
|
+
return f"{name.name}: {lookups}"
|
|
70
132
|
for f in ast.find_all(nodes.Filter):
|
|
71
133
|
if _short(f.name) in FILTER_DENY:
|
|
72
|
-
return f"The {f.name} filter is not allowed
|
|
134
|
+
return f"The {f.name} filter is not allowed in {where}"
|
|
73
135
|
for attr in ast.find_all(nodes.Getattr):
|
|
74
136
|
if str(attr.attr).startswith("_"):
|
|
75
|
-
return "Attributes starting with _ are not allowed
|
|
137
|
+
return f"Attributes starting with _ are not allowed in {where}"
|
|
138
|
+
for name in ast.find_all(nodes.Name):
|
|
139
|
+
if str(name.name).startswith("_"):
|
|
140
|
+
return f"Names starting with _ are not allowed in {where}"
|
|
76
141
|
return None
|
|
77
142
|
|
|
78
143
|
|
|
@@ -97,7 +162,9 @@ def block_lookups() -> None:
|
|
|
97
162
|
class _Guard:
|
|
98
163
|
def get(self, name, *a, **kw):
|
|
99
164
|
if _short(name) not in LOOKUP_ALLOW:
|
|
100
|
-
raise Blocked(
|
|
165
|
+
raise Blocked(
|
|
166
|
+
f"lookups are not allowed while debugging (a variable runs lookup {name!r})"
|
|
167
|
+
)
|
|
101
168
|
return real.get(name, *a, **kw)
|
|
102
169
|
|
|
103
170
|
def __getattr__(self, attr):
|
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
# Taint by reference (ADR-0040 §4, AFD-373): an expression or a template that reads a masked value
|
|
2
|
+
# is masked whole, before anything renders it. Matching the result's text (mask.py, check 5) misses
|
|
3
|
+
# a value a filter changed (reverse, list, slices, length, hash, comparisons); what the expression
|
|
4
|
+
# reads does not change.
|
|
5
|
+
#
|
|
6
|
+
# The Jinja AST gives each variable read as a root name and a path of constant keys
|
|
7
|
+
# (`creds.password`, `hostvars['h2'].x`, `x[0]`). The value at the deepest part of the path that
|
|
8
|
+
# exists is checked whole, with everything inside it: a masked part anywhere masks the result.
|
|
9
|
+
# - A part of the path chosen at run time (`x[k]`, a slice) stops the path there: the value before
|
|
10
|
+
# it is checked whole.
|
|
11
|
+
# - `hostvars` with a host chosen at run time checks that path on every host of the inventory;
|
|
12
|
+
# `hostvars` or `vars` with no path checks every variable.
|
|
13
|
+
# - A value that is a template (a raw inventory or play variable) is checked by what it reads.
|
|
14
|
+
# - Magic variables (groups, inventory_hostname, ...) hold names and settings, not secrets.
|
|
15
|
+
# Only raw values are read here (variable_manager.get_vars): nothing is rendered, no lookup runs.
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import re
|
|
19
|
+
from collections.abc import Callable, Mapping
|
|
20
|
+
|
|
21
|
+
from .capture import MAGIC
|
|
22
|
+
from .mask import Masker, _is_hostvars
|
|
23
|
+
|
|
24
|
+
DYN = object() # a part of a path chosen at run time
|
|
25
|
+
DEPTH = 40
|
|
26
|
+
TEMPLATE_DEPTH = 8
|
|
27
|
+
# `hostvars[<a host chosen at run time>]` is checked on every host up to this many.
|
|
28
|
+
MAX_HOSTS = 300
|
|
29
|
+
# Roots read as the variables of a host.
|
|
30
|
+
ROOTS = ("hostvars", "vars")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class TooMany(Exception):
|
|
34
|
+
"""A hostvars lookup by a host chosen at run time, in an inventory too large to check."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _constant(node) -> object:
|
|
38
|
+
"""A key written as constants joined (`'db' ~ '_password'`, `'a' + 'b'`): its value; DYN for a
|
|
39
|
+
key chosen at run time. So `vars['db' ~ '_password']` reads that variable, with its reason."""
|
|
40
|
+
from jinja2 import nodes
|
|
41
|
+
|
|
42
|
+
if isinstance(node, nodes.Const):
|
|
43
|
+
v = node.value
|
|
44
|
+
return v if isinstance(v, (str, int)) and not isinstance(v, bool) else DYN
|
|
45
|
+
if isinstance(node, nodes.Concat):
|
|
46
|
+
parts = [_constant(n) for n in node.nodes]
|
|
47
|
+
return DYN if any(p is DYN for p in parts) else "".join(str(p) for p in parts)
|
|
48
|
+
if isinstance(node, nodes.Add):
|
|
49
|
+
left, right = _constant(node.left), _constant(node.right)
|
|
50
|
+
if isinstance(left, str) and isinstance(right, str):
|
|
51
|
+
return left + right
|
|
52
|
+
return DYN
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _chain(node) -> tuple[str, list] | None:
|
|
56
|
+
"""(root name, keys) of a chain of names, attributes and items; None for anything else."""
|
|
57
|
+
from jinja2 import nodes
|
|
58
|
+
|
|
59
|
+
keys: list = []
|
|
60
|
+
while True:
|
|
61
|
+
if isinstance(node, nodes.Getattr):
|
|
62
|
+
keys.append(node.attr)
|
|
63
|
+
node = node.node
|
|
64
|
+
elif isinstance(node, nodes.Getitem):
|
|
65
|
+
keys.append(_constant(node.arg))
|
|
66
|
+
node = node.node
|
|
67
|
+
elif isinstance(node, nodes.Name):
|
|
68
|
+
keys.reverse()
|
|
69
|
+
return str(node.name), keys
|
|
70
|
+
else:
|
|
71
|
+
return None
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def references(ast) -> tuple[list[tuple[str, list]], list[str]]:
|
|
75
|
+
"""Every variable an AST reads, as (root, keys), and the string constants that are templates."""
|
|
76
|
+
from jinja2 import nodes
|
|
77
|
+
|
|
78
|
+
refs: list[tuple[str, list]] = []
|
|
79
|
+
texts: list[str] = []
|
|
80
|
+
|
|
81
|
+
def visit(node) -> None:
|
|
82
|
+
if isinstance(node, (nodes.Getattr, nodes.Getitem, nodes.Name)):
|
|
83
|
+
chain = _chain(node)
|
|
84
|
+
if chain is not None:
|
|
85
|
+
if not (isinstance(node, nodes.Name) and node.ctx != "load"):
|
|
86
|
+
refs.append(chain)
|
|
87
|
+
# The keys chosen at run time read variables of their own.
|
|
88
|
+
n = node
|
|
89
|
+
while isinstance(n, (nodes.Getattr, nodes.Getitem)):
|
|
90
|
+
if isinstance(n, nodes.Getitem):
|
|
91
|
+
visit(n.arg)
|
|
92
|
+
n = n.node
|
|
93
|
+
return
|
|
94
|
+
if (
|
|
95
|
+
isinstance(node, nodes.Const)
|
|
96
|
+
and isinstance(node.value, str)
|
|
97
|
+
and ("{{" in node.value or "{%" in node.value)
|
|
98
|
+
):
|
|
99
|
+
texts.append(node.value)
|
|
100
|
+
for child in node.iter_child_nodes():
|
|
101
|
+
visit(child)
|
|
102
|
+
|
|
103
|
+
visit(ast)
|
|
104
|
+
return refs, texts
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class Taint:
|
|
108
|
+
"""What a host's expression reads, checked against the masking. One per pause and host."""
|
|
109
|
+
|
|
110
|
+
def __init__(
|
|
111
|
+
self,
|
|
112
|
+
masker: Masker,
|
|
113
|
+
environment,
|
|
114
|
+
variables: Callable[[str], Mapping | None],
|
|
115
|
+
inventory_hosts: Callable[[], list[str]],
|
|
116
|
+
host: str,
|
|
117
|
+
*,
|
|
118
|
+
nolog: set[str] | None = None,
|
|
119
|
+
secret: set[str] | None = None,
|
|
120
|
+
) -> None:
|
|
121
|
+
self.masker = masker
|
|
122
|
+
self.environment = environment
|
|
123
|
+
self.variables = variables
|
|
124
|
+
self.inventory_hosts = inventory_hosts
|
|
125
|
+
self.host = host
|
|
126
|
+
self.nolog = nolog or set()
|
|
127
|
+
self.secret = secret or set()
|
|
128
|
+
self._templates: set[str] = set()
|
|
129
|
+
|
|
130
|
+
# ---- entry points ----------------------------------------------------------------------
|
|
131
|
+
def expression(self, expr: str) -> str | None:
|
|
132
|
+
"""Why the result of `expr` (no braces) is masked whole, or None."""
|
|
133
|
+
return self.template("{{ " + expr + " }}")
|
|
134
|
+
|
|
135
|
+
def template(self, text: str, depth: int = 0) -> str | None:
|
|
136
|
+
"""Why the rendering of `text` is masked whole, or None. An AST that does not parse reads
|
|
137
|
+
nothing here (the render fails on its own)."""
|
|
138
|
+
if depth > TEMPLATE_DEPTH:
|
|
139
|
+
return None
|
|
140
|
+
try:
|
|
141
|
+
ast = self.environment.parse(text)
|
|
142
|
+
except Exception: # noqa: BLE001
|
|
143
|
+
return None
|
|
144
|
+
refs, texts = references(ast)
|
|
145
|
+
own = self.variables(self.host) or {}
|
|
146
|
+
for root, keys in refs:
|
|
147
|
+
why = self._root(own, root, keys, depth)
|
|
148
|
+
if why:
|
|
149
|
+
return why
|
|
150
|
+
for t in texts:
|
|
151
|
+
why = self._text(t, depth + 1)
|
|
152
|
+
if why:
|
|
153
|
+
return why
|
|
154
|
+
return None
|
|
155
|
+
|
|
156
|
+
# ---- a reference -----------------------------------------------------------------------
|
|
157
|
+
def _root(self, own: Mapping, root: str, keys: list, depth: int) -> str | None:
|
|
158
|
+
if root == "hostvars":
|
|
159
|
+
return self._hostvars(keys, depth)
|
|
160
|
+
if root == "vars":
|
|
161
|
+
return self._in_vars(own, keys, depth, whole=True)
|
|
162
|
+
return self._in_vars(own, [root, *keys], depth)
|
|
163
|
+
|
|
164
|
+
def _hostvars(self, keys: list, depth: int) -> str | None:
|
|
165
|
+
first = keys[0] if keys else DYN
|
|
166
|
+
known = self.inventory_hosts()
|
|
167
|
+
if first is not DYN and str(first) in known:
|
|
168
|
+
hosts, rest = [str(first)], keys[1:]
|
|
169
|
+
else:
|
|
170
|
+
# A host chosen at run time, or no host at all (`hostvars | dict2items`, `.values()`).
|
|
171
|
+
if len(known) > MAX_HOSTS:
|
|
172
|
+
raise TooMany
|
|
173
|
+
hosts, rest = known, (keys[1:] if keys else [])
|
|
174
|
+
for h in hosts:
|
|
175
|
+
hv = self.variables(h)
|
|
176
|
+
if hv is None:
|
|
177
|
+
continue
|
|
178
|
+
why = self._in_vars(hv, rest, depth, host=h, whole=True)
|
|
179
|
+
if why:
|
|
180
|
+
return why
|
|
181
|
+
return None
|
|
182
|
+
|
|
183
|
+
def _in_vars(
|
|
184
|
+
self,
|
|
185
|
+
all_vars: Mapping,
|
|
186
|
+
keys: list,
|
|
187
|
+
depth: int,
|
|
188
|
+
host: str | None = None,
|
|
189
|
+
whole: bool = False,
|
|
190
|
+
) -> str | None:
|
|
191
|
+
"""A path into a host's variables: its first key is a variable's name. A name the host
|
|
192
|
+
does not have reads nothing (undefined, or a Jinja global such as range), unless the path
|
|
193
|
+
is inside `vars` or `hostvars[h]` (`whole`): there it is a method or a lookup by a name
|
|
194
|
+
chosen at run time (`vars.values()`, `vars[k]`), and every variable is checked."""
|
|
195
|
+
if not keys or keys[0] is DYN or str(keys[0]) not in all_vars:
|
|
196
|
+
if not whole and keys and keys[0] is not DYN:
|
|
197
|
+
return None
|
|
198
|
+
for name, value in all_vars.items():
|
|
199
|
+
why = self._variable(str(name), value, [], depth, host)
|
|
200
|
+
if why:
|
|
201
|
+
return why
|
|
202
|
+
return None
|
|
203
|
+
name = str(keys[0])
|
|
204
|
+
return self._variable(name, all_vars[name], keys[1:], depth, host)
|
|
205
|
+
|
|
206
|
+
def _variable(
|
|
207
|
+
self, name: str, value: object, keys: list, depth: int, host: str | None
|
|
208
|
+
) -> str | None:
|
|
209
|
+
if name in MAGIC and name not in ROOTS:
|
|
210
|
+
return None
|
|
211
|
+
if name in ROOTS:
|
|
212
|
+
return None # the lazy objects themselves (2.19's `vars` is every variable again)
|
|
213
|
+
if name in self.nolog:
|
|
214
|
+
return "no_log"
|
|
215
|
+
if name in self.secret:
|
|
216
|
+
return "credential"
|
|
217
|
+
# A secret-looking name is the weakest reason: a vaulted, credential, external or no_log
|
|
218
|
+
# value at or inside it says what it truly is (AFS-252).
|
|
219
|
+
why = self.masker.kind(name, value)
|
|
220
|
+
if why and why != "name":
|
|
221
|
+
return why
|
|
222
|
+
weak = why
|
|
223
|
+
for key in keys:
|
|
224
|
+
if key is DYN:
|
|
225
|
+
break
|
|
226
|
+
if isinstance(value, Mapping) and not _is_hostvars(value) and key in value:
|
|
227
|
+
name, value = str(key), value[key]
|
|
228
|
+
elif (
|
|
229
|
+
isinstance(value, (list, tuple))
|
|
230
|
+
and isinstance(key, int)
|
|
231
|
+
and -len(value) <= key < len(value)
|
|
232
|
+
):
|
|
233
|
+
name, value = "", value[key]
|
|
234
|
+
else:
|
|
235
|
+
break # an attribute of a value (a method, a missing key): the value is read
|
|
236
|
+
why = self.masker.kind(name, value)
|
|
237
|
+
if why and why != "name":
|
|
238
|
+
return why
|
|
239
|
+
weak = weak or why
|
|
240
|
+
inner = self._inside(value, 0, depth, host)
|
|
241
|
+
return inner if inner and inner != "name" else (weak or inner)
|
|
242
|
+
|
|
243
|
+
def _inside(self, value: object, level: int, depth: int, host: str | None) -> str | None:
|
|
244
|
+
"""A masked part anywhere inside `value`, or a template there that reads one; a
|
|
245
|
+
secret-looking name only when nothing stronger is found."""
|
|
246
|
+
if level > DEPTH:
|
|
247
|
+
return None
|
|
248
|
+
weak = None
|
|
249
|
+
parts: list[tuple[str, object]] = []
|
|
250
|
+
if isinstance(value, Mapping):
|
|
251
|
+
if _is_hostvars(value):
|
|
252
|
+
return None
|
|
253
|
+
parts = [(str(k), v) for k, v in value.items()]
|
|
254
|
+
elif isinstance(value, (list, tuple, set, frozenset)):
|
|
255
|
+
parts = [("", v) for v in value]
|
|
256
|
+
elif isinstance(value, str):
|
|
257
|
+
text = str.__str__(value)
|
|
258
|
+
if "{{" in text or "{%" in text:
|
|
259
|
+
return self._text(text, depth + 1, host)
|
|
260
|
+
return None
|
|
261
|
+
for k, v in parts:
|
|
262
|
+
for why in (self.masker.kind(k, v), self._inside(v, level + 1, depth, host)):
|
|
263
|
+
if why and why != "name":
|
|
264
|
+
return why
|
|
265
|
+
weak = weak or why
|
|
266
|
+
return weak
|
|
267
|
+
|
|
268
|
+
def _text(self, text: str, depth: int, host: str | None = None) -> str | None:
|
|
269
|
+
"""A template inside a value: what it reads, as the host that has it."""
|
|
270
|
+
key = f"{host or self.host}\0{text}"
|
|
271
|
+
if key in self._templates or depth > TEMPLATE_DEPTH:
|
|
272
|
+
return None
|
|
273
|
+
self._templates.add(key)
|
|
274
|
+
if host is None or host == self.host:
|
|
275
|
+
return self.template(text, depth)
|
|
276
|
+
other = Taint(
|
|
277
|
+
self.masker,
|
|
278
|
+
self.environment,
|
|
279
|
+
self.variables,
|
|
280
|
+
self.inventory_hosts,
|
|
281
|
+
host,
|
|
282
|
+
nolog=self.nolog,
|
|
283
|
+
secret=self.secret,
|
|
284
|
+
)
|
|
285
|
+
other._templates = self._templates
|
|
286
|
+
return other.template(text, depth)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def mask_blocks(
|
|
290
|
+
environment, text: str, why: Callable[[str], str | None]
|
|
291
|
+
) -> tuple[str | None, set[str]]:
|
|
292
|
+
"""A log message with each `{{ ... }}` that reads a masked value replaced by the mask, so the
|
|
293
|
+
rest still renders ("sw-01 cred=********"); `why(expr)` says why an expression is masked.
|
|
294
|
+
Returns (the template to render, the kinds), or (None, kinds) when the message is masked
|
|
295
|
+
whole: a `{% ... %}` that reads a masked value, or a template the lexer cannot read."""
|
|
296
|
+
from .mask import REDACTED
|
|
297
|
+
|
|
298
|
+
try:
|
|
299
|
+
tokens = list(environment.lex(text))
|
|
300
|
+
except Exception: # noqa: BLE001
|
|
301
|
+
return None, {"name"}
|
|
302
|
+
out: list[str] = []
|
|
303
|
+
kinds: set[str] = set()
|
|
304
|
+
block: list[tuple[str, str]] | None = None
|
|
305
|
+
for _line, kind, value in tokens:
|
|
306
|
+
if kind in ("variable_begin", "block_begin"):
|
|
307
|
+
block = [(kind, value)]
|
|
308
|
+
continue
|
|
309
|
+
if block is None:
|
|
310
|
+
out.append(value)
|
|
311
|
+
continue
|
|
312
|
+
block.append((kind, value))
|
|
313
|
+
if kind not in ("variable_end", "block_end"):
|
|
314
|
+
continue
|
|
315
|
+
source = "".join(v for _k, v in block)
|
|
316
|
+
inner = "".join(v for _k, v in block[1:-1])
|
|
317
|
+
opened = block[0][0]
|
|
318
|
+
block = None
|
|
319
|
+
if opened == "block_begin":
|
|
320
|
+
# A statement (for, if, set): what it reads shapes the whole message.
|
|
321
|
+
found = why_statement(inner, why)
|
|
322
|
+
if found:
|
|
323
|
+
return None, {found}
|
|
324
|
+
out.append(source)
|
|
325
|
+
continue
|
|
326
|
+
found = why(inner)
|
|
327
|
+
if found:
|
|
328
|
+
kinds.add(found)
|
|
329
|
+
out.append(REDACTED)
|
|
330
|
+
else:
|
|
331
|
+
out.append(source)
|
|
332
|
+
if block is not None: # not closed: the render reports the error
|
|
333
|
+
out.extend(v for _k, v in block)
|
|
334
|
+
return "".join(out), kinds
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
# Statements that read no expression.
|
|
338
|
+
QUIET = {"else", "endif", "endfor", "endset", "raw", "endraw", "endfilter", "endwith", "endcall"}
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def why_statement(inner: str, why: Callable[[str], str | None]) -> str | None:
|
|
342
|
+
"""A `{% ... %}` statement's expression: `if <expr>`, `for x in <expr>`, `set x = <expr>`.
|
|
343
|
+
Any other statement (with, macro, call, filter) masks the message when the message as a whole
|
|
344
|
+
reads a masked value (`why` of an empty expression is that kind)."""
|
|
345
|
+
text = inner.strip().lstrip("-+").rstrip("-+").strip()
|
|
346
|
+
word = text.split(None, 1)[0] if text else ""
|
|
347
|
+
if word in QUIET:
|
|
348
|
+
return None
|
|
349
|
+
m = re.match(r"(?:el)?if\s+(.*)$|for\s+.+?\s+in\s+(.*)$|set\s+[^=]+=\s*(.*)$", text, re.S)
|
|
350
|
+
if m is None:
|
|
351
|
+
return why("")
|
|
352
|
+
expr = next(g for g in m.groups() if g is not None)
|
|
353
|
+
# `for x in items if cond`, `... recursive`: the whole tail is read.
|
|
354
|
+
return why(expr.removesuffix(" recursive"))
|
|
@@ -46,6 +46,31 @@ DOCUMENTATION = """
|
|
|
46
46
|
|
|
47
47
|
display = Display()
|
|
48
48
|
|
|
49
|
+
# ansible-core 2.19+ calls every strategy outside ansible.builtin deprecated, with no replacement
|
|
50
|
+
# planned, on each play of a step-by-step or debug run. This plugin is the linear strategy with
|
|
51
|
+
# pauses, and the warning tells the person running a flow nothing they can act on, so that one
|
|
52
|
+
# message is dropped (Display is one object per process; the loader warns right after it imports
|
|
53
|
+
# this module). Every other deprecation warning still shows.
|
|
54
|
+
_THIRD_PARTY_STRATEGY = "Use of strategy plugins not included in ansible.builtin are deprecated"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _quiet_strategy_deprecation() -> None:
|
|
58
|
+
if getattr(display, "_afd_quiet", False):
|
|
59
|
+
return
|
|
60
|
+
warn = display.deprecated
|
|
61
|
+
|
|
62
|
+
def deprecated(*args, **kwargs):
|
|
63
|
+
msg = kwargs.get("msg", args[0] if args else "")
|
|
64
|
+
if isinstance(msg, str) and msg.startswith(_THIRD_PARTY_STRATEGY):
|
|
65
|
+
return None
|
|
66
|
+
return warn(*args, **kwargs)
|
|
67
|
+
|
|
68
|
+
display.deprecated = deprecated
|
|
69
|
+
display._afd_quiet = True
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
_quiet_strategy_deprecation()
|
|
73
|
+
|
|
49
74
|
|
|
50
75
|
def _paused_line(play: str, hosts: int) -> str:
|
|
51
76
|
"""The terminal's line for a pause: the step's title without its [key], the hosts waiting."""
|
|
@@ -54,10 +79,23 @@ def _paused_line(play: str, hosts: int) -> str:
|
|
|
54
79
|
return f"Paused before {title}: {waits} for Step, Continue or Stop"
|
|
55
80
|
|
|
56
81
|
|
|
57
|
-
def _failed_line(play: str, failed: int) -> str:
|
|
82
|
+
def _failed_line(play: str, failed: int, hosts: int, attempt: int) -> str:
|
|
83
|
+
title = re.sub(r"^\[[^\]]*\]\s*", "", play) or play
|
|
84
|
+
of = f"{failed} of {hosts} hosts" if hosts > 1 else "1 host"
|
|
85
|
+
return f"Paused after {title}: {of} failed (attempt {attempt}): Retry, Continue or Stop"
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _log_line(play: str, event: dict) -> str | None:
|
|
89
|
+
"""A log point's line in the run's output (ADR-0040 §6): masked as the event is."""
|
|
58
90
|
title = re.sub(r"^\[[^\]]*\]\s*", "", play) or play
|
|
59
|
-
|
|
60
|
-
|
|
91
|
+
host = event.get("host")
|
|
92
|
+
where = f"{title} · {host}" if host else title
|
|
93
|
+
if "message" in event:
|
|
94
|
+
return f"Log point {where}: {event['message']}"[:2000]
|
|
95
|
+
if event.get("error"):
|
|
96
|
+
what = {"condition": "condition", "log": "log message"}.get(event.get("source"), "point")
|
|
97
|
+
return f"Log point {where}: the {what} failed: {event['error']}"[:2000]
|
|
98
|
+
return None
|
|
61
99
|
|
|
62
100
|
|
|
63
101
|
VERSION = 1
|
|
@@ -76,13 +114,15 @@ FAIL_FACTS = (
|
|
|
76
114
|
)
|
|
77
115
|
# A rolling subflow (AFD-55) is one play with serial for all its steps.
|
|
78
116
|
ROLLING = re.compile(r": rolling, .+ at a time$")
|
|
117
|
+
# Why Retry is not offered, as a reason: shown alone and after "Retry is not offered here: ".
|
|
79
118
|
NO_RETRY_ROLLING = (
|
|
80
|
-
"
|
|
119
|
+
"A rolling subflow runs its steps as one play for each batch. "
|
|
81
120
|
"Rerun from this step as a new run instead."
|
|
82
121
|
)
|
|
83
122
|
NO_RETRY_HARD = (
|
|
84
|
-
"
|
|
85
|
-
"
|
|
123
|
+
"Ansible took the failed host out of the run (it failed outside the step's rescue, as with a "
|
|
124
|
+
"missing role, an include error or a failure percentage). Rerun from this step as a new run "
|
|
125
|
+
"instead."
|
|
86
126
|
)
|
|
87
127
|
_MISSING = object()
|
|
88
128
|
|
|
@@ -201,7 +241,8 @@ def _wants_pause(control: dict, node: str) -> bool:
|
|
|
201
241
|
def _msg(result: object) -> str:
|
|
202
242
|
if not isinstance(result, dict):
|
|
203
243
|
return ""
|
|
204
|
-
|
|
244
|
+
# "The command exited with a non-zero return code; rc=1", not "code.; rc=1".
|
|
245
|
+
parts = [str(result.get("msg") or result.get("reason") or "").strip().rstrip(".")]
|
|
205
246
|
rc = result.get("rc")
|
|
206
247
|
if rc not in (None, 0):
|
|
207
248
|
parts.append(f"rc={rc}")
|
|
@@ -211,6 +252,37 @@ def _msg(result: object) -> str:
|
|
|
211
252
|
return "; ".join(p for p in parts if p)[:500]
|
|
212
253
|
|
|
213
254
|
|
|
255
|
+
def _last_failures(path: str, offset: int) -> dict[str, dict]:
|
|
256
|
+
"""The last failed result of each host in events.jsonl after `offset` (the afd_events
|
|
257
|
+
callback's lines, masked there): the task and message of a failure no rescue saw."""
|
|
258
|
+
out: dict[str, dict] = {}
|
|
259
|
+
if not path:
|
|
260
|
+
return out
|
|
261
|
+
try:
|
|
262
|
+
with open(path, encoding="utf-8") as f:
|
|
263
|
+
f.seek(offset)
|
|
264
|
+
lines = f.read().splitlines()
|
|
265
|
+
except OSError:
|
|
266
|
+
return out
|
|
267
|
+
for line in lines:
|
|
268
|
+
if '"result"' not in line or '"failed"' not in line:
|
|
269
|
+
continue
|
|
270
|
+
try:
|
|
271
|
+
e = json.loads(line)
|
|
272
|
+
except ValueError:
|
|
273
|
+
continue
|
|
274
|
+
if e.get("event") == "result" and e.get("status") == "failed" and not e.get("ignored"):
|
|
275
|
+
out[str(e.get("host"))] = e
|
|
276
|
+
return out
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _events_size(path: str) -> int:
|
|
280
|
+
try:
|
|
281
|
+
return os.path.getsize(path) if path else 0
|
|
282
|
+
except OSError:
|
|
283
|
+
return 0
|
|
284
|
+
|
|
285
|
+
|
|
214
286
|
class StrategyModule(LinearStrategy):
|
|
215
287
|
def _afd_state(self) -> _State:
|
|
216
288
|
state = getattr(self._tqm, "_afd_step", None)
|
|
@@ -264,10 +336,16 @@ class StrategyModule(LinearStrategy):
|
|
|
264
336
|
found = state.lib.at_point(state.debug, self, play, hosts, node, point)
|
|
265
337
|
for e in found["events"]:
|
|
266
338
|
state.emit(**e)
|
|
339
|
+
if e.get("event") == "log":
|
|
340
|
+
line = _log_line(name, e)
|
|
341
|
+
if line:
|
|
342
|
+
display.display(line)
|
|
267
343
|
if found["pause"]:
|
|
268
344
|
kind = "condition" if point.get("condition") or point.get("hits") else "point"
|
|
269
345
|
if found["matched"]:
|
|
270
346
|
extra["matched"] = found["matched"]
|
|
347
|
+
if point.get("hits"):
|
|
348
|
+
extra["reached"] = point.get("hits")
|
|
271
349
|
elif point is not None:
|
|
272
350
|
kind = "point"
|
|
273
351
|
if kind is None:
|
|
@@ -302,7 +380,7 @@ class StrategyModule(LinearStrategy):
|
|
|
302
380
|
state.emit(**event)
|
|
303
381
|
if kind == "failure":
|
|
304
382
|
failed = extra.get("failed") or []
|
|
305
|
-
display.display(_failed_line(name, len(failed)))
|
|
383
|
+
display.display(_failed_line(name, len(failed), len(names), extra.get("attempt", 1)))
|
|
306
384
|
for f in failed:
|
|
307
385
|
display.display(f" {f['host']}: {f.get('task') or ''}: {f.get('msg') or ''}"[:300])
|
|
308
386
|
else:
|
|
@@ -345,9 +423,17 @@ class StrategyModule(LinearStrategy):
|
|
|
345
423
|
return "stop"
|
|
346
424
|
time.sleep(POLL_S)
|
|
347
425
|
if command == "stop":
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
426
|
+
stopped: dict = {"hosts": names}
|
|
427
|
+
if kind == "failure":
|
|
428
|
+
# Stopped after the step: its failed hosts stay failed there, the others ran it
|
|
429
|
+
# and stop after it (not before it).
|
|
430
|
+
gone = {f["host"] for f in extra.get("failed") or []}
|
|
431
|
+
stopped = {
|
|
432
|
+
"hosts": [n for n in names if n not in gone],
|
|
433
|
+
"failed": [n for n in names if n in gone],
|
|
434
|
+
"after": True,
|
|
435
|
+
}
|
|
436
|
+
state.emit(event="stopped", id=pause, node=node, play=name, reason="driver", **stopped)
|
|
351
437
|
return "stop"
|
|
352
438
|
state.emit(event="resume", id=pause, node=node, command=command)
|
|
353
439
|
return command
|
|
@@ -371,12 +457,15 @@ class StrategyModule(LinearStrategy):
|
|
|
371
457
|
for h in hosts
|
|
372
458
|
}
|
|
373
459
|
|
|
374
|
-
def _afd_failed(self, before: dict, filters: dict
|
|
460
|
+
def _afd_failed(self, before: dict, filters: dict, events: str = "", offset: int = 0):
|
|
375
461
|
"""The hosts that failed the play just run: rescued into the fail port (the rescue set
|
|
376
|
-
afd_failed_node again), failed outside the rescue, or unreachable (when asked).
|
|
462
|
+
afd_failed_node again), failed outside the rescue, or unreachable (when asked). A failure
|
|
463
|
+
outside the rescue has no afd_failed_* facts: its task and message are the run's last
|
|
464
|
+
failed result for the host (events.jsonl since the play started)."""
|
|
377
465
|
facts = self._variable_manager._nonpersistent_fact_cache
|
|
378
466
|
stats = self._tqm._stats
|
|
379
467
|
out = []
|
|
468
|
+
seen: dict[str, dict] | None = None
|
|
380
469
|
for name, snap in before.items():
|
|
381
470
|
hf = facts.get(name, {})
|
|
382
471
|
node_fact = hf.get("afd_failed_node", _MISSING)
|
|
@@ -402,6 +491,12 @@ class StrategyModule(LinearStrategy):
|
|
|
402
491
|
}
|
|
403
492
|
if hard and not rescued:
|
|
404
493
|
item["hard"] = True
|
|
494
|
+
if not item["task"] or not item["msg"]:
|
|
495
|
+
if seen is None:
|
|
496
|
+
seen = _last_failures(events, offset)
|
|
497
|
+
last = seen.get(name) or {}
|
|
498
|
+
item["task"] = item["task"] or str(last.get("task") or "")
|
|
499
|
+
item["msg"] = item["msg"] or str(last.get("msg") or "")[:500]
|
|
405
500
|
out.append(item)
|
|
406
501
|
elif filters["unreachable"] and gone:
|
|
407
502
|
out.append({"host": name, "task": "", "msg": "Unreachable", "unreachable": True})
|
|
@@ -478,11 +573,14 @@ class StrategyModule(LinearStrategy):
|
|
|
478
573
|
):
|
|
479
574
|
return super().run(iterator, play_context)
|
|
480
575
|
before = self._afd_snapshot(play)
|
|
576
|
+
# Every pause holds all hosts: after a Retry, those that passed still wait at it.
|
|
577
|
+
everyone = [s["host"] for s in before.values()]
|
|
578
|
+
offset = _events_size(state.events)
|
|
481
579
|
result = super().run(iterator, play_context)
|
|
482
580
|
attempt = 1
|
|
483
581
|
while not state.stopped:
|
|
484
582
|
filters = state.failures()
|
|
485
|
-
failed = self._afd_failed(before, filters)
|
|
583
|
+
failed = self._afd_failed(before, filters, state.events, offset)
|
|
486
584
|
if not failed or state.read().get("command") == "stop":
|
|
487
585
|
return result
|
|
488
586
|
refused = None
|
|
@@ -490,12 +588,11 @@ class StrategyModule(LinearStrategy):
|
|
|
490
588
|
refused = NO_RETRY_ROLLING
|
|
491
589
|
elif any(f.get("hard") for f in failed):
|
|
492
590
|
refused = NO_RETRY_HARD
|
|
493
|
-
hosts = [s["host"] for s in before.values()]
|
|
494
591
|
command = self._afd_pause(
|
|
495
592
|
state,
|
|
496
593
|
node,
|
|
497
594
|
play,
|
|
498
|
-
|
|
595
|
+
everyone,
|
|
499
596
|
"failure",
|
|
500
597
|
failed=failed,
|
|
501
598
|
attempt=attempt,
|
|
@@ -519,5 +616,6 @@ class StrategyModule(LinearStrategy):
|
|
|
519
616
|
)
|
|
520
617
|
fresh = self._afd_snapshot(play)
|
|
521
618
|
before = {n: fresh.get(n, before[n]) for n in names}
|
|
619
|
+
offset = _events_size(state.events)
|
|
522
620
|
result = self._afd_rerun(iterator, play_context, names)
|
|
523
621
|
return self._tqm.RUN_FAILED_BREAK_PLAY
|