@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,293 @@
|
|
|
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
|
+
# 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
|
|
257
|
+
if name and SECRET_NAME.search(str(name)):
|
|
258
|
+
return "name"
|
|
259
|
+
if isinstance(value, Mapping) and not _is_hostvars(value):
|
|
260
|
+
try:
|
|
261
|
+
if value.get("_ansible_no_log") or _censored(value.get("censored")):
|
|
262
|
+
return "no_log"
|
|
263
|
+
except Exception: # noqa: BLE001
|
|
264
|
+
return None
|
|
265
|
+
return None
|
|
266
|
+
|
|
267
|
+
def mask(self, name: str, value: object, depth: int = 0) -> object:
|
|
268
|
+
"""`value` (raw Ansible data) with each masked part replaced by a Masked."""
|
|
269
|
+
why = self.kind(name, value)
|
|
270
|
+
if why:
|
|
271
|
+
return Masked(why)
|
|
272
|
+
if depth > DEPTH:
|
|
273
|
+
return value
|
|
274
|
+
if isinstance(value, Mapping) and not _is_hostvars(value):
|
|
275
|
+
return {k: self.mask(str(k), v, depth + 1) for k, v in value.items()}
|
|
276
|
+
if isinstance(value, (list, tuple)):
|
|
277
|
+
return [self.mask("", v, depth + 1) for v in value]
|
|
278
|
+
return value
|
|
279
|
+
|
|
280
|
+
def scrub(self, text: str, value: object = None) -> tuple[str, set[str]]:
|
|
281
|
+
"""A log line: a vaulted result is masked whole, known values inside it are replaced."""
|
|
282
|
+
if value is not None and is_vaulted(value):
|
|
283
|
+
return REDACTED, {"vault"}
|
|
284
|
+
return self.known.scrub(text)
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _censored(text: object) -> bool:
|
|
288
|
+
"""The text a no_log result keeps in place of its output (registered without the flag)."""
|
|
289
|
+
return isinstance(text, str) and "no_log: true" in text
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _is_hostvars(value: object) -> bool:
|
|
293
|
+
return type(value).__name__ in ("HostVars", "HostVarsVars")
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
# Safe render at a pause (ADR-0040 §5, AFD-370): evaluate, watch, pause point conditions and log
|
|
2
|
+
# messages. Before rendering, the Jinja AST is checked: lookup, query and q calls and the vault and
|
|
3
|
+
# unvault filters are refused. The render runs in a forked child: lookups blocked while it runs
|
|
4
|
+
# (also those a lazy variable runs, which disable_lookups misses), a memory cap, and a time limit
|
|
5
|
+
# the parent enforces by killing the child. No SIGALRM: an in-process alarm corrupted the template
|
|
6
|
+
# context on 2.19 and did not stop a loop on 2.21. Nothing the child changes reaches the run.
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import resource
|
|
12
|
+
import select
|
|
13
|
+
import signal
|
|
14
|
+
import time
|
|
15
|
+
from collections.abc import Callable
|
|
16
|
+
|
|
17
|
+
try:
|
|
18
|
+
from ansible._internal._datatag._tags import TrustedAsTemplate
|
|
19
|
+
|
|
20
|
+
TAGS = True
|
|
21
|
+
except ImportError: # pragma: no cover
|
|
22
|
+
TAGS = False
|
|
23
|
+
|
|
24
|
+
TIME_LIMIT = 2.0
|
|
25
|
+
MAX_TIME_LIMIT = 10.0
|
|
26
|
+
MEMORY_EXTRA = 512 * 1024 * 1024
|
|
27
|
+
EXPR_LIMIT = 4000
|
|
28
|
+
# Lookups a lazy variable may still run while rendering: they read only what is already there.
|
|
29
|
+
LOOKUP_ALLOW = {
|
|
30
|
+
"vars", "varnames", "items", "list", "dict", "indexed_items", "sequence", "subelements",
|
|
31
|
+
"nested", "together", "cartesian",
|
|
32
|
+
} # fmt: skip
|
|
33
|
+
LOOKUP_CALLS = {"lookup", "query", "q"}
|
|
34
|
+
FILTER_DENY = {"vault", "unvault"}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Blocked(Exception):
|
|
38
|
+
pass
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _short(name: object) -> str:
|
|
42
|
+
return str(name).rsplit(".", 1)[-1]
|
|
43
|
+
|
|
44
|
+
|
|
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")."""
|
|
48
|
+
if not expr.strip():
|
|
49
|
+
return "Nothing to evaluate"
|
|
50
|
+
if len(expr) > EXPR_LIMIT:
|
|
51
|
+
return f"The expression is longer than {EXPR_LIMIT} characters"
|
|
52
|
+
if any(m in expr for m in ("{{", "}}", "{%", "%}", "{#", "#}")):
|
|
53
|
+
return "Write an expression without {{ }} or {% %}"
|
|
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
|
|
91
|
+
|
|
92
|
+
|
|
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"."""
|
|
111
|
+
try:
|
|
112
|
+
from jinja2 import nodes
|
|
113
|
+
|
|
114
|
+
ast = environment.parse(text)
|
|
115
|
+
except Exception as ex: # noqa: BLE001
|
|
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"
|
|
119
|
+
for call in ast.find_all(nodes.Call):
|
|
120
|
+
if isinstance(call.node, nodes.Name) and call.node.name in LOOKUP_CALLS:
|
|
121
|
+
return f"{call.node.name}(): {lookups}"
|
|
122
|
+
for name in ast.find_all(nodes.Name):
|
|
123
|
+
if name.name in LOOKUP_CALLS:
|
|
124
|
+
return f"{name.name}: {lookups}"
|
|
125
|
+
for f in ast.find_all(nodes.Filter):
|
|
126
|
+
if _short(f.name) in FILTER_DENY:
|
|
127
|
+
return f"The {f.name} filter is not allowed in {where}"
|
|
128
|
+
for attr in ast.find_all(nodes.Getattr):
|
|
129
|
+
if str(attr.attr).startswith("_"):
|
|
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}"
|
|
134
|
+
return None
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def names_in(expr: str, environment) -> set[str]:
|
|
138
|
+
"""The variable names an expression reads."""
|
|
139
|
+
try:
|
|
140
|
+
from jinja2 import nodes
|
|
141
|
+
|
|
142
|
+
ast = environment.parse("{{ " + expr + " }}")
|
|
143
|
+
except Exception: # noqa: BLE001
|
|
144
|
+
return set()
|
|
145
|
+
return {n.name for n in ast.find_all(nodes.Name)}
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def block_lookups() -> None:
|
|
149
|
+
"""Every lookup outside LOOKUP_ALLOW raises. Patches the module global the templating engine
|
|
150
|
+
uses (a private one: the engine suite checks it on every core): call it in the child only."""
|
|
151
|
+
import ansible._internal._templating._jinja_plugins as jp
|
|
152
|
+
|
|
153
|
+
real = jp.lookup_loader
|
|
154
|
+
|
|
155
|
+
class _Guard:
|
|
156
|
+
def get(self, name, *a, **kw):
|
|
157
|
+
if _short(name) not in LOOKUP_ALLOW:
|
|
158
|
+
raise Blocked(
|
|
159
|
+
f"lookups are not allowed while debugging (a variable runs lookup {name!r})"
|
|
160
|
+
)
|
|
161
|
+
return real.get(name, *a, **kw)
|
|
162
|
+
|
|
163
|
+
def __getattr__(self, attr):
|
|
164
|
+
return getattr(real, attr)
|
|
165
|
+
|
|
166
|
+
jp.lookup_loader = _Guard()
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def trusted(text: str) -> object:
|
|
170
|
+
return TrustedAsTemplate().tag(text) if TAGS else text
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _vm_bytes() -> int:
|
|
174
|
+
try:
|
|
175
|
+
with open("/proc/self/statm") as f:
|
|
176
|
+
return int(f.read().split()[0]) * os.sysconf("SC_PAGE_SIZE")
|
|
177
|
+
except (OSError, ValueError):
|
|
178
|
+
return 0
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def error_text(ex: BaseException) -> str:
|
|
182
|
+
text = str(ex).strip().splitlines()
|
|
183
|
+
first = text[0] if text else ""
|
|
184
|
+
if isinstance(ex, MemoryError):
|
|
185
|
+
return "The expression needed more memory than a debugger may use"
|
|
186
|
+
return f"{type(ex).__name__}: {first[:400]}" if first else type(ex).__name__
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def in_child(fn: Callable[[], object], timeout: float = TIME_LIMIT) -> dict:
|
|
190
|
+
"""Runs fn() in a forked child with a memory cap; the parent kills it at `timeout`.
|
|
191
|
+
Returns {"value": <JSON>} or {"error": <text>}, and the time it took in ms."""
|
|
192
|
+
timeout = max(0.1, min(float(timeout), MAX_TIME_LIMIT))
|
|
193
|
+
r, w = os.pipe()
|
|
194
|
+
t0 = time.perf_counter()
|
|
195
|
+
pid = os.fork()
|
|
196
|
+
if pid == 0: # the child: no display, no logging; it ends with os._exit
|
|
197
|
+
try:
|
|
198
|
+
os.close(r)
|
|
199
|
+
base = _vm_bytes()
|
|
200
|
+
if base:
|
|
201
|
+
limit = base + MEMORY_EXTRA
|
|
202
|
+
resource.setrlimit(resource.RLIMIT_AS, (limit, limit))
|
|
203
|
+
block_lookups()
|
|
204
|
+
data = json.dumps({"value": fn()}, default=str).encode()
|
|
205
|
+
except BaseException as ex: # noqa: BLE001
|
|
206
|
+
try:
|
|
207
|
+
data = json.dumps({"error": error_text(ex)}).encode()
|
|
208
|
+
except BaseException: # noqa: BLE001
|
|
209
|
+
data = b'{"error": "The expression failed"}'
|
|
210
|
+
try:
|
|
211
|
+
view = memoryview(data)
|
|
212
|
+
while view:
|
|
213
|
+
n = os.write(w, view)
|
|
214
|
+
view = view[n:]
|
|
215
|
+
finally:
|
|
216
|
+
os._exit(0)
|
|
217
|
+
os.close(w)
|
|
218
|
+
chunks: list[bytes] = []
|
|
219
|
+
deadline = time.monotonic() + timeout
|
|
220
|
+
killed = False
|
|
221
|
+
try:
|
|
222
|
+
while True:
|
|
223
|
+
left = deadline - time.monotonic()
|
|
224
|
+
if left <= 0:
|
|
225
|
+
os.kill(pid, signal.SIGKILL)
|
|
226
|
+
killed = True
|
|
227
|
+
break
|
|
228
|
+
ready, _, _ = select.select([r], [], [], left)
|
|
229
|
+
if ready:
|
|
230
|
+
chunk = os.read(r, 65536)
|
|
231
|
+
if not chunk:
|
|
232
|
+
break
|
|
233
|
+
chunks.append(chunk)
|
|
234
|
+
finally:
|
|
235
|
+
os.close(r)
|
|
236
|
+
os.waitpid(pid, 0)
|
|
237
|
+
ms = round((time.perf_counter() - t0) * 1000, 1)
|
|
238
|
+
if killed:
|
|
239
|
+
return {
|
|
240
|
+
"error": f"Stopped after the time limit of {timeout:g} s",
|
|
241
|
+
"ms": ms,
|
|
242
|
+
"timeout": True,
|
|
243
|
+
}
|
|
244
|
+
try:
|
|
245
|
+
out = json.loads(b"".join(chunks) or b'{"error": "No answer (the memory limit?)"}')
|
|
246
|
+
except ValueError:
|
|
247
|
+
out = {"error": "No answer (the memory limit?)"}
|
|
248
|
+
out["ms"] = ms
|
|
249
|
+
return out
|