3"""Reviewed semantic fixtures for the uv cache policy checker."""
5from __future__
import annotations
10def bootstrap_module_mutations() -> tuple[tuple[str, str], ...]:
11 """Return caller-side module mutation and append-only attacks."""
14 "import bootstrap_uv_exec\n",
15 "import bootstrap_uv_exec\n"
16 "bootstrap_uv_exec._require_trusted_system_root = lambda _descriptor: None\n",
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",
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",
31 "import bootstrap_uv_exec\n",
32 "import bootstrap_uv_exec\nUV_BOOTSTRAP_UNREVIEWED_SURFACE = True\n",
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"
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"),
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."""
51 for node
in ast.parse(source).body
52 if isinstance(node, ast.FunctionDef)
and node.name == name
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)]
67def portable_execution_references() -> dict[str, tuple[tuple[str, str, int], ...]]:
68 """Return private-name snapshot and attack-test references."""
70 "portable_readonly_fd_selftest": (
71 (
"importlib",
"import_module", 1),
72 (
"controls",
"fcntl", 1),
73 (
"b.bootstrap_uv_exec",
"portable_named_exec_snapshot", 1),
77 (
"os",
"posix_spawn", 1),
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),
87 "portable_snapshot_path_attack_selftest": (
93 (
"mock.patch",
"object", 1),
94 (
"",
"expect_exec_failure", 1),
97 "portable_snapshot_unlink_failure_selftest": (
98 (
"mock.patch",
"object", 1),
99 (
"",
"expect_exec_failure", 1),
105def mode_execution_references() -> dict[str, tuple[tuple[str, str, int], ...]]:
106 """Return cache execution/status/mode selftest references."""
108 "cache_exact_fd_execution_selftest": (
109 (
"destination",
"rename", 1),
110 (
"replacement",
"replace", 1),
111 (
"subprocess",
"run", 1),
112 (
"b",
"run_cached_uv", 1),
115 "cache_same_inode_execution_selftest": (
117 (
"subprocess",
"run", 1),
118 (
"b",
"run_cached_uv", 1),
119 (
"b",
"expect_bootstrap_error", 1),
121 "cache_run_exit_status_selftest": (
122 (
"sys",
"executable", 1),
123 (
"os",
"posix_spawn", 1),
124 (
"os",
"waitpid", 1),
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),
135 "cache_mode_path_attack_selftest": (
137 (
"b",
"normalize_cached_modes", 1),
139 "bootstrap_run_status": (
140 (
"sys",
"executable", 1),
141 (
"os",
"posix_spawn", 1),
142 (
"os",
"waitpid", 1),
145 "cache_status_contract_selftest": (
146 (
"b",
"verify_cached_uv", 3),
147 (
"",
"bootstrap_run_status", 3),
149 "cache_mode_readonly_and_windows_selftest": (
150 (
"b",
"verify_cached_uv", 2),
151 (
"b",
"ensure_uv", 1),
156def _bootstrap_io_expected_bodies() -> dict[str, str]:
157 """Return reviewed cache-open and bounded-read bodies."""
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
165 bootstrap_uv_exec.write_atomic_nofollow(path, payload, mode)
166 except bootstrap_uv_exec.UvExecError as exc:
170def open_cache_fd(path):
172 return bootstrap_uv_exec.open_regular_nofollow(path)
173 except bootstrap_uv_exec.UvExecError as exc:
176 "read_stable_fd":
"""
177def read_stable_fd(descriptor, path, maximum):
178 before = os.fstat(descriptor)
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
195def _bootstrap_cache_expected_bodies() -> dict[str, str]:
196 """Return reviewed cache authentication and stability bodies."""
198 "authenticated_cache_fds":
"""
199def authenticated_cache_fds(archive_path, destination, asset_name, digest):
200 archive_fd = open_cache_fd(archive_path)
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
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
214 if destination_fd >= 0:
215 os.close(destination_fd)
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)
226 "verify_fd_path":
"""
227def verify_fd_path(path, descriptor, mode):
228 descriptor_state = os.fstat(descriptor)
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
239 same_file = (descriptor_state.st_dev, descriptor_state.st_ino) == (
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}")
252def _bootstrap_probe_expected_bodies() -> dict[str, str]:
253 """Return reviewed anonymous probe and nested selftest bodies."""
255 "probe_authenticated_uv":
"""
256def probe_authenticated_uv(binary, version):
258 completed = bootstrap_uv_exec.run_uv_snapshot(
259 binary, ["--version"], capture_output=True, timeout=10
261 except bootstrap_uv_exec.UvExecError as 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()}")
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__]},
272 runner = namespace.get("run_mode_selftest")
273 if not callable(runner):
274 fail("uv mode selftest module has no runner")
280def _bootstrap_run_expected_bodies() -> dict[str, str]:
281 """Return the reviewed cache-to-anonymous execution body."""
283 "propagate_child_status":
"""
284def propagate_child_status(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)
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")
302def run_cached_uv(manifest_path, cache_root, arguments, *, ensure):
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")
308 ensure_uv(manifest_path, cache_root)
310 else verify_cached_uv(manifest_path, cache_root)
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)
320 completed = bootstrap_uv_exec.run_uv_snapshot(binary, arguments)
321 except bootstrap_uv_exec.UvExecError as 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)
332def _bootstrap_cli_expected_bodies() -> dict[str, str]:
333 """Return the reviewed run-mode CLI parser body."""
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")
343 help="authenticate an existing cache without downloads or writes",
346 "--check-cache-modes",
348 help="check shared POSIX cache modes without authenticating or writing",
350 mode.add_argument("--print-path", action="store_true", help="print cache path without writes")
352 "--run", nargs=argparse.REMAINDER, metavar="UV_ARG",
353 help="run uv from an authenticated existing-cache snapshot",
356 "--ensure-and-run", nargs=argparse.REMAINDER, metavar="UV_ARG",
357 help="ensure the cache, then run uv from an authenticated snapshot",
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()
367def _bootstrap_main_expected_bodies() -> dict[str, str]:
368 """Return the reviewed mode-dispatch body."""
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)
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)
389 elif args.check_cache_modes:
390 verify_cached_modes(destination.parent / asset_name, destination)
392 elif args.verify_cache:
393 print(verify_cached_uv(args.manifest, args.cache_root))
395 print(ensure_uv(args.manifest, args.cache_root))
402def bootstrap_expected_bodies() -> dict[str, str]:
403 """Return every reviewed bootstrap semantic body."""
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(),