@ansible-flow/assets 1.2.0-rc.1 → 1.2.0-rc.2

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 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.1
5
+ Built from [Ansible Flow Designer](https://github.com/ChistokhinSV/ansible-flow-designer) 1.2.0-rc.2
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.1",
3
+ "version": "1.2.0-rc.2",
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",
@@ -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,31 @@ 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
- for v in all_vars.values():
216
- masker.learn(v)
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_") and name in self._all_play:
248
+ return None # the generator's own play variables
221
249
  if name in self._extra:
222
250
  return "flow"
223
251
  if name in self._play_vars:
@@ -241,7 +269,9 @@ class HostView:
241
269
  out[str(name)] = plain(self._masker.mask(str(name), facts[name]))
242
270
  else:
243
271
  for name in sorted(self._vars, key=str):
244
- if self.scope_of(str(name)) != scope:
272
+ where = self.scope_of(str(name))
273
+ # A step input the flow data gives is listed in both: it is the step's input.
274
+ if not (where == scope or (scope == "inputs" and where and name in self._inputs)):
245
275
  continue
246
276
  if scope == "inputs" and name in self._secret:
247
277
  out[name] = plain(Masked("credential"))
@@ -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,6 +137,7 @@ 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
 
@@ -197,18 +239,33 @@ class Gate:
197
239
  e["value"] = value
198
240
  return e
199
241
 
200
- def _nolog_in(self, expr: str) -> bool:
201
- """The expression reads a no_log task's register: its result is masked whole."""
202
- return bool(render.names_in(expr, self.environment()) & self.session.nolog)
242
+ def _masked_row(self, host: str, expr: str) -> dict | None:
243
+ """The answer for an expression that reads a masked value: masked whole, with the kind
244
+ of what it reads (a filter's result keeps it: reverse, list, length, hash, ==)."""
245
+ try:
246
+ why = self.masked_by(host, expr)
247
+ except TooMany:
248
+ return {
249
+ "host": host,
250
+ "expr": expr,
251
+ "error": (
252
+ f"hostvars with a host chosen at run time is not evaluated in an inventory "
253
+ f"of more than {MAX_HOSTS} hosts: name the host"
254
+ ),
255
+ "refused": True,
256
+ }
257
+ if why:
258
+ return {"host": host, "expr": expr, "type": "masked", "masked": why}
259
+ return None
203
260
 
204
261
  def evaluate(self, host: str, expr: str, timeout: object = None) -> dict:
205
262
  refused = render.precheck(expr, self.environment())
206
263
  if refused:
207
264
  return {"host": host, "expr": expr, "error": refused, "refused": True}
208
- if self._nolog_in(expr):
209
- return {"host": host, "expr": expr, "type": "masked", "masked": "no_log"}
210
265
  # The plain texts of this host's vaulted values are learned here, before the child.
211
- self.view(host)
266
+ masked = self._masked_row(host, expr)
267
+ if masked:
268
+ return masked
212
269
  target = self.hosts[host]
213
270
 
214
271
  def work() -> object:
@@ -227,9 +284,7 @@ class Gate:
227
284
  hosts = [str(h) for h in (req.get("hosts") or list(self.hosts)) if str(h) in self.hosts]
228
285
  env = self.environment()
229
286
  refused = {e: render.precheck(e, env) for e in exprs}
230
- nolog = {e: not refused[e] and self._nolog_in(e) for e in exprs}
231
- for h in hosts:
232
- self.view(h)
287
+ masked = {(h, e): self._masked_row(h, e) for h in hosts for e in exprs if not refused[e]}
233
288
  targets = {h: self.hosts[h] for h in hosts}
234
289
 
235
290
  def work() -> object:
@@ -240,8 +295,8 @@ class Gate:
240
295
  if refused[e]:
241
296
  rows.append({"host": h, "expr": e, "error": refused[e], "refused": True})
242
297
  continue
243
- if nolog[e]:
244
- rows.append({"host": h, "expr": e, "type": "masked", "masked": "no_log"})
298
+ if masked.get((h, e)):
299
+ rows.append(masked[(h, e)])
245
300
  continue
246
301
  try:
247
302
  value = templar.evaluate_expression(render.trusted(e))
@@ -272,6 +327,13 @@ def point_settings(point: Mapping) -> dict:
272
327
  return out
273
328
 
274
329
 
330
+ def _masked_by(gate: Gate, host: str, text: str, template: bool = False) -> str | None:
331
+ try:
332
+ return gate.masked_by(host, text, template=template)
333
+ except TooMany:
334
+ return "name" # hostvars by a host chosen at run time in a large inventory: not shown
335
+
336
+
275
337
  def at_point(session: Session, strategy, play, hosts: list, node: str, point: Mapping) -> dict:
276
338
  """A pause point's settings at its gate, for every host:
277
339
  - condition: Jinja per host; all hosts pause if any matches (the matched hosts are named);
@@ -288,10 +350,31 @@ def at_point(session: Session, strategy, play, hosts: list, node: str, point: Ma
288
350
  if cond or log:
289
351
  gate = Gate(session, strategy, play, hosts, "")
290
352
  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
- for h in names: # learn the vaulted plain texts before the child masks
353
+ bad_cond = render.precheck(cond, env, "a condition") if cond else None
354
+ bad_log = render.check_template(log, env, "a log message") if log else None
355
+ # Before the child: the vaulted plain texts are learned, and what each host's condition
356
+ # and message read is checked (AFD-373). A condition that reads a masked value is not
357
+ # checked (true or false would tell its value); in a message, each {{ }} that reads one
358
+ # is masked (a {% %} that reads one masks the whole message).
359
+ taint: dict[str, dict] = {}
360
+ for h in names:
294
361
  gate.view(h)
362
+ row: dict = {}
363
+ if cond and not bad_cond:
364
+ why = _masked_by(gate, h, cond)
365
+ if why:
366
+ row["cond"] = why
367
+ if log and not bad_log:
368
+ whole = _masked_by(gate, h, log, template=True)
369
+ if whole:
370
+ text, kinds = mask_blocks(
371
+ env,
372
+ log,
373
+ lambda e, h=h, whole=whole: _masked_by(gate, h, e) if e else whole,
374
+ )
375
+ row["log"] = text
376
+ row["kinds"] = sorted(kinds or {whole})
377
+ taint[h] = row
295
378
  masker = session.masker
296
379
 
297
380
  def work() -> object:
@@ -299,15 +382,27 @@ def at_point(session: Session, strategy, play, hosts: list, node: str, point: Ma
299
382
  for h in hosts:
300
383
  templar = gate._templar_for(h)
301
384
  row: dict = {}
302
- if cond and not bad_cond:
385
+ masked = taint.get(h.get_name(), {})
386
+ if cond and not bad_cond and masked.get("cond"):
387
+ row["cond"] = (
388
+ f"The condition reads a masked value ({masked['cond']}): it is not checked"
389
+ )
390
+ elif cond and not bad_cond:
303
391
  try:
304
392
  row["cond"] = bool(templar.evaluate_conditional(render.trusted(cond)))
305
393
  except Exception as ex: # noqa: BLE001
306
394
  row["cond"] = render.error_text(ex)
307
395
  if log and not bad_log and row.get("cond", True) is True:
308
396
  try:
309
- value = templar.template(render.trusted(log))
397
+ # A message that reads masked values renders with those parts masked
398
+ # (None: masked whole).
399
+ source = masked.get("log", log)
400
+ if source is None:
401
+ value: object = REDACTED
402
+ else:
403
+ value = templar.template(render.trusted(source))
310
404
  text, kinds = masker.scrub(str(value), value)
405
+ kinds |= set(masked.get("kinds") or [])
311
406
  row["log"] = text
312
407
  if kinds:
313
408
  row["masked"] = sorted(kinds)
@@ -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:
@@ -42,37 +42,95 @@ 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
- return check_template("{{ " + expr + " }}", environment, "Not a Jinja expression")
54
+ unclosed = not_closed(expr)
55
+ if unclosed:
56
+ return unclosed
57
+ return check_template("{{ " + expr + " }}", environment, where, expression=True)
58
+
59
+
60
+ PAIRS = {"(": ")", "[": "]", "{": "}"}
61
+
62
+
63
+ def not_closed(expr: str) -> str | None:
64
+ """A bracket or quote the expression opens and never closes (or closes without opening), in
65
+ words: Jinja's own error names the `}}` the expression is wrapped in, never typed."""
66
+ stack: list[str] = []
67
+ quote = ""
68
+ escaped = False
69
+ for ch in expr:
70
+ if quote:
71
+ if escaped:
72
+ escaped = False
73
+ elif ch == "\\":
74
+ escaped = True
75
+ elif ch == quote:
76
+ quote = ""
77
+ continue
78
+ if ch in ("'", '"'):
79
+ quote = ch
80
+ elif ch in PAIRS:
81
+ stack.append(ch)
82
+ elif ch in PAIRS.values():
83
+ if not stack or PAIRS[stack[-1]] != ch:
84
+ return f"A {ch} has no opening bracket before it"
85
+ stack.pop()
86
+ if quote:
87
+ return f"A quote ({quote}) is not closed"
88
+ if stack:
89
+ return f"A bracket ({stack[-1]}) is not closed"
90
+ return None
54
91
 
55
92
 
56
- def check_template(text: str, environment, what: str = "Not a Jinja template") -> str | None:
57
- """Why a template (a log message, an expression in braces) is refused; None when it may run."""
93
+ def _syntax(ex: BaseException, expression: bool) -> str:
94
+ """Jinja's syntax error in plain words, without the parser's own terms."""
95
+ text = (str(ex).strip().splitlines() or [""])[0]
96
+ if expression:
97
+ text = (
98
+ text.replace("expected token 'end of print statement'", "expected the end")
99
+ .replace("'end of print statement'", "the end")
100
+ .replace("unexpected '}'", "unexpected end")
101
+ .replace("unexpected end of template", "unexpected end")
102
+ )
103
+ return text[:300]
104
+
105
+
106
+ def check_template(
107
+ text: str, environment, where: str = "a log message", expression: bool = False
108
+ ) -> str | None:
109
+ """Why a template (a log message, an expression in braces) is refused; None when it may run.
110
+ `where` names what refuses it, in the words: "lookups are not allowed in Evaluate"."""
58
111
  try:
59
112
  from jinja2 import nodes
60
113
 
61
114
  ast = environment.parse(text)
62
115
  except Exception as ex: # noqa: BLE001
63
- return f"{what}: {str(ex)[:300]}"
116
+ what = "Not a Jinja expression" if expression else "Not a Jinja template"
117
+ return f"{what}: {_syntax(ex, expression)}"
118
+ lookups = f"lookups are not allowed in {where}: they can read files or run commands"
64
119
  for call in ast.find_all(nodes.Call):
65
120
  if isinstance(call.node, nodes.Name) and call.node.name in LOOKUP_CALLS:
66
- return f"{call.node.name}() is not allowed while debugging: it can read or run things"
121
+ return f"{call.node.name}(): {lookups}"
67
122
  for name in ast.find_all(nodes.Name):
68
123
  if name.name in LOOKUP_CALLS:
69
- return f"{name.name} is not allowed while debugging: it can read or run things"
124
+ return f"{name.name}: {lookups}"
70
125
  for f in ast.find_all(nodes.Filter):
71
126
  if _short(f.name) in FILTER_DENY:
72
- return f"The {f.name} filter is not allowed while debugging"
127
+ return f"The {f.name} filter is not allowed in {where}"
73
128
  for attr in ast.find_all(nodes.Getattr):
74
129
  if str(attr.attr).startswith("_"):
75
- return "Attributes starting with _ are not allowed while debugging"
130
+ return f"Attributes starting with _ are not allowed in {where}"
131
+ for name in ast.find_all(nodes.Name):
132
+ if str(name.name).startswith("_"):
133
+ return f"Names starting with _ are not allowed in {where}"
76
134
  return None
77
135
 
78
136
 
@@ -97,7 +155,9 @@ def block_lookups() -> None:
97
155
  class _Guard:
98
156
  def get(self, name, *a, **kw):
99
157
  if _short(name) not in LOOKUP_ALLOW:
100
- raise Blocked(f"lookup {name!r} is not allowed while debugging")
158
+ raise Blocked(
159
+ f"lookups are not allowed while debugging (a variable runs lookup {name!r})"
160
+ )
101
161
  return real.get(name, *a, **kw)
102
162
 
103
163
  def __getattr__(self, attr):
@@ -0,0 +1,344 @@
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 _chain(node) -> tuple[str, list] | None:
38
+ """(root name, keys) of a chain of names, attributes and items; None for anything else."""
39
+ from jinja2 import nodes
40
+
41
+ keys: list = []
42
+ while True:
43
+ if isinstance(node, nodes.Getattr):
44
+ keys.append(node.attr)
45
+ node = node.node
46
+ elif isinstance(node, nodes.Getitem):
47
+ arg = node.arg
48
+ if (
49
+ isinstance(arg, nodes.Const)
50
+ and isinstance(arg.value, (str, int))
51
+ and not isinstance(arg.value, bool)
52
+ ):
53
+ keys.append(arg.value)
54
+ else:
55
+ keys.append(DYN)
56
+ node = node.node
57
+ elif isinstance(node, nodes.Name):
58
+ keys.reverse()
59
+ return str(node.name), keys
60
+ else:
61
+ return None
62
+
63
+
64
+ def references(ast) -> tuple[list[tuple[str, list]], list[str]]:
65
+ """Every variable an AST reads, as (root, keys), and the string constants that are templates."""
66
+ from jinja2 import nodes
67
+
68
+ refs: list[tuple[str, list]] = []
69
+ texts: list[str] = []
70
+
71
+ def visit(node) -> None:
72
+ if isinstance(node, (nodes.Getattr, nodes.Getitem, nodes.Name)):
73
+ chain = _chain(node)
74
+ if chain is not None:
75
+ if not (isinstance(node, nodes.Name) and node.ctx != "load"):
76
+ refs.append(chain)
77
+ # The keys chosen at run time read variables of their own.
78
+ n = node
79
+ while isinstance(n, (nodes.Getattr, nodes.Getitem)):
80
+ if isinstance(n, nodes.Getitem):
81
+ visit(n.arg)
82
+ n = n.node
83
+ return
84
+ if (
85
+ isinstance(node, nodes.Const)
86
+ and isinstance(node.value, str)
87
+ and ("{{" in node.value or "{%" in node.value)
88
+ ):
89
+ texts.append(node.value)
90
+ for child in node.iter_child_nodes():
91
+ visit(child)
92
+
93
+ visit(ast)
94
+ return refs, texts
95
+
96
+
97
+ class Taint:
98
+ """What a host's expression reads, checked against the masking. One per pause and host."""
99
+
100
+ def __init__(
101
+ self,
102
+ masker: Masker,
103
+ environment,
104
+ variables: Callable[[str], Mapping | None],
105
+ inventory_hosts: Callable[[], list[str]],
106
+ host: str,
107
+ *,
108
+ nolog: set[str] | None = None,
109
+ secret: set[str] | None = None,
110
+ ) -> None:
111
+ self.masker = masker
112
+ self.environment = environment
113
+ self.variables = variables
114
+ self.inventory_hosts = inventory_hosts
115
+ self.host = host
116
+ self.nolog = nolog or set()
117
+ self.secret = secret or set()
118
+ self._templates: set[str] = set()
119
+
120
+ # ---- entry points ----------------------------------------------------------------------
121
+ def expression(self, expr: str) -> str | None:
122
+ """Why the result of `expr` (no braces) is masked whole, or None."""
123
+ return self.template("{{ " + expr + " }}")
124
+
125
+ def template(self, text: str, depth: int = 0) -> str | None:
126
+ """Why the rendering of `text` is masked whole, or None. An AST that does not parse reads
127
+ nothing here (the render fails on its own)."""
128
+ if depth > TEMPLATE_DEPTH:
129
+ return None
130
+ try:
131
+ ast = self.environment.parse(text)
132
+ except Exception: # noqa: BLE001
133
+ return None
134
+ refs, texts = references(ast)
135
+ own = self.variables(self.host) or {}
136
+ for root, keys in refs:
137
+ why = self._root(own, root, keys, depth)
138
+ if why:
139
+ return why
140
+ for t in texts:
141
+ why = self._text(t, depth + 1)
142
+ if why:
143
+ return why
144
+ return None
145
+
146
+ # ---- a reference -----------------------------------------------------------------------
147
+ def _root(self, own: Mapping, root: str, keys: list, depth: int) -> str | None:
148
+ if root == "hostvars":
149
+ return self._hostvars(keys, depth)
150
+ if root == "vars":
151
+ return self._in_vars(own, keys, depth, whole=True)
152
+ return self._in_vars(own, [root, *keys], depth)
153
+
154
+ def _hostvars(self, keys: list, depth: int) -> str | None:
155
+ first = keys[0] if keys else DYN
156
+ known = self.inventory_hosts()
157
+ if first is not DYN and str(first) in known:
158
+ hosts, rest = [str(first)], keys[1:]
159
+ else:
160
+ # A host chosen at run time, or no host at all (`hostvars | dict2items`, `.values()`).
161
+ if len(known) > MAX_HOSTS:
162
+ raise TooMany
163
+ hosts, rest = known, (keys[1:] if keys else [])
164
+ for h in hosts:
165
+ hv = self.variables(h)
166
+ if hv is None:
167
+ continue
168
+ why = self._in_vars(hv, rest, depth, host=h, whole=True)
169
+ if why:
170
+ return why
171
+ return None
172
+
173
+ def _in_vars(
174
+ self,
175
+ all_vars: Mapping,
176
+ keys: list,
177
+ depth: int,
178
+ host: str | None = None,
179
+ whole: bool = False,
180
+ ) -> str | None:
181
+ """A path into a host's variables: its first key is a variable's name. A name the host
182
+ does not have reads nothing (undefined, or a Jinja global such as range), unless the path
183
+ is inside `vars` or `hostvars[h]` (`whole`): there it is a method or a lookup by a name
184
+ chosen at run time (`vars.values()`, `vars[k]`), and every variable is checked."""
185
+ if not keys or keys[0] is DYN or str(keys[0]) not in all_vars:
186
+ if not whole and keys and keys[0] is not DYN:
187
+ return None
188
+ for name, value in all_vars.items():
189
+ why = self._variable(str(name), value, [], depth, host)
190
+ if why:
191
+ return why
192
+ return None
193
+ name = str(keys[0])
194
+ return self._variable(name, all_vars[name], keys[1:], depth, host)
195
+
196
+ def _variable(
197
+ self, name: str, value: object, keys: list, depth: int, host: str | None
198
+ ) -> str | None:
199
+ if name in MAGIC and name not in ROOTS:
200
+ return None
201
+ if name in ROOTS:
202
+ return None # the lazy objects themselves (2.19's `vars` is every variable again)
203
+ if name in self.nolog:
204
+ return "no_log"
205
+ if name in self.secret:
206
+ return "credential"
207
+ # A secret-looking name is the weakest reason: a vaulted, credential, external or no_log
208
+ # value at or inside it says what it truly is (AFS-252).
209
+ why = self.masker.kind(name, value)
210
+ if why and why != "name":
211
+ return why
212
+ weak = why
213
+ for key in keys:
214
+ if key is DYN:
215
+ break
216
+ if isinstance(value, Mapping) and not _is_hostvars(value) and key in value:
217
+ name, value = str(key), value[key]
218
+ elif (
219
+ isinstance(value, (list, tuple))
220
+ and isinstance(key, int)
221
+ and -len(value) <= key < len(value)
222
+ ):
223
+ name, value = "", value[key]
224
+ else:
225
+ break # an attribute of a value (a method, a missing key): the value is read
226
+ why = self.masker.kind(name, value)
227
+ if why and why != "name":
228
+ return why
229
+ weak = weak or why
230
+ inner = self._inside(value, 0, depth, host)
231
+ return inner if inner and inner != "name" else (weak or inner)
232
+
233
+ def _inside(self, value: object, level: int, depth: int, host: str | None) -> str | None:
234
+ """A masked part anywhere inside `value`, or a template there that reads one; a
235
+ secret-looking name only when nothing stronger is found."""
236
+ if level > DEPTH:
237
+ return None
238
+ weak = None
239
+ parts: list[tuple[str, object]] = []
240
+ if isinstance(value, Mapping):
241
+ if _is_hostvars(value):
242
+ return None
243
+ parts = [(str(k), v) for k, v in value.items()]
244
+ elif isinstance(value, (list, tuple, set, frozenset)):
245
+ parts = [("", v) for v in value]
246
+ elif isinstance(value, str):
247
+ text = str.__str__(value)
248
+ if "{{" in text or "{%" in text:
249
+ return self._text(text, depth + 1, host)
250
+ return None
251
+ for k, v in parts:
252
+ for why in (self.masker.kind(k, v), self._inside(v, level + 1, depth, host)):
253
+ if why and why != "name":
254
+ return why
255
+ weak = weak or why
256
+ return weak
257
+
258
+ def _text(self, text: str, depth: int, host: str | None = None) -> str | None:
259
+ """A template inside a value: what it reads, as the host that has it."""
260
+ key = f"{host or self.host}\0{text}"
261
+ if key in self._templates or depth > TEMPLATE_DEPTH:
262
+ return None
263
+ self._templates.add(key)
264
+ if host is None or host == self.host:
265
+ return self.template(text, depth)
266
+ other = Taint(
267
+ self.masker,
268
+ self.environment,
269
+ self.variables,
270
+ self.inventory_hosts,
271
+ host,
272
+ nolog=self.nolog,
273
+ secret=self.secret,
274
+ )
275
+ other._templates = self._templates
276
+ return other.template(text, depth)
277
+
278
+
279
+ def mask_blocks(
280
+ environment, text: str, why: Callable[[str], str | None]
281
+ ) -> tuple[str | None, set[str]]:
282
+ """A log message with each `{{ ... }}` that reads a masked value replaced by the mask, so the
283
+ rest still renders ("sw-01 cred=********"); `why(expr)` says why an expression is masked.
284
+ Returns (the template to render, the kinds), or (None, kinds) when the message is masked
285
+ whole: a `{% ... %}` that reads a masked value, or a template the lexer cannot read."""
286
+ from .mask import REDACTED
287
+
288
+ try:
289
+ tokens = list(environment.lex(text))
290
+ except Exception: # noqa: BLE001
291
+ return None, {"name"}
292
+ out: list[str] = []
293
+ kinds: set[str] = set()
294
+ block: list[tuple[str, str]] | None = None
295
+ for _line, kind, value in tokens:
296
+ if kind in ("variable_begin", "block_begin"):
297
+ block = [(kind, value)]
298
+ continue
299
+ if block is None:
300
+ out.append(value)
301
+ continue
302
+ block.append((kind, value))
303
+ if kind not in ("variable_end", "block_end"):
304
+ continue
305
+ source = "".join(v for _k, v in block)
306
+ inner = "".join(v for _k, v in block[1:-1])
307
+ opened = block[0][0]
308
+ block = None
309
+ if opened == "block_begin":
310
+ # A statement (for, if, set): what it reads shapes the whole message.
311
+ found = why_statement(inner, why)
312
+ if found:
313
+ return None, {found}
314
+ out.append(source)
315
+ continue
316
+ found = why(inner)
317
+ if found:
318
+ kinds.add(found)
319
+ out.append(REDACTED)
320
+ else:
321
+ out.append(source)
322
+ if block is not None: # not closed: the render reports the error
323
+ out.extend(v for _k, v in block)
324
+ return "".join(out), kinds
325
+
326
+
327
+ # Statements that read no expression.
328
+ QUIET = {"else", "endif", "endfor", "endset", "raw", "endraw", "endfilter", "endwith", "endcall"}
329
+
330
+
331
+ def why_statement(inner: str, why: Callable[[str], str | None]) -> str | None:
332
+ """A `{% ... %}` statement's expression: `if <expr>`, `for x in <expr>`, `set x = <expr>`.
333
+ Any other statement (with, macro, call, filter) masks the message when the message as a whole
334
+ reads a masked value (`why` of an empty expression is that kind)."""
335
+ text = inner.strip().lstrip("-+").rstrip("-+").strip()
336
+ word = text.split(None, 1)[0] if text else ""
337
+ if word in QUIET:
338
+ return None
339
+ m = re.match(r"(?:el)?if\s+(.*)$|for\s+.+?\s+in\s+(.*)$|set\s+[^=]+=\s*(.*)$", text, re.S)
340
+ if m is None:
341
+ return why("")
342
+ expr = next(g for g in m.groups() if g is not None)
343
+ # `for x in items if cond`, `... recursive`: the whole tail is read.
344
+ return why(expr.removesuffix(" recursive"))
@@ -54,10 +54,23 @@ def _paused_line(play: str, hosts: int) -> str:
54
54
  return f"Paused before {title}: {waits} for Step, Continue or Stop"
55
55
 
56
56
 
57
- def _failed_line(play: str, failed: int) -> str:
57
+ def _failed_line(play: str, failed: int, hosts: int, attempt: int) -> str:
58
58
  title = re.sub(r"^\[[^\]]*\]\s*", "", play) or play
59
- who = "1 host" if failed == 1 else f"{failed} hosts"
60
- return f"{who} failed {title}: Retry, Continue or Stop"
59
+ of = f"{failed} of {hosts} hosts" if hosts > 1 else "1 host"
60
+ return f"Paused after {title}: {of} failed (attempt {attempt}): Retry, Continue or Stop"
61
+
62
+
63
+ def _log_line(play: str, event: dict) -> str | None:
64
+ """A log point's line in the run's output (ADR-0040 §6): masked as the event is."""
65
+ title = re.sub(r"^\[[^\]]*\]\s*", "", play) or play
66
+ host = event.get("host")
67
+ where = f"{title} · {host}" if host else title
68
+ if "message" in event:
69
+ return f"Log point {where}: {event['message']}"[:2000]
70
+ if event.get("error"):
71
+ what = {"condition": "condition", "log": "log message"}.get(event.get("source"), "point")
72
+ return f"Log point {where}: the {what} failed: {event['error']}"[:2000]
73
+ return None
61
74
 
62
75
 
63
76
  VERSION = 1
@@ -264,10 +277,16 @@ class StrategyModule(LinearStrategy):
264
277
  found = state.lib.at_point(state.debug, self, play, hosts, node, point)
265
278
  for e in found["events"]:
266
279
  state.emit(**e)
280
+ if e.get("event") == "log":
281
+ line = _log_line(name, e)
282
+ if line:
283
+ display.display(line)
267
284
  if found["pause"]:
268
285
  kind = "condition" if point.get("condition") or point.get("hits") else "point"
269
286
  if found["matched"]:
270
287
  extra["matched"] = found["matched"]
288
+ if point.get("hits"):
289
+ extra["reached"] = point.get("hits")
271
290
  elif point is not None:
272
291
  kind = "point"
273
292
  if kind is None:
@@ -302,7 +321,7 @@ class StrategyModule(LinearStrategy):
302
321
  state.emit(**event)
303
322
  if kind == "failure":
304
323
  failed = extra.get("failed") or []
305
- display.display(_failed_line(name, len(failed)))
324
+ display.display(_failed_line(name, len(failed), len(names), extra.get("attempt", 1)))
306
325
  for f in failed:
307
326
  display.display(f" {f['host']}: {f.get('task') or ''}: {f.get('msg') or ''}"[:300])
308
327
  else:
@@ -345,9 +364,17 @@ class StrategyModule(LinearStrategy):
345
364
  return "stop"
346
365
  time.sleep(POLL_S)
347
366
  if command == "stop":
348
- state.emit(
349
- event="stopped", id=pause, node=node, play=name, hosts=names, reason="driver"
350
- )
367
+ stopped: dict = {"hosts": names}
368
+ if kind == "failure":
369
+ # Stopped after the step: its failed hosts stay failed there, the others ran it
370
+ # and stop after it (not before it).
371
+ gone = {f["host"] for f in extra.get("failed") or []}
372
+ stopped = {
373
+ "hosts": [n for n in names if n not in gone],
374
+ "failed": [n for n in names if n in gone],
375
+ "after": True,
376
+ }
377
+ state.emit(event="stopped", id=pause, node=node, play=name, reason="driver", **stopped)
351
378
  return "stop"
352
379
  state.emit(event="resume", id=pause, node=node, command=command)
353
380
  return command
@@ -478,6 +505,8 @@ class StrategyModule(LinearStrategy):
478
505
  ):
479
506
  return super().run(iterator, play_context)
480
507
  before = self._afd_snapshot(play)
508
+ # Every pause holds all hosts: after a Retry, those that passed still wait at it.
509
+ everyone = [s["host"] for s in before.values()]
481
510
  result = super().run(iterator, play_context)
482
511
  attempt = 1
483
512
  while not state.stopped:
@@ -490,12 +519,11 @@ class StrategyModule(LinearStrategy):
490
519
  refused = NO_RETRY_ROLLING
491
520
  elif any(f.get("hard") for f in failed):
492
521
  refused = NO_RETRY_HARD
493
- hosts = [s["host"] for s in before.values()]
494
522
  command = self._afd_pause(
495
523
  state,
496
524
  node,
497
525
  play,
498
- hosts,
526
+ everyone,
499
527
  "failure",
500
528
  failed=failed,
501
529
  attempt=attempt,