ra8-firmware 0.1.0
Bare-metal firmware for the Renesas RA8 family (RA8D2 / RA8P1)
Loading...
Searching...
No Matches
python_lock_policy_uv_cache_contracts.py
Go to the documentation of this file.
1# SPDX-License-Identifier: MIT
2# Copyright (c) 2026 Brighton Sikarskie
3"""Reviewed semantic fixtures for the uv cache policy checker."""
4
5from __future__ import annotations
6
7import ast
8
9
10def bootstrap_module_mutations() -> tuple[tuple[str, str], ...]:
11 """Return caller-side module mutation and append-only attacks."""
12 return (
13 (
14 "import bootstrap_uv_exec\n",
15 "import bootstrap_uv_exec\n"
16 "bootstrap_uv_exec._require_trusted_system_root = lambda _descriptor: None\n",
17 ),
18 (
19 "import bootstrap_uv_exec\n",
20 "import bootstrap_uv_exec\n"
21 'setattr(bootstrap_uv_exec, "_require_trusted_system_root", '
22 "lambda _descriptor: None)\n",
23 ),
24 (
25 "import bootstrap_uv_exec\n",
26 "import bootstrap_uv_exec\n"
27 'globals()["bootstrap_uv_exec"]._require_trusted_system_root = '
28 "lambda _descriptor: None\n",
29 ),
30 (
31 "import bootstrap_uv_exec\n",
32 "import bootstrap_uv_exec\nUV_BOOTSTRAP_UNREVIEWED_SURFACE = True\n",
33 ),
34 )
35
36
37def mode_module_mutations() -> tuple[tuple[str, str], ...]:
38 """Return mode-runner rebind and append-only attacks."""
39 anchor = " cache_mode_readonly_and_windows_selftest()\n"
40 return (
41 (anchor, f"{anchor}run_mode_selftest = lambda: None\n"),
42 (anchor, f'{anchor}globals()["run_mode_selftest"] = lambda: None\n'),
43 (anchor, f"{anchor}UV_MODE_TEST_UNREVIEWED_SURFACE = True\n"),
44 )
45
46
47def mutate_named_function_once(source: str, name: str, old: str, new: str) -> str:
48 """Apply one mutation only inside one named top-level Python function."""
49 functions = [
50 node
51 for node in ast.parse(source).body
52 if isinstance(node, ast.FunctionDef) and node.name == name
53 ]
54 if len(functions) != 1 or functions[0].end_lineno is None:
55 message = f"selftest function anchor drifted: {name}"
56 raise ValueError(message)
57 function = functions[0]
58 lines = source.splitlines(keepends=True)
59 segment = "".join(lines[function.lineno - 1 : function.end_lineno])
60 if segment.count(old) != 1:
61 message = f"selftest mutation anchor count changed in {name}: {old!r}"
62 raise ValueError(message)
63 lines[function.lineno - 1 : function.end_lineno] = [segment.replace(old, new, 1)]
64 return "".join(lines)
65
66
67def portable_execution_references() -> dict[str, tuple[tuple[str, str, int], ...]]:
68 """Return private-name snapshot and attack-test references."""
69 return {
70 "portable_readonly_fd_selftest": (
71 ("importlib", "import_module", 1),
72 ("controls", "fcntl", 1),
73 ("b.bootstrap_uv_exec", "portable_named_exec_snapshot", 1),
74 ("os", "fstat", 1),
75 ("os", "pread", 1),
76 ("os", "write", 1),
77 ("os", "posix_spawn", 1),
78 ("os", "waitpid", 1),
79 ("b", "fail", 6),
80 ),
81 "run_portable_snapshot": (("b.bootstrap_uv_exec", "portable_named_exec_snapshot", 1),),
82 "portable_snapshot_flags_selftest": (
83 ("mock.patch", "object", 1),
84 ("", "run_portable_snapshot", 1),
85 ("b", "fail", 3),
86 ),
87 "portable_snapshot_path_attack_selftest": (
88 ("os", "unlink", 1),
89 ("os", "rename", 1),
90 ("os", "symlink", 1),
91 ("os", "link", 1),
92 ("os", "chmod", 2),
93 ("mock.patch", "object", 1),
94 ("", "expect_exec_failure", 1),
95 ("b", "fail", 1),
96 ),
97 "portable_snapshot_unlink_failure_selftest": (
98 ("mock.patch", "object", 1),
99 ("", "expect_exec_failure", 1),
100 ("b", "fail", 1),
101 ),
102 }
103
104
105def mode_execution_references() -> dict[str, tuple[tuple[str, str, int], ...]]:
106 """Return cache execution/status/mode selftest references."""
107 return {
108 "cache_exact_fd_execution_selftest": (
109 ("destination", "rename", 1),
110 ("replacement", "replace", 1),
111 ("subprocess", "run", 1),
112 ("b", "run_cached_uv", 1),
113 ("b", "fail", 3),
114 ),
115 "cache_same_inode_execution_selftest": (
116 ("os", "fsync", 1),
117 ("subprocess", "run", 1),
118 ("b", "run_cached_uv", 1),
119 ("b", "expect_bootstrap_error", 1),
120 ),
121 "cache_run_exit_status_selftest": (
122 ("sys", "executable", 1),
123 ("os", "posix_spawn", 1),
124 ("os", "waitpid", 1),
125 ("b", "fail", 1),
126 ),
127 "cache_run_signal_status_selftest": (
128 ("sys", "executable", 1),
129 ("os", "posix_spawn", 1),
130 ("os", "waitpid", 1),
131 ("os", "WIFSIGNALED", 1),
132 ("os", "WTERMSIG", 1),
133 ("b", "fail", 2),
134 ),
135 "cache_mode_path_attack_selftest": (
136 ("os", "fchmod", 1),
137 ("b", "normalize_cached_modes", 1),
138 ),
139 "bootstrap_run_status": (
140 ("sys", "executable", 1),
141 ("os", "posix_spawn", 1),
142 ("os", "waitpid", 1),
143 ("b", "fail", 1),
144 ),
145 "cache_status_contract_selftest": (
146 ("b", "verify_cached_uv", 3),
147 ("", "bootstrap_run_status", 3),
148 ),
149 "cache_mode_readonly_and_windows_selftest": (
150 ("b", "verify_cached_uv", 2),
151 ("b", "ensure_uv", 1),
152 ),
153 }
154
155
156def _bootstrap_io_expected_bodies() -> dict[str, str]:
157 """Return reviewed cache-open and bounded-read bodies."""
158 return {
159 "write_atomic": """
160def write_atomic(path, payload, executable=False):
161 if os.name != "posix":
162 fail("authenticated uv cache writes require POSIX; use WSL on Windows")
163 mode = PRIVATE_EXECUTABLE_MODE if executable else PRIVATE_ARCHIVE_MODE
164 try:
165 bootstrap_uv_exec.write_atomic_nofollow(path, payload, mode)
166 except bootstrap_uv_exec.UvExecError as exc:
167 fail(str(exc))
168""",
169 "open_cache_fd": """
170def open_cache_fd(path):
171 try:
172 return bootstrap_uv_exec.open_regular_nofollow(path)
173 except bootstrap_uv_exec.UvExecError as exc:
174 fail(str(exc))
175""",
176 "read_stable_fd": """
177def read_stable_fd(descriptor, path, maximum):
178 before = os.fstat(descriptor)
179 try:
180 with os.fdopen(os.dup(descriptor), "rb") as source:
181 payload = source.read(maximum + 1)
182 after = os.fstat(descriptor)
183 except OSError as exc:
184 fail(f"cannot read cached uv artifact {path}: {exc}")
185 stable = ("st_dev", "st_ino", "st_size", "st_mtime_ns", "st_ctime_ns", "st_nlink")
186 if any(getattr(before, field) != getattr(after, field) for field in stable):
187 fail(f"cached uv artifact changed while authenticating: {path}")
188 if len(payload) > maximum:
189 fail(f"cached uv artifact exceeds policy: {path}")
190 return payload, after
191""",
192 }
193
194
195def _bootstrap_cache_expected_bodies() -> dict[str, str]:
196 """Return reviewed cache authentication and stability bodies."""
197 return {
198 "authenticated_cache_fds": """
199def authenticated_cache_fds(archive_path, destination, asset_name, digest):
200 archive_fd = open_cache_fd(archive_path)
201 destination_fd = -1
202 try:
203 destination_fd = open_cache_fd(destination)
204 payload, archive_state = read_stable_fd(archive_fd, archive_path, MAX_ASSET_BYTES)
205 verify_payload(payload, digest)
206 binary = executable_bytes(payload, asset_name)
207 installed, installed_state = read_stable_fd(
208 destination_fd, destination, MAX_UV_BINARY_BYTES
209 )
210 if not binary or installed != binary:
211 fail(f"cached uv executable differs from verified archive: {destination}")
212 yield archive_fd, destination_fd, binary, archive_state, installed_state
213 finally:
214 if destination_fd >= 0:
215 os.close(destination_fd)
216 os.close(archive_fd)
217""",
218 "verify_fd_unchanged": """
219def verify_fd_unchanged(path, descriptor, expected):
220 current = os.fstat(descriptor)
221 stable = ("st_dev", "st_ino", "st_size", "st_mtime_ns", "st_ctime_ns", "st_nlink")
222 if any(getattr(expected, field) != getattr(current, field) for field in stable):
223 message = f"cached uv artifact changed after authenticating: {path}"
224 raise CacheMetadataChangedError(message)
225""",
226 "verify_fd_path": """
227def verify_fd_path(path, descriptor, mode):
228 descriptor_state = os.fstat(descriptor)
229 reopened = -1
230 try:
231 reopened = open_cache_fd(path)
232 path_state = os.fstat(reopened)
233 except (BootstrapError, OSError) as exc:
234 message = f"cached uv path moved during permission repair: {path}: {exc}"
235 raise CachePathBindingError(message) from exc
236 finally:
237 if reopened >= 0:
238 os.close(reopened)
239 same_file = (descriptor_state.st_dev, descriptor_state.st_ino) == (
240 path_state.st_dev,
241 path_state.st_ino,
242 )
243 if not stat.S_ISREG(path_state.st_mode) or path_state.st_nlink != 1 or not same_file:
244 message = f"cached uv path moved during permission repair: {path}"
245 raise CachePathBindingError(message)
246 if stat.S_IMODE(descriptor_state.st_mode) != mode:
247 fail(f"cached uv permissions did not converge: {path}")
248""",
249 }
250
251
252def _bootstrap_probe_expected_bodies() -> dict[str, str]:
253 """Return reviewed anonymous probe and nested selftest bodies."""
254 return {
255 "probe_authenticated_uv": """
256def probe_authenticated_uv(binary, version):
257 try:
258 completed = bootstrap_uv_exec.run_uv_snapshot(
259 binary, ["--version"], capture_output=True, timeout=10
260 )
261 except bootstrap_uv_exec.UvExecError as exc:
262 fail(str(exc))
263 if completed.returncode != 0 or completed.stdout.split()[:2] != ["uv", version]:
264 fail(f"installed uv failed its version probe: {completed.stderr.strip()}")
265""",
266 "cache_mode_selftest": """
267def cache_mode_selftest():
268 namespace = runpy.run_path(
269 str(Path(__file__).with_name("bootstrap_uv_mode_selftest.py")),
270 init_globals={"bootstrap": sys.modules[__name__]},
271 )
272 runner = namespace.get("run_mode_selftest")
273 if not callable(runner):
274 fail("uv mode selftest module has no runner")
275 runner()
276""",
277 }
278
279
280def _bootstrap_run_expected_bodies() -> dict[str, str]:
281 """Return the reviewed cache-to-anonymous execution body."""
282 return {
283 "propagate_child_status": """
284def propagate_child_status(status):
285 if status >= 0:
286 return status
287 signum = -status
288 unmask = getattr(signal, "pthread_sigmask", None)
289 if signum >= signal.NSIG or unmask is None:
290 fail("authenticated uv child returned an unsupported signal status")
291 uncatchable = (signal.SIGKILL, signal.SIGSTOP)
292 try:
293 if signum not in uncatchable:
294 signal.signal(signum, signal.SIG_DFL)
295 unmask(signal.SIG_UNBLOCK, {signum})
296 os.kill(os.getpid(), signum)
297 except (OSError, ValueError) as exc:
298 fail(f"cannot propagate authenticated uv child signal: {exc}")
299 fail("authenticated uv child signal did not terminate the wrapper")
300""",
301 "run_cached_uv": """
302def run_cached_uv(manifest_path, cache_root, arguments, *, ensure):
303 if not arguments:
304 fail("authenticated uv execution requires at least one uv argument")
305 if os.name != "posix":
306 fail("authenticated uv execution requires POSIX; use WSL on Windows")
307 destination = (
308 ensure_uv(manifest_path, cache_root)
309 if ensure
310 else verify_cached_uv(manifest_path, cache_root)
311 )
312 manifest = load_manifest(manifest_path)
313 _, asset_name, digest = select_asset(manifest)
314 archive_path = destination.parent / asset_name
315 with authenticated_cache_fds(archive_path, destination, asset_name, digest) as descriptors:
316 archive_fd, destination_fd, binary, archive_state, installed_state = descriptors
317 verify_fd_mode(archive_path, archive_fd, PUBLIC_ARCHIVE_MODE)
318 verify_fd_mode(destination, destination_fd, PUBLIC_EXECUTABLE_MODE)
319 try:
320 completed = bootstrap_uv_exec.run_uv_snapshot(binary, arguments)
321 except bootstrap_uv_exec.UvExecError as exc:
322 fail(str(exc))
323 verify_fd_unchanged(archive_path, archive_fd, archive_state)
324 verify_fd_unchanged(destination, destination_fd, installed_state)
325 verify_fd_path(archive_path, archive_fd, PUBLIC_ARCHIVE_MODE)
326 verify_fd_path(destination, destination_fd, PUBLIC_EXECUTABLE_MODE)
327 return propagate_child_status(completed.returncode)
328""",
329 }
330
331
332def _bootstrap_cli_expected_bodies() -> dict[str, str]:
333 """Return the reviewed run-mode CLI parser body."""
334 return {
335 "parse_args": """
336def parse_args():
337 parser = argparse.ArgumentParser(description=__doc__)
338 mode = parser.add_mutually_exclusive_group(required=True)
339 mode.add_argument("--ensure", action="store_true", help="install and print pinned uv")
340 mode.add_argument(
341 "--verify-cache",
342 action="store_true",
343 help="authenticate an existing cache without downloads or writes",
344 )
345 mode.add_argument(
346 "--check-cache-modes",
347 action="store_true",
348 help="check shared POSIX cache modes without authenticating or writing",
349 )
350 mode.add_argument("--print-path", action="store_true", help="print cache path without writes")
351 mode.add_argument(
352 "--run", nargs=argparse.REMAINDER, metavar="UV_ARG",
353 help="run uv from an authenticated existing-cache snapshot",
354 )
355 mode.add_argument(
356 "--ensure-and-run", nargs=argparse.REMAINDER, metavar="UV_ARG",
357 help="ensure the cache, then run uv from an authenticated snapshot",
358 )
359 mode.add_argument("--selftest", action="store_true", help="run offline fail-closed tests")
360 parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
361 parser.add_argument("--cache-root", type=Path, default=DEFAULT_CACHE)
362 return parser.parse_args()
363""",
364 }
365
366
367def _bootstrap_main_expected_bodies() -> dict[str, str]:
368 """Return the reviewed mode-dispatch body."""
369 return {
370 "main": """
371def main():
372 args = parse_args()
373 if args.selftest:
374 run_selftest()
375 status = 0
376 elif args.run is not None:
377 status = run_cached_uv(args.manifest, args.cache_root, args.run, ensure=False)
378 elif args.ensure_and_run is not None:
379 status = run_cached_uv(args.manifest, args.cache_root, args.ensure_and_run, ensure=True)
380 else:
381 manifest = load_manifest(args.manifest)
382 _, asset_name, _ = select_asset(manifest)
383 version = manifest["version"]
384 if not isinstance(version, str):
385 fail("uv manifest version is not a string")
386 destination = cache_destination(args.cache_root, version, asset_name)
387 if args.print_path:
388 print(destination)
389 elif args.check_cache_modes:
390 verify_cached_modes(destination.parent / asset_name, destination)
391 print(destination)
392 elif args.verify_cache:
393 print(verify_cached_uv(args.manifest, args.cache_root))
394 else:
395 print(ensure_uv(args.manifest, args.cache_root))
396 status = 0
397 return status
398""",
399 }
400
401
402def bootstrap_expected_bodies() -> dict[str, str]:
403 """Return every reviewed bootstrap semantic body."""
404 return {
405 **_bootstrap_io_expected_bodies(),
406 **_bootstrap_cache_expected_bodies(),
407 **_bootstrap_probe_expected_bodies(),
408 **_bootstrap_run_expected_bodies(),
409 **_bootstrap_cli_expected_bodies(),
410 **_bootstrap_main_expected_bodies(),
411 }