@ansible-flow/assets 1.1.0 → 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 +1 -1
- package/package.json +1 -1
- package/probe/afd_lib/__init__.py +4 -0
- package/probe/afd_lib/capture.py +346 -0
- package/probe/afd_lib/debug.py +459 -0
- package/probe/afd_lib/mask.py +293 -0
- package/probe/afd_lib/render.py +249 -0
- package/probe/afd_lib/taint.py +344 -0
- package/probe/strategy_plugins/afd_step.py +399 -28
|
@@ -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"))
|