@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
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.
|
|
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.
|
|
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",
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
# Ansible Flow Designer debugger library (ADR-0040): masking (mask), capture (capture), safe render
|
|
2
|
+
# (render) and the debugger's side of a paused run (debug). Stdlib and ansible-core 2.19+ only.
|
|
3
|
+
# Imported by the afd_step strategy in debug runs (AFD_DEBUG=1): the probe folder goes on sys.path,
|
|
4
|
+
# so a run that is not a debug run never loads it.
|
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
# Capture at a pause (ADR-0040 §3, AFD-361): a host's variables by scope, masked, as JSON-safe
|
|
2
|
+
# values, with a size per value and per answer. Only at a pause, only when asked, from one
|
|
3
|
+
# variable_manager.get_vars(play, host) per host per pause.
|
|
4
|
+
#
|
|
5
|
+
# Scopes:
|
|
6
|
+
# - inputs: the step's inputs (its play vars, ADR-0011), as written: a template stays text;
|
|
7
|
+
# - host: inventory variables, set_fact values and registers;
|
|
8
|
+
# - flow: the run's extra vars (the flow's inputs and carried data);
|
|
9
|
+
# - facts: ansible_facts, only when asked for (expensive).
|
|
10
|
+
# Never sent: `vars` (2.19+: every variable again), `hostvars` (walking it renders every variable
|
|
11
|
+
# of every host and runs their lookups) and the other magic variables.
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import contextlib
|
|
15
|
+
import datetime
|
|
16
|
+
import json
|
|
17
|
+
import math
|
|
18
|
+
import re
|
|
19
|
+
from collections.abc import Mapping
|
|
20
|
+
|
|
21
|
+
from .mask import SECRET_NAME, Masked, Masker
|
|
22
|
+
|
|
23
|
+
try:
|
|
24
|
+
from ansible._internal._datatag._tags import TrustedAsTemplate
|
|
25
|
+
from ansible.module_utils._internal._datatag import AnsibleTagHelper
|
|
26
|
+
from ansible.parsing.vault import EncryptedString
|
|
27
|
+
|
|
28
|
+
TAGS = True
|
|
29
|
+
except ImportError: # pragma: no cover
|
|
30
|
+
TAGS = False
|
|
31
|
+
|
|
32
|
+
VALUE_LIMIT = 64 * 1024
|
|
33
|
+
ANSWER_LIMIT = 1024 * 1024
|
|
34
|
+
PAGE = 100
|
|
35
|
+
DEPTH = 40
|
|
36
|
+
SCOPES = ("inputs", "host", "flow", "facts")
|
|
37
|
+
SCOPE_NAMES = {
|
|
38
|
+
"inputs": "Step inputs",
|
|
39
|
+
"host": "Host variables",
|
|
40
|
+
"flow": "Flow data",
|
|
41
|
+
"facts": "Facts",
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
MAGIC = {
|
|
45
|
+
"hostvars", "groups", "group_names", "inventory_hostname", "inventory_hostname_short",
|
|
46
|
+
"inventory_dir", "inventory_file", "play_hosts", "playbook_dir", "role_names", "omit",
|
|
47
|
+
"environment", "ansible_play_hosts", "ansible_play_hosts_all", "ansible_play_batch",
|
|
48
|
+
"ansible_play_name", "ansible_play_role_names", "ansible_role_names", "ansible_version",
|
|
49
|
+
"ansible_check_mode", "ansible_diff_mode", "ansible_forks", "ansible_inventory_sources",
|
|
50
|
+
"ansible_playbook_python", "ansible_config_file", "ansible_verbosity", "ansible_run_tags",
|
|
51
|
+
"ansible_skip_tags", "ansible_dependent_role_names", "ansible_collection_name",
|
|
52
|
+
"ansible_search_path", "ansible_loop_var", "ansible_index_var", "ansible_parent_role_names",
|
|
53
|
+
"ansible_parent_role_paths", "ansible_role_name", "ansible_vault_id", "vars",
|
|
54
|
+
} # fmt: skip
|
|
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
|
+
# The record inputs task marks an input the flow knows is secret with this constant (AFD-341).
|
|
58
|
+
SECRET_MARK = "__afd_secret__"
|
|
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 + "')")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def plain(value: object, depth: int = 0) -> object:
|
|
65
|
+
"""A JSON-safe copy: masked parts as markers, vaulted values never decrypted, a template as
|
|
66
|
+
its text (flagged), odd types described."""
|
|
67
|
+
if isinstance(value, Masked):
|
|
68
|
+
return {"__afd__": "masked", "masked": value.kind}
|
|
69
|
+
if depth > DEPTH:
|
|
70
|
+
return {"__afd__": "deep"}
|
|
71
|
+
if TAGS and isinstance(value, EncryptedString):
|
|
72
|
+
return {"__afd__": "masked", "masked": "vault"}
|
|
73
|
+
if type(value).__name__ in ("HostVars", "HostVarsVars"):
|
|
74
|
+
return {"__afd__": "lazy", "type": "hostvars"}
|
|
75
|
+
if isinstance(value, bool) or value is None:
|
|
76
|
+
return value
|
|
77
|
+
if isinstance(value, int):
|
|
78
|
+
return int(value)
|
|
79
|
+
if isinstance(value, float):
|
|
80
|
+
return float(value) if math.isfinite(value) else str(value)
|
|
81
|
+
if isinstance(value, str):
|
|
82
|
+
text = str.__str__(value)
|
|
83
|
+
if "{{" in text or "{%" in text:
|
|
84
|
+
try:
|
|
85
|
+
if not TAGS or TrustedAsTemplate in AnsibleTagHelper.tag_types(value):
|
|
86
|
+
return {"__afd__": "template", "text": text}
|
|
87
|
+
except Exception: # noqa: BLE001
|
|
88
|
+
pass
|
|
89
|
+
return text
|
|
90
|
+
if isinstance(value, Mapping):
|
|
91
|
+
return {str(k): plain(v, depth + 1) for k, v in value.items()}
|
|
92
|
+
if isinstance(value, (list, tuple, set, frozenset)):
|
|
93
|
+
return [plain(v, depth + 1) for v in value]
|
|
94
|
+
if isinstance(value, bytes):
|
|
95
|
+
return {"__afd__": "bytes", "size": len(value)}
|
|
96
|
+
if isinstance(value, (datetime.date, datetime.time)):
|
|
97
|
+
return value.isoformat()
|
|
98
|
+
try:
|
|
99
|
+
shown = repr(value)[:200]
|
|
100
|
+
except Exception as ex: # noqa: BLE001 - an Undefined's repr may raise
|
|
101
|
+
shown = f"<{type(ex).__name__}>"
|
|
102
|
+
return {"__afd__": type(value).__name__, "repr": shown}
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def type_of(value: object) -> str:
|
|
106
|
+
"""The type a client shows: a marker's kind, or the JSON type."""
|
|
107
|
+
if isinstance(value, dict):
|
|
108
|
+
marker = value.get("__afd__")
|
|
109
|
+
if isinstance(marker, str):
|
|
110
|
+
return marker
|
|
111
|
+
return "dict"
|
|
112
|
+
if isinstance(value, list):
|
|
113
|
+
return "list"
|
|
114
|
+
if isinstance(value, bool):
|
|
115
|
+
return "bool"
|
|
116
|
+
if value is None:
|
|
117
|
+
return "null"
|
|
118
|
+
if isinstance(value, int):
|
|
119
|
+
return "int"
|
|
120
|
+
if isinstance(value, float):
|
|
121
|
+
return "float"
|
|
122
|
+
return "str"
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def to_json(value: object) -> str:
|
|
126
|
+
return json.dumps(value, ensure_ascii=False, separators=(",", ":"), default=str)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def entry(name: str | int, value: object) -> dict:
|
|
130
|
+
"""One variable or item, as a list shows it: name, type, size; a scalar's value (cut at
|
|
131
|
+
VALUE_LIMIT), a container's count. A masked value says why, never its size."""
|
|
132
|
+
kind = type_of(value)
|
|
133
|
+
out: dict[str, object] = {"name": name, "type": kind}
|
|
134
|
+
if kind == "masked":
|
|
135
|
+
out["masked"] = value["masked"] # type: ignore[index]
|
|
136
|
+
return out
|
|
137
|
+
if kind == "dict" or kind == "list":
|
|
138
|
+
out["count"] = len(value) # type: ignore[arg-type]
|
|
139
|
+
out["size"] = len(to_json(value))
|
|
140
|
+
return out
|
|
141
|
+
text = to_json(value)
|
|
142
|
+
out["size"] = len(text)
|
|
143
|
+
if kind == "str" and len(value) > VALUE_LIMIT: # type: ignore[arg-type]
|
|
144
|
+
out["value"] = value[:VALUE_LIMIT] # type: ignore[index]
|
|
145
|
+
out["cut"] = len(value) # type: ignore[arg-type]
|
|
146
|
+
elif len(text) > VALUE_LIMIT:
|
|
147
|
+
out["value"] = text[:VALUE_LIMIT]
|
|
148
|
+
out["cut"] = len(text)
|
|
149
|
+
else:
|
|
150
|
+
out["value"] = value
|
|
151
|
+
return out
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _walk_tasks(items: list, visit, depth: int = 0) -> None:
|
|
155
|
+
for item in items or []:
|
|
156
|
+
if depth < 8 and hasattr(item, "block"):
|
|
157
|
+
for part in ("block", "rescue", "always"):
|
|
158
|
+
_walk_tasks(getattr(item, part, None) or [], visit, depth + 1)
|
|
159
|
+
continue
|
|
160
|
+
visit(item)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def nolog_registers(play) -> set[str]:
|
|
164
|
+
"""The variables a no_log task of the play registers: from 2.19 a register keeps the task's
|
|
165
|
+
whole result, without the _ansible_no_log flag."""
|
|
166
|
+
found: set[str] = set()
|
|
167
|
+
|
|
168
|
+
def visit(task) -> None:
|
|
169
|
+
register = getattr(task, "register", None)
|
|
170
|
+
no_log = getattr(task, "no_log", None)
|
|
171
|
+
if not register or no_log in (None, False, "false", "False", "no"):
|
|
172
|
+
return
|
|
173
|
+
# 2.21: a mapping of names to what each registers; before: one name.
|
|
174
|
+
names = list(register) if isinstance(register, Mapping) else [register]
|
|
175
|
+
found.update(str(n) for n in names)
|
|
176
|
+
|
|
177
|
+
with contextlib.suppress(Exception):
|
|
178
|
+
for part in ("pre_tasks", "tasks", "post_tasks", "handlers"):
|
|
179
|
+
_walk_tasks(list(getattr(play, part, None) or []), visit)
|
|
180
|
+
return found
|
|
181
|
+
|
|
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
|
+
|
|
198
|
+
def secret_inputs(play) -> set[str]:
|
|
199
|
+
"""The inputs the flow knows are secret: the record inputs task writes them as a constant."""
|
|
200
|
+
found: set[str] = set()
|
|
201
|
+
|
|
202
|
+
def visit(task) -> None:
|
|
203
|
+
if str(getattr(task, "name", "") or "").endswith("] record inputs"):
|
|
204
|
+
for v in (getattr(task, "args", None) or {}).values():
|
|
205
|
+
found.update(_MARKED.findall(str.__str__(str(v))))
|
|
206
|
+
|
|
207
|
+
with contextlib.suppress(Exception): # nothing more known: the other checks still run
|
|
208
|
+
_walk_tasks(list(play.tasks or []), visit)
|
|
209
|
+
return found
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
class HostView:
|
|
213
|
+
"""A host's variables at one pause: masked and made plain once, then listed and paged."""
|
|
214
|
+
|
|
215
|
+
def __init__(
|
|
216
|
+
self,
|
|
217
|
+
all_vars: Mapping,
|
|
218
|
+
*,
|
|
219
|
+
play_vars: set[str],
|
|
220
|
+
extra: set[str],
|
|
221
|
+
secret: set[str],
|
|
222
|
+
masker: Masker,
|
|
223
|
+
nolog: set[str] | None = None,
|
|
224
|
+
inputs: set[str] | None = None,
|
|
225
|
+
) -> None:
|
|
226
|
+
self._vars = all_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
|
|
230
|
+
self._extra = extra
|
|
231
|
+
self._secret = secret
|
|
232
|
+
self._nolog = nolog or set()
|
|
233
|
+
self._masker = masker
|
|
234
|
+
self._scopes: dict[str, dict[str, object]] = {}
|
|
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))))
|
|
243
|
+
|
|
244
|
+
def scope_of(self, name: str) -> str | None:
|
|
245
|
+
if name in MAGIC or name in OWN_PLAY_VARS or name.startswith("ansible_facts"):
|
|
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
|
|
249
|
+
if name in self._extra:
|
|
250
|
+
return "flow"
|
|
251
|
+
if name in self._play_vars:
|
|
252
|
+
return "inputs"
|
|
253
|
+
facts = self._vars.get("ansible_facts")
|
|
254
|
+
if isinstance(facts, Mapping) and name.startswith("ansible_") and name[8:] in facts:
|
|
255
|
+
return None # a fact again, as a variable (INJECT_FACTS_AS_VARS)
|
|
256
|
+
if name == "ansible_local":
|
|
257
|
+
return None
|
|
258
|
+
return "host"
|
|
259
|
+
|
|
260
|
+
def scope(self, scope: str) -> dict[str, object]:
|
|
261
|
+
"""The scope's values by name, plain and masked."""
|
|
262
|
+
if scope in self._scopes:
|
|
263
|
+
return self._scopes[scope]
|
|
264
|
+
out: dict[str, object] = {}
|
|
265
|
+
if scope == "facts":
|
|
266
|
+
facts = self._vars.get("ansible_facts")
|
|
267
|
+
if isinstance(facts, Mapping):
|
|
268
|
+
for name in sorted(facts, key=str):
|
|
269
|
+
out[str(name)] = plain(self._masker.mask(str(name), facts[name]))
|
|
270
|
+
else:
|
|
271
|
+
for name in sorted(self._vars, key=str):
|
|
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)):
|
|
275
|
+
continue
|
|
276
|
+
if scope == "inputs" and name in self._secret:
|
|
277
|
+
out[name] = plain(Masked("credential"))
|
|
278
|
+
continue
|
|
279
|
+
if scope == "host" and name in self._nolog:
|
|
280
|
+
out[name] = plain(Masked("no_log"))
|
|
281
|
+
continue
|
|
282
|
+
out[name] = plain(self._masker.mask(str(name), self._vars[name]))
|
|
283
|
+
self._scopes[scope] = out
|
|
284
|
+
return out
|
|
285
|
+
|
|
286
|
+
def scopes(self, facts: bool = False) -> list[dict]:
|
|
287
|
+
"""Every scope with its variables' names, types and sizes, no values."""
|
|
288
|
+
out = []
|
|
289
|
+
for scope in SCOPES:
|
|
290
|
+
item: dict[str, object] = {"id": scope, "name": SCOPE_NAMES[scope]}
|
|
291
|
+
if scope == "facts":
|
|
292
|
+
item["expensive"] = True
|
|
293
|
+
if not facts:
|
|
294
|
+
out.append(item)
|
|
295
|
+
continue
|
|
296
|
+
names = []
|
|
297
|
+
for name, value in self.scope(scope).items():
|
|
298
|
+
e = entry(name, value)
|
|
299
|
+
e.pop("value", None)
|
|
300
|
+
e.pop("cut", None)
|
|
301
|
+
names.append(e)
|
|
302
|
+
item["vars"] = names
|
|
303
|
+
out.append(item)
|
|
304
|
+
return out
|
|
305
|
+
|
|
306
|
+
def page(self, scope: str, path: list, start: int = 0, count: int = PAGE) -> dict:
|
|
307
|
+
"""The value at `path` in a scope: a scalar whole (cut), a container's items paged."""
|
|
308
|
+
node: object = self.scope(scope)
|
|
309
|
+
for i, key in enumerate(path):
|
|
310
|
+
if isinstance(node, dict) and type_of(node) == "dict" and str(key) in node:
|
|
311
|
+
node = node[str(key)]
|
|
312
|
+
elif isinstance(node, list) and isinstance(key, int) and 0 <= key < len(node):
|
|
313
|
+
node = node[key]
|
|
314
|
+
else:
|
|
315
|
+
where = "/".join(str(p) for p in path[: i + 1])
|
|
316
|
+
return {"error": f"no such variable: {where}"}
|
|
317
|
+
kind = type_of(node)
|
|
318
|
+
if path and kind not in ("dict", "list"):
|
|
319
|
+
return entry(path[-1], node)
|
|
320
|
+
items: list[tuple[str | int, object]] = (
|
|
321
|
+
list(node.items()) if isinstance(node, dict) else list(enumerate(node)) # type: ignore[union-attr]
|
|
322
|
+
)
|
|
323
|
+
start = max(0, int(start))
|
|
324
|
+
count = max(1, min(int(count), 1000))
|
|
325
|
+
children = []
|
|
326
|
+
used = 0
|
|
327
|
+
more = False
|
|
328
|
+
for name, value in items[start : start + count]:
|
|
329
|
+
e = entry(name, value)
|
|
330
|
+
size = len(to_json(e))
|
|
331
|
+
if children and used + size > ANSWER_LIMIT:
|
|
332
|
+
more = True
|
|
333
|
+
break
|
|
334
|
+
used += size
|
|
335
|
+
children.append(e)
|
|
336
|
+
if start + len(children) < len(items):
|
|
337
|
+
more = True
|
|
338
|
+
out: dict[str, object] = {
|
|
339
|
+
"type": kind if path else "scope",
|
|
340
|
+
"total": len(items),
|
|
341
|
+
"start": start,
|
|
342
|
+
"children": children,
|
|
343
|
+
}
|
|
344
|
+
if more:
|
|
345
|
+
out["more"] = True
|
|
346
|
+
return out
|