@ansible-flow/assets 1.1.0-rc.3 → 1.2.0-rc.1

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.
@@ -0,0 +1,364 @@
1
+ # The debugger at a pause (ADR-0040 §2, §3, §5, §6; AFD-370, AFD-371): requests served from the
2
+ # afd_step gate loop, and pause point conditions, hit counts and log points at a step gate.
3
+ #
4
+ # Channel: the driver writes request-<n>.json beside control.json (whole: a temporary file, then a
5
+ # rename): {v:1, pause, n, op, host?, hosts?, scope?, path?, start?, count?, expr?, exprs?,
6
+ # timeout?}. The gate loop answers with answer-<n>.json (whole too) on its 100 ms tick and removes
7
+ # the request. A request for a pause that is not the current one is answered {gone: true}.
8
+ # Ops: scopes, vars, facts, eval, watch.
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ import time
14
+ from collections.abc import Mapping
15
+
16
+ from . import capture, render
17
+ from .capture import HostView, entry, plain, to_json
18
+ from .mask import TAGS, Masker
19
+
20
+ VERSION = 1
21
+ # A gate's conditions and log messages, for every host: one child, at most this long.
22
+ GATE_LIMIT = 2.0
23
+
24
+
25
+ def unavailable() -> str | None:
26
+ """Why this core cannot be debugged, in words; None when it can."""
27
+ if not TAGS:
28
+ return "Debugging needs ansible-core 2.19 or later; this run goes on step by step only"
29
+ try:
30
+ import ansible._internal._templating._jinja_plugins as jp
31
+
32
+ if not hasattr(jp, "lookup_loader"):
33
+ raise ImportError
34
+ except ImportError:
35
+ return (
36
+ "This ansible-core cannot block lookups while debugging; the run goes on step by step"
37
+ )
38
+ return None
39
+
40
+
41
+ def write_whole(path: str, data: object) -> None:
42
+ tmp = f"{path}.{os.getpid()}.tmp"
43
+ with open(tmp, "w", encoding="utf-8") as f:
44
+ f.write(json.dumps(data, ensure_ascii=False, separators=(",", ":"), default=str))
45
+ os.replace(tmp, path)
46
+
47
+
48
+ class Session:
49
+ """One per ansible-playbook process: the masker (its known values grow) and hit counts."""
50
+
51
+ def __init__(self) -> None:
52
+ self.masker = Masker()
53
+ self.hits: dict[str, int] = {}
54
+ # Registers of no_log tasks, from every play so far (ADR-0040 §4, check 4).
55
+ self.nolog: set[str] = set()
56
+
57
+ def note_play(self, play) -> None:
58
+ self.nolog |= capture.nolog_registers(play)
59
+
60
+ def gate(self, strategy, play, hosts: list, pause: str) -> Gate:
61
+ return Gate(self, strategy, play, hosts, pause)
62
+
63
+
64
+ class Gate:
65
+ """One pause: the play, its hosts and the variable manager, with each host's view cached."""
66
+
67
+ def __init__(self, session: Session, strategy, play, hosts: list, pause: str) -> None:
68
+ self.session = session
69
+ self.strategy = strategy
70
+ self.play = play
71
+ self.hosts = {h.get_name(): h for h in hosts}
72
+ self.pause = pause
73
+ self._views: dict[str, HostView] = {}
74
+ self._secret: set[str] | None = None
75
+ self._templar = None
76
+
77
+ # ---- what a host has -------------------------------------------------------------------
78
+ def variables(self, host) -> Mapping:
79
+ s = self.strategy
80
+ return s._variable_manager.get_vars( # noqa: SLF001
81
+ play=self.play,
82
+ host=host,
83
+ _hosts=getattr(s, "_hosts_cache", None),
84
+ _hosts_all=getattr(s, "_hosts_cache_all", None),
85
+ )
86
+
87
+ def view(self, name: str) -> HostView:
88
+ if name not in self._views:
89
+ if self._secret is None:
90
+ self._secret = capture.secret_inputs(self.play)
91
+ vm = self.strategy._variable_manager # noqa: SLF001
92
+ self._views[name] = HostView(
93
+ self.variables(self.hosts[name]),
94
+ play_vars=set(self.play.vars or {}),
95
+ extra=set(vm.extra_vars or {}),
96
+ secret=self._secret,
97
+ masker=self.session.masker,
98
+ nolog=self.session.nolog,
99
+ )
100
+ return self._views[name]
101
+
102
+ def environment(self):
103
+ if self._templar is None:
104
+ from ansible.template import Templar
105
+
106
+ self._templar = Templar(loader=self.strategy._loader) # noqa: SLF001
107
+ return self._templar.environment
108
+
109
+ # ---- requests --------------------------------------------------------------------------
110
+ def serve(self, folder: str) -> int:
111
+ """Answers the request files waiting in `folder`; returns how many."""
112
+ try:
113
+ names = sorted(
114
+ n for n in os.listdir(folder) if n.startswith("request-") and n.endswith(".json")
115
+ )
116
+ except OSError:
117
+ return 0
118
+ done = 0
119
+ for fname in names:
120
+ path = os.path.join(folder, fname)
121
+ try:
122
+ with open(path, encoding="utf-8") as f:
123
+ req = json.load(f)
124
+ except (OSError, ValueError):
125
+ continue # half written (an SSH copy): the next tick reads it whole
126
+ n = fname[len("request-") : -len(".json")]
127
+ t0 = time.perf_counter()
128
+ if not isinstance(req, dict):
129
+ answer: dict = {"error": "Not a request"}
130
+ elif str(req.get("pause")) != self.pause:
131
+ answer = {"gone": True}
132
+ else:
133
+ try:
134
+ answer = self.answer(req)
135
+ except Exception as ex: # noqa: BLE001 - an answer, never a broken run
136
+ answer = {"error": render.error_text(ex)}
137
+ answer.update(
138
+ v=VERSION, pause=self.pause, n=req.get("n", n) if isinstance(req, dict) else n
139
+ )
140
+ answer["ms"] = round((time.perf_counter() - t0) * 1000, 1)
141
+ try:
142
+ write_whole(os.path.join(folder, f"answer-{n}.json"), answer)
143
+ os.remove(path)
144
+ except OSError:
145
+ pass
146
+ done += 1
147
+ return done
148
+
149
+ def _host(self, req: dict) -> str | dict:
150
+ name = str(req.get("host") or "")
151
+ if name not in self.hosts:
152
+ return {"error": f"{name or 'No host'} does not wait at this pause"}
153
+ return name
154
+
155
+ def answer(self, req: dict) -> dict:
156
+ op = req.get("op")
157
+ if op == "watch":
158
+ return self.watch(req)
159
+ host = self._host(req)
160
+ if isinstance(host, dict):
161
+ return host
162
+ if op == "scopes":
163
+ return {"host": host, "scopes": self.view(host).scopes(facts=bool(req.get("facts")))}
164
+ if op in ("vars", "facts"):
165
+ scope = "facts" if op == "facts" else str(req.get("scope") or "host")
166
+ if scope not in capture.SCOPES:
167
+ return {"error": f"No scope {scope}"}
168
+ path = req.get("path") or []
169
+ if not isinstance(path, list):
170
+ return {"error": "path is a list of names and indexes"}
171
+ out = self.view(host).page(
172
+ scope, path, int(req.get("start") or 0), int(req.get("count") or capture.PAGE)
173
+ )
174
+ out.update(host=host, scope=scope)
175
+ return out
176
+ if op == "eval":
177
+ return self.evaluate(host, str(req.get("expr") or ""), req.get("timeout"))
178
+ return {"error": f"Unknown op {op!r}"}
179
+
180
+ # ---- evaluate and watch ----------------------------------------------------------------
181
+ def _templar_for(self, host):
182
+ from ansible.template import Templar
183
+
184
+ return Templar(loader=self.strategy._loader, variables=self.variables(host)) # noqa: SLF001
185
+
186
+ def _result(self, value: object) -> dict:
187
+ """An expression's value as an answer: masked, plain, cut."""
188
+ value = plain(self.session.masker.mask("", value))
189
+ e = entry("result", value)
190
+ e.pop("name", None)
191
+ if e["type"] in ("dict", "list"):
192
+ text = to_json(value)
193
+ if len(text) > capture.VALUE_LIMIT:
194
+ e["value"] = text[: capture.VALUE_LIMIT]
195
+ e["cut"] = len(text)
196
+ else:
197
+ e["value"] = value
198
+ return e
199
+
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)
203
+
204
+ def evaluate(self, host: str, expr: str, timeout: object = None) -> dict:
205
+ refused = render.precheck(expr, self.environment())
206
+ if refused:
207
+ 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
+ # The plain texts of this host's vaulted values are learned here, before the child.
211
+ self.view(host)
212
+ target = self.hosts[host]
213
+
214
+ def work() -> object:
215
+ value = self._templar_for(target).evaluate_expression(render.trusted(expr))
216
+ return self._result(value)
217
+
218
+ out = render.in_child(work, float(timeout or render.TIME_LIMIT))
219
+ result = out.pop("value", None)
220
+ answer: dict = {"host": host, "expr": expr, **out}
221
+ if isinstance(result, dict):
222
+ answer.update(result)
223
+ return answer
224
+
225
+ def watch(self, req: dict) -> dict:
226
+ exprs = [str(e) for e in (req.get("exprs") or []) if isinstance(e, str)][:50]
227
+ hosts = [str(h) for h in (req.get("hosts") or list(self.hosts)) if str(h) in self.hosts]
228
+ env = self.environment()
229
+ 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)
233
+ targets = {h: self.hosts[h] for h in hosts}
234
+
235
+ def work() -> object:
236
+ rows = []
237
+ for h, target in targets.items():
238
+ templar = self._templar_for(target)
239
+ for e in exprs:
240
+ if refused[e]:
241
+ rows.append({"host": h, "expr": e, "error": refused[e], "refused": True})
242
+ continue
243
+ if nolog[e]:
244
+ rows.append({"host": h, "expr": e, "type": "masked", "masked": "no_log"})
245
+ continue
246
+ try:
247
+ value = templar.evaluate_expression(render.trusted(e))
248
+ rows.append({"host": h, "expr": e, **self._result(value)})
249
+ except Exception as ex: # noqa: BLE001
250
+ rows.append({"host": h, "expr": e, "error": render.error_text(ex)})
251
+ return rows
252
+
253
+ limit = float(req.get("timeout") or render.TIME_LIMIT) * max(1, len(exprs))
254
+ out = render.in_child(work, min(limit, render.MAX_TIME_LIMIT))
255
+ if "error" in out:
256
+ return {"error": out["error"], "ms": out.get("ms")}
257
+ return {"results": out.get("value") or [], "ms": out.get("ms")}
258
+
259
+
260
+ # ---- pause points with settings at a step gate ----------------------------------------------
261
+ def point_settings(point: Mapping) -> dict:
262
+ out: dict = {}
263
+ cond = point.get("condition")
264
+ if isinstance(cond, str) and cond.strip():
265
+ out["condition"] = cond.strip()
266
+ hits = point.get("hits")
267
+ if isinstance(hits, int) and not isinstance(hits, bool) and hits > 0:
268
+ out["hits"] = hits
269
+ log = point.get("log")
270
+ if isinstance(log, str) and log.strip():
271
+ out["log"] = log
272
+ return out
273
+
274
+
275
+ def at_point(session: Session, strategy, play, hosts: list, node: str, point: Mapping) -> dict:
276
+ """A pause point's settings at its gate, for every host:
277
+ - condition: Jinja per host; all hosts pause if any matches (the matched hosts are named);
278
+ an error is reported and does not pause;
279
+ - hits: hosts arriving here (matching the condition, if any) are counted; it pauses where
280
+ the count reaches N;
281
+ - log: rendered per host (where the condition holds), masked; never pauses.
282
+ Returns {pause, matched, events}: events to append (log lines, errors, the hit count)."""
283
+ settings = point_settings(point)
284
+ cond, hits, log = settings.get("condition"), settings.get("hits"), settings.get("log")
285
+ events: list[dict] = []
286
+ names = [h.get_name() for h in hosts]
287
+ matched = names
288
+ if cond or log:
289
+ gate = Gate(session, strategy, play, hosts, "")
290
+ 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
294
+ gate.view(h)
295
+ masker = session.masker
296
+
297
+ def work() -> object:
298
+ rows = {}
299
+ for h in hosts:
300
+ templar = gate._templar_for(h)
301
+ row: dict = {}
302
+ if cond and not bad_cond:
303
+ try:
304
+ row["cond"] = bool(templar.evaluate_conditional(render.trusted(cond)))
305
+ except Exception as ex: # noqa: BLE001
306
+ row["cond"] = render.error_text(ex)
307
+ if log and not bad_log and row.get("cond", True) is True:
308
+ try:
309
+ value = templar.template(render.trusted(log))
310
+ text, kinds = masker.scrub(str(value), value)
311
+ row["log"] = text
312
+ if kinds:
313
+ row["masked"] = sorted(kinds)
314
+ except Exception as ex: # noqa: BLE001
315
+ row["logError"] = render.error_text(ex)
316
+ rows[h.get_name()] = row
317
+ return rows
318
+
319
+ out = render.in_child(work, GATE_LIMIT) if not (bad_cond and (bad_log or not log)) else {}
320
+ rows: dict = out.get("value") or {}
321
+ if "error" in out:
322
+ events.append({"event": "log", "node": node, "source": "point", "error": out["error"]})
323
+ if bad_cond:
324
+ events.append({"event": "log", "node": node, "source": "condition", "error": bad_cond})
325
+ if bad_log:
326
+ events.append({"event": "log", "node": node, "source": "log", "error": bad_log})
327
+ if cond:
328
+ matched = []
329
+ for h in names:
330
+ c = rows.get(h, {}).get("cond")
331
+ if c is True:
332
+ matched.append(h)
333
+ elif isinstance(c, str):
334
+ events.append(
335
+ {"event": "log", "node": node, "host": h, "source": "condition", "error": c}
336
+ )
337
+ if bad_cond or "error" in out:
338
+ matched = []
339
+ if log:
340
+ for h in names:
341
+ row = rows.get(h, {})
342
+ if "log" in row:
343
+ e = {"event": "log", "node": node, "host": h, "message": row["log"]}
344
+ if row.get("masked"):
345
+ e["masked"] = row["masked"]
346
+ events.append(e)
347
+ elif "logError" in row:
348
+ events.append(
349
+ {
350
+ "event": "log",
351
+ "node": node,
352
+ "host": h,
353
+ "source": "log",
354
+ "error": row["logError"],
355
+ }
356
+ )
357
+ pause = bool(matched) and not log
358
+ if hits:
359
+ before = session.hits.get(node, 0)
360
+ now = before + len(matched)
361
+ session.hits[node] = now
362
+ events.append({"event": "hits", "node": node, "count": now, "hits": hits})
363
+ pause = pause and before < hits <= now
364
+ return {"pause": pause, "matched": matched if cond else [], "events": events}
@@ -0,0 +1,289 @@
1
+ # Masking in the engine (ADR-0040 §4, AFS-223): a value leaves a debug run masked, with the reason
2
+ # and never its length. Five checks:
3
+ # 1. data tags: an EncryptedString, or a value with the VaultedValue tag (they survive a whole value
4
+ # and set_fact, and each leaf of a dict or list);
5
+ # 2. origin in a vault file: whole-file vault values carry no VaultedValue tag, only an Origin
6
+ # naming a file that starts with $ANSIBLE_VAULT;
7
+ # 3. secret-looking names at any depth;
8
+ # 4. no_log results (_ansible_no_log): the whole register;
9
+ # 5. known values: credential values (AFD_SECRETS_FILE), external secrets resolved by a server
10
+ # (AFD_EXTERNAL_SECRETS_FILE), the vault password (AFD_VAULT_FILE), the plain texts of vaulted
11
+ # values and the values under secret-looking names, each in its plain, base64, JSON-escaped and
12
+ # URL-quoted forms, case ignored. Filters drop the tags (b64encode, to_json, `~`): the text is
13
+ # what is left to match.
14
+ from __future__ import annotations
15
+
16
+ import base64
17
+ import contextlib
18
+ import json
19
+ import os
20
+ import re
21
+ import urllib.parse
22
+ from collections.abc import Mapping
23
+
24
+ try: # ansible-core 2.19+: data tagging
25
+ from ansible._internal._datatag._tags import Origin, VaultedValue
26
+ from ansible.module_utils._internal._datatag import AnsibleTagHelper
27
+ from ansible.parsing.vault import EncryptedString
28
+
29
+ TAGS = True
30
+ except ImportError: # pragma: no cover - older cores: the debugger refuses to run there
31
+ TAGS = False
32
+
33
+ # The import rules' secret-looking names (src/core/import/secrets.ts SECRET, afd_events.py).
34
+ SECRET_NAME = re.compile(r"pass(word|wd)?|secret|token|api_?key|private_?key|vault", re.IGNORECASE)
35
+ # Shorter known values are not matched: they would mask ordinary words and numbers.
36
+ MIN_KNOWN = 4
37
+ REDACTED = "********"
38
+ KINDS = ("vault", "no_log", "credential", "external", "name")
39
+ DEPTH = 40
40
+
41
+
42
+ class Masked:
43
+ """A masked value: what goes out in its place is {"__afd__": "masked", "masked": kind}."""
44
+
45
+ __slots__ = ("kind",)
46
+
47
+ def __init__(self, kind: str) -> None:
48
+ self.kind = kind
49
+
50
+
51
+ def leaves(value: object, out: set[str], depth: int = 0) -> None:
52
+ """Every string and number inside a value; a dict or list also as its compact JSON."""
53
+ if depth > DEPTH or isinstance(value, bool) or value is None:
54
+ return
55
+ if isinstance(value, (str, int, float)):
56
+ text = str.__str__(value) if isinstance(value, str) else str(value)
57
+ if text:
58
+ out.add(text)
59
+ elif isinstance(value, Mapping):
60
+ with contextlib.suppress(TypeError, ValueError):
61
+ out.add(json.dumps(value, separators=(",", ":"), default=str))
62
+ for v in value.values():
63
+ leaves(v, out, depth + 1)
64
+ elif isinstance(value, (list, tuple)):
65
+ with contextlib.suppress(TypeError, ValueError):
66
+ out.add(json.dumps(value, separators=(",", ":"), default=str))
67
+ for v in value:
68
+ leaves(v, out, depth + 1)
69
+
70
+
71
+ def forms(secret: str) -> set[str]:
72
+ """The forms a task commonly turns a secret into: plain, base64, JSON-escaped, URL-quoted."""
73
+ out = {secret}
74
+ raw = secret.encode("utf-8", "surrogatepass")
75
+ out.add(base64.b64encode(raw).decode())
76
+ out.add(json.dumps(secret, ensure_ascii=False)[1:-1])
77
+ out.add(json.dumps(secret)[1:-1])
78
+ out.add(urllib.parse.quote(secret, safe=""))
79
+ return {f for f in out if len(f) >= MIN_KNOWN}
80
+
81
+
82
+ class Known:
83
+ """Known secret values, each with the kind it is masked as; the first kind given stays."""
84
+
85
+ def __init__(self) -> None:
86
+ self._kinds: dict[str, str] = {}
87
+ self._re: re.Pattern[str] | None = None
88
+ self._dirty = False
89
+
90
+ def __len__(self) -> int:
91
+ return len(self._kinds)
92
+
93
+ def add(self, value: object, kind: str) -> None:
94
+ found: set[str] = set()
95
+ leaves(value, found)
96
+ for text in found:
97
+ for f in forms(text):
98
+ key = f.lower()
99
+ if key not in self._kinds:
100
+ self._kinds[key] = kind
101
+ self._dirty = True
102
+
103
+ def _pattern(self) -> re.Pattern[str] | None:
104
+ if self._dirty:
105
+ # Longest first: a secret that holds another is matched whole.
106
+ keys = sorted(self._kinds, key=len, reverse=True)
107
+ self._re = re.compile("|".join(re.escape(k) for k in keys), re.IGNORECASE)
108
+ self._dirty = False
109
+ return self._re if self._kinds else None
110
+
111
+ def find(self, text: str) -> str | None:
112
+ """The kind of the first known value inside `text`, or None."""
113
+ pattern = self._pattern()
114
+ if pattern is None:
115
+ return None
116
+ m = pattern.search(text)
117
+ return self._kinds.get(m.group(0).lower(), "credential") if m else None
118
+
119
+ def scrub(self, text: str) -> tuple[str, set[str]]:
120
+ """`text` with every known value replaced; the kinds that were found."""
121
+ pattern = self._pattern()
122
+ if pattern is None:
123
+ return text, set()
124
+ kinds: set[str] = set()
125
+
126
+ def repl(m: re.Match[str]) -> str:
127
+ kinds.add(self._kinds.get(m.group(0).lower(), "credential"))
128
+ return REDACTED
129
+
130
+ return pattern.sub(repl, text), kinds
131
+
132
+
133
+ def _json_file(path: str | None) -> object:
134
+ if not path:
135
+ return None
136
+ try:
137
+ with open(path, encoding="utf-8") as f:
138
+ return json.load(f)
139
+ except (OSError, ValueError):
140
+ return None
141
+
142
+
143
+ def load_known() -> Known:
144
+ """The run's known secrets, from the files its shell names (never from the environment)."""
145
+ known = Known()
146
+ # External secrets first: the first kind given stays, and a value a provider resolved is also
147
+ # a credential's variable (a login or become password) when a credential reads it from there.
148
+ external = _json_file(os.environ.get("AFD_EXTERNAL_SECRETS_FILE"))
149
+ if isinstance(external, Mapping):
150
+ for v in external.values():
151
+ known.add(v, "external")
152
+ elif isinstance(external, list):
153
+ known.add(external, "external")
154
+ secrets = _json_file(os.environ.get("AFD_SECRETS_FILE"))
155
+ if isinstance(secrets, Mapping):
156
+ for v in secrets.values():
157
+ known.add(v, "credential")
158
+ path = os.environ.get("AFD_VAULT_FILE")
159
+ if path:
160
+ try:
161
+ with open(path, encoding="utf-8") as f:
162
+ password = f.read().rstrip("\r\n")
163
+ if password:
164
+ known.add(password, "vault")
165
+ except OSError:
166
+ pass
167
+ return known
168
+
169
+
170
+ def is_vaulted(value: object) -> bool:
171
+ """Still encrypted (EncryptedString), or decrypted and tagged VaultedValue."""
172
+ if not TAGS:
173
+ return False
174
+ if isinstance(value, EncryptedString):
175
+ return True
176
+ try:
177
+ return VaultedValue in AnsibleTagHelper.tag_types(value)
178
+ except Exception: # noqa: BLE001 - a value that cannot say its tags has none
179
+ return False
180
+
181
+
182
+ class Masker:
183
+ """One per process: known values grow as vaulted values are met (their plain texts)."""
184
+
185
+ def __init__(self, known: Known | None = None) -> None:
186
+ self.known = known if known is not None else load_known()
187
+ self._vault_files: dict[str, bool] = {}
188
+ # Ciphertexts already decrypted: PBKDF2 costs about 10 ms each.
189
+ self._seen: set[str] = set()
190
+
191
+ def from_vault_file(self, value: object) -> bool:
192
+ if not TAGS or not isinstance(value, (str, Mapping, list)):
193
+ return False
194
+ try:
195
+ origin = Origin.get_tag(value)
196
+ except Exception: # noqa: BLE001
197
+ return False
198
+ path = getattr(origin, "path", None)
199
+ if not path:
200
+ return False
201
+ if path not in self._vault_files:
202
+ try:
203
+ with open(path, "rb") as f:
204
+ self._vault_files[path] = f.read(14) == b"$ANSIBLE_VAULT"
205
+ except OSError:
206
+ self._vault_files[path] = False
207
+ return self._vault_files[path]
208
+
209
+ def _plain_of(self, value: object) -> str | None:
210
+ """The plain text of a vaulted value, for the known values only (never output)."""
211
+ if TAGS and isinstance(value, EncryptedString):
212
+ key = str(getattr(value, "_ciphertext", ""))
213
+ if key in self._seen:
214
+ return None
215
+ self._seen.add(key)
216
+ try:
217
+ return str.__str__(value._decrypt()) # noqa: SLF001
218
+ except Exception: # noqa: BLE001 - no password for it: nothing to learn
219
+ return None
220
+ if isinstance(value, str) and (is_vaulted(value) or self.from_vault_file(value)):
221
+ return str.__str__(value)
222
+ return None
223
+
224
+ def learn(self, value: object, depth: int = 0, secret: bool = False) -> None:
225
+ """Learns the plain texts of vaulted values inside `value`, and the values under
226
+ secret-looking names, so derived copies (b64, JSON, concatenation) are caught."""
227
+ if depth > DEPTH:
228
+ return
229
+ plain = self._plain_of(value)
230
+ if plain:
231
+ self.known.add(plain, "vault")
232
+ return
233
+ if isinstance(value, Mapping):
234
+ if _is_hostvars(value):
235
+ return
236
+ for k, v in value.items():
237
+ self.learn(v, depth + 1, secret or bool(SECRET_NAME.search(str(k))))
238
+ elif isinstance(value, (list, tuple)):
239
+ for v in value:
240
+ self.learn(v, depth + 1, secret)
241
+ elif secret and isinstance(value, (str, int, float)) and not isinstance(value, bool):
242
+ text = str.__str__(value) if isinstance(value, str) else str(value)
243
+ # A template is not the secret: its value is not known here.
244
+ if "{{" not in text and "{%" not in text:
245
+ self.known.add(text, "name")
246
+
247
+ def kind(self, name: str, value: object) -> str | None:
248
+ """Why `value` under `name` is masked whole, or None."""
249
+ if is_vaulted(value) or self.from_vault_file(value):
250
+ return "vault"
251
+ if name and SECRET_NAME.search(str(name)):
252
+ return "name"
253
+ if isinstance(value, Mapping) and not _is_hostvars(value):
254
+ try:
255
+ if value.get("_ansible_no_log") or _censored(value.get("censored")):
256
+ return "no_log"
257
+ except Exception: # noqa: BLE001
258
+ return None
259
+ if isinstance(value, str):
260
+ return self.known.find(str.__str__(value))
261
+ return None
262
+
263
+ def mask(self, name: str, value: object, depth: int = 0) -> object:
264
+ """`value` (raw Ansible data) with each masked part replaced by a Masked."""
265
+ why = self.kind(name, value)
266
+ if why:
267
+ return Masked(why)
268
+ if depth > DEPTH:
269
+ return value
270
+ if isinstance(value, Mapping) and not _is_hostvars(value):
271
+ return {k: self.mask(str(k), v, depth + 1) for k, v in value.items()}
272
+ if isinstance(value, (list, tuple)):
273
+ return [self.mask("", v, depth + 1) for v in value]
274
+ return value
275
+
276
+ def scrub(self, text: str, value: object = None) -> tuple[str, set[str]]:
277
+ """A log line: a vaulted result is masked whole, known values inside it are replaced."""
278
+ if value is not None and is_vaulted(value):
279
+ return REDACTED, {"vault"}
280
+ return self.known.scrub(text)
281
+
282
+
283
+ def _censored(text: object) -> bool:
284
+ """The text a no_log result keeps in place of its output (registered without the flag)."""
285
+ return isinstance(text, str) and "no_log: true" in text
286
+
287
+
288
+ def _is_hostvars(value: object) -> bool:
289
+ return type(value).__name__ in ("HostVars", "HostVarsVars")