3"""Release/runtime policy checks for the managed uv-cache provisioner."""
5from __future__
import annotations
10from python_lock_policy_uv_cache_release_contracts
import (
12 provisioner_expected_bodies,
13 provisioner_mutations,
14 provisioner_release_tmp_contract,
17EXPECTED_PROVISIONER_UV_RUNS = 3
18EXPECTED_SELFTEST_DISPATCH_CALLS = 3
19RELEASE_SELFTEST_PATH =
"scripts/dev/provision_dev_box_toolchain_selftest.bash"
22def _shell_function(source: str, name: str, indent: str =
" ") -> list[str] |
None:
23 """Extract one two-space-indented top-level Bash function semantically."""
24 source_lines = source.splitlines()
25 starts = [index
for index, line
in enumerate(source_lines)
if line == f
"{indent}{name}() {{"]
31 for index
in range(starts[0] + 1, len(source_lines))
32 if source_lines[index] == f
"{indent}}}"
39 " ".join(line.strip().split())
40 for line
in source_lines[starts[0] + 1 : end]
41 if line.strip()
and not line.lstrip().startswith(
"#")
45def _shell_subshell_function(source: str, name: str, indent: str =
" ") -> list[str] |
None:
46 """Extract one two-space-indented top-level Bash subshell function."""
47 source_lines = source.splitlines()
48 starts = [index
for index, line
in enumerate(source_lines)
if line == f
"{indent}{name}() ("]
54 for index
in range(starts[0] + 1, len(source_lines))
55 if source_lines[index] == f
"{indent})"
62 " ".join(line.strip().split())
63 for line
in source_lines[starts[0] + 1 : end]
64 if line.strip()
and not line.lstrip().startswith(
"#")
68def _expected_shell_body(source: str, name: str) -> list[str]:
69 """Return one canonical shell function body."""
70 body = _shell_function(source, name)
72 message = f
"canonical shell fixture is missing {name}"
73 raise ValueError(message)
77def _provisioner_body(source: str, selftest_source: str, name: str) -> list[str] |
None:
78 """Return one function from exactly one of the split provisioner surfaces."""
80 _shell_function(source, name),
81 _shell_function(selftest_source, name,
""),
83 present = [body
for body
in bodies
if body
is not None]
84 return present[0]
if len(present) == 1
else None
87def _contains_once(lines: list[str], sequence: list[str]) -> bool:
88 """Return whether one exact contiguous semantic shell sequence occurs."""
90 lines[index : index + len(sequence)] == sequence
91 for index
in range(len(lines) - len(sequence) + 1)
96def _provisioner_release_tmp_findings(source: str, selftest_source: str) -> list[str]:
97 """Bind privileged release installers to one owned temporary root."""
98 findings: list[str] = []
99 contract = provisioner_release_tmp_contract()
102 "release_tmp_identity",
103 "release_tmp_root_is_safe",
104 "release_tmp_is_safe",
105 "release_tmp_pending_cleanup",
106 "release_tmp_cleanup_owned",
108 "release_tmp_signal",
109 "install_release_tmp_traps",
110 "release_tmp_allocation_checkpoint",
112 "release_tmp_path_is_absent",
113 "release_tmp_signal_case",
114 "release_tmp_signal_child",
115 "release_tmp_replacement_refusal",
116 "release_tmp_wrong_owner_refusal",
117 "release_tmp_contract_selftest",
120 f
"dev-box provisioner {name} semantic contract drifted"
121 for name
in helper_names
122 if _provisioner_body(source, selftest_source, name) != _expected_shell_body(contract, name)
124 if source.count(
" unset PYTHONHOME PYTHONPATH RA8_TOOL_VENV TMPDIR\n") != 1:
125 findings.append(
"dev-box privileged boundary does not sanitize TMPDIR exactly once")
126 if any(token
in source
or token
in selftest_source
for token
in (
"mktemp -d",
"trap 'rm -rf")):
127 findings.append(
"dev-box provisioner retains an unowned temporary-directory authority")
129 "install_shellcheck",
131 "install_actionlint",
136 body = _shell_subshell_function(source, name)
139 or body.count(
"release_tmp_begin") != 1
140 or body.count(
'tmp="$RELEASE_TMP_DIR"') != 1
142 findings.append(f
"dev-box {name} does not use the shared release temporary root")
146def _provisioner_install_findings(source: str) -> list[str]:
147 """Bind the provisioner's mutating install path."""
148 install = _shell_function(source,
"install_python_tools")
150 'local venv="$1" cache_modes_current=1',
151 "if ! uv_cache_modes_current; then",
152 "cache_modes_current=0",
154 "uv_bootstrap_apply --ensure >/dev/null",
155 'uv_cache_apply_report "${cache_modes_current}"',
157 if install
is None or install[: len(install_prefix)] != install_prefix:
158 return [
"dev-box apply path is not bound to mode-check, ensure, and exact report"]
159 run_calls = sum(line.startswith(
"uv_bootstrap_apply_run ")
for line
in install)
160 if run_calls != EXPECTED_PROVISIONER_UV_RUNS
or any(
"uv_bin" in line
for line
in install):
161 return [
"dev-box apply path does not execute all uv work through bootstrap snapshots"]
165def _provisioner_dispatch_findings(source: str) -> list[str]:
166 """Bind the provisioner's read-only branch and selftest dispatch."""
167 findings: list[str] = []
168 main = _shell_function(source,
"main")
171 "if uv_cache_check; then",
174 "uv_check_status=$?",
175 'return "${uv_check_status}"',
179 if main
is None or not _contains_once(main, check_sequence):
180 findings.append(
"dev-box --check-only path is not directly bound to uv_cache_check")
181 dispatch = list(provisioner_dispatch())
183 " ".join(line.strip().split())
184 for line
in source.splitlines()
185 if line.strip()
and not line.lstrip().startswith(
"#")
187 if not _contains_once(semantic, dispatch):
188 findings.append(
"dev-box provisioner contract selftest is not the production dispatch")
192def _provisioner_selftest_findings(selftest_source: str) -> list[str]:
193 """Bind the contract test to every status and apply-marker direction."""
194 body = _shell_function(selftest_source,
"uv_cache_contract_selftest",
"")
195 joined =
" ".join(body
or [])
197 'uv_cache_check_scenario_selftest 0 "" current-path',
198 '2 " ... uv-cache restricted -> shared (planned)" drift-path',
199 '1 "error: authenticated uv cache check failed" invalid-path',
200 '"$(uv_cache_apply_report 0)" != " ... uv-cache restricted -> shared"',
201 "release_selftest_loader_refusals || return 1",
202 "release_tmp_contract_selftest",
203 "python_no_bytecode_residue_selftest",
204 "current) return 0 ;;",
205 "drift) return 2 ;;",
206 "invalid) return 1 ;;",
208 if body
is None or any(token
not in joined
for token
in required):
209 return [
"dev-box provisioner contract selftest call chain drifted"]
213def _release_loader_runtime_findings(selftest_source: str) -> list[str]:
214 """Bind hostile loader tests to every reviewed refusal direction."""
215 case_body =
" ".join(
216 _shell_subshell_function(selftest_source,
"release_selftest_loader_case",
"")
or []
218 matrix_body =
" ".join(
219 _shell_function(selftest_source,
"release_selftest_loader_refusals",
"")
or []
222 'if [[ "$kind" == "parent-symlink" ]]; then',
223 'ln -s "${fixture_dir##*/}" "$directory" || return 1',
224 "printf 'return 42\\n' >\"$helper\"",
225 '[[ "$status" == "42" && -z "${RA8_RELEASE_LOADER_MARKER:-}" ]]',
226 '[[ "$status" != "0" && -z "${RA8_RELEASE_LOADER_MARKER:-}" ]]',
227 'source_release_selftest_helper_from "$main" "$helper" "$directory" "$digest"',
230 "safe parent-symlink main-symlink main-hardlink main-mode",
231 "helper-symlink helper-hardlink helper-mode digest inplace path-replace return-42",
232 "main-owner main-group helper-owner helper-group",
233 'release_selftest_loader_case "$root" "$kind" || return 1',
235 if any(token
not in case_body
for token
in case_tokens)
or any(
236 token
not in matrix_body
for token
in matrix_tokens
238 return [
"dev-box release selftest hostile runtime matrix drifted"]
242def _release_selftest_loader_findings(source: str, selftest_source: str) -> list[str]:
243 """Bind the split release selftest to one privileged two-FD loader."""
244 findings: list[str] = []
245 digest = hashlib.sha256(selftest_source.encode(
"utf-8")).hexdigest()
246 pin = re.findall(
r'^ RELEASE_SELFTEST_RAW_SHA256="([0-9a-f]{64})"$', source, re.MULTILINE)
248 findings.append(
"dev-box release selftest raw digest is stale or ambiguous")
250 "local identity digest source_path source_status=0",
251 'local helper="$ROOT/scripts/dev/provision_dev_box_toolchain_selftest.bash"',
252 'local main="$ROOT/scripts/dev/provision_dev_box_toolchain.sh"',
253 'local expected_dir="$ROOT/scripts/dev" expected_digest="$RELEASE_SELFTEST_RAW_SHA256"',
254 '[[ "$resolved" == "$expected_dir" && -f "$main" && ! -L "$main" &&',
255 '"$(stat -c \'%h\' "$main")" == "1" && "$(stat -c \'%a\' "$main")" == "755"',
256 '("$main_owner" == "0" || "$main_owner" == "$caller_uid")',
257 '("$caller_uid" != "0" || ("$main_owner" == "0" && "$main_group" == "0"))',
258 '-f "$helper" && ! -L "$helper" && "$(stat -c \'%h\' "$helper")" == "1"',
259 '"$(stat -c \'%a\' "$helper")" == "644"',
260 '"$(stat -c \'%u\' "$helper")" == "$main_owner"',
261 '"$(stat -c \'%g\' "$helper")" == "$main_group"',
264 '"$(stat -Lc \'%d:%i\' /proc/self/fd/7)" == "$identity"',
265 '"$(stat -Lc \'%d:%i\' /proc/self/fd/8)" == "$identity"',
266 'digest="$(sha256sum <&7)"',
267 '[[ "$digest" == "$expected_digest" ]]',
268 "release_selftest_open_checkpoint || {",
269 'source_path="/proc/self/fd/8"',
270 'source "$source_path" || source_status=$?',
271 "exec 8<&- || return 1",
272 '[[ "$source_status" == "0" ]] || return "$source_status"',
273 "declare -F release_tmp_contract_selftest release_tmp_signal_child >/dev/null",
274 'source_release_selftest_helper_from "$main" "$helper" '
275 '"$expected_dir" "$expected_digest" || return 1',
277 if any(source.count(token) != 1
for token
in required):
278 findings.append(
"dev-box release selftest loader authority drifted")
279 if source.count(
"load_release_selftest_helper || exit 1") != EXPECTED_SELFTEST_DISPATCH_CALLS:
280 findings.append(
"dev-box release selftest dispatcher is not load-bearing")
282 '[[ "${BASH_SOURCE[0]}" != "$0" ]]',
284 '"${BASH_SOURCE[1]##*/}" == "provision_dev_box_toolchain.sh"',
286 if any(selftest_source.count(token) != 1
for token
in helper_required):
287 findings.append(
"dev-box release selftest source boundary drifted")
291def provisioner_findings(source: str, selftest_source: str) -> list[str]:
292 """Bind read-only check and mutating apply to disjoint shell helpers."""
293 findings: list[str] = []
294 for name, expected
in provisioner_expected_bodies().items():
295 body = _provisioner_body(source, selftest_source, name)
296 if body != _expected_shell_body(expected, name):
297 findings.append(f
"dev-box provisioner {name} semantic contract drifted")
298 findings.extend(_provisioner_release_tmp_findings(source, selftest_source))
299 findings.extend(_provisioner_install_findings(source))
300 findings.extend(_provisioner_dispatch_findings(source))
301 findings.extend(_provisioner_selftest_findings(selftest_source))
302 findings.extend(_release_selftest_loader_findings(source, selftest_source))
303 findings.extend(_release_loader_runtime_findings(selftest_source))
307def _mutate_once(source: str, old: str, new: str) -> str:
308 """Apply one exact mutation and fail if the fixture authority drifted."""
309 if source.count(old) != 1:
310 message = f
"selftest mutation anchor count changed: {old!r}"
311 raise ValueError(message)
312 return source.replace(old, new, 1)
315def _hollow_shell_function(source: str, name: str) -> str:
316 """Replace one two-space-indented shell function body with a no-op."""
317 lines = source.splitlines()
319 index
for index, line
in enumerate(lines)
if line
in (f
" {name}() {{", f
"{name}() {{")
322 message = f
"selftest shell function is missing: {name}"
323 raise ValueError(message)
324 indent =
" " if lines[starts[0]].startswith(
" ")
else ""
325 end = next(index
for index
in range(starts[0] + 1, len(lines))
if lines[index] == f
"{indent}}}")
326 replacement = [lines[starts[0]],
" :", lines[end]]
327 return "\n".join([*lines[: starts[0]], *replacement, *lines[end + 1 :]]) +
"\n"
330def _mutate_provisioner_pair(
331 provisioner: str, selftest_source: str, old: str, new: str
333 """Mutate the unique owner of one provisioner contract token."""
334 helper_old =
"\n".join(line.removeprefix(
" ")
for line
in old.split(
"\n"))
335 helper_new =
"\n".join(line.removeprefix(
" ")
for line
in new.split(
"\n"))
336 hits = provisioner.count(old) + selftest_source.count(helper_old)
338 message = f
"selftest mutation anchor count changed across provisioner inputs: {old!r}"
339 raise ValueError(message)
340 if old
in provisioner:
341 return _mutate_once(provisioner, old, new), selftest_source
342 return provisioner, _mutate_once(selftest_source, helper_old, helper_new)
345def _release_loader_path_mutations() -> tuple[tuple[str, str, list[str]], ...]:
346 """Return loader path, metadata, and wrapper-call mutations."""
347 loader_diagnostic = [
"dev-box release selftest loader authority drifted"]
350 "local identity digest source_path source_status=0",
351 "local identity digest source_path source_status",
355 'local helper="$ROOT/scripts/dev/provision_dev_box_toolchain_selftest.bash"',
356 'local helper="$ROOT/scripts/dev/provision_dev_box_toolchain.sh"',
360 'local main="$ROOT/scripts/dev/provision_dev_box_toolchain.sh"',
361 'local main="$ROOT/scripts/dev/provision_dev_box_toolchain_selftest.bash"',
365 'local expected_dir="$ROOT/scripts/dev" expected_digest="$RELEASE_SELFTEST_RAW_SHA256"',
366 'local expected_dir="$(pwd)" expected_digest="$RELEASE_SELFTEST_RAW_SHA256"',
370 'local expected_dir="$ROOT/scripts/dev" expected_digest="$RELEASE_SELFTEST_RAW_SHA256"',
371 'local expected_dir="$ROOT/scripts/dev" expected_digest="$(sha256sum "$helper")"',
375 'source_release_selftest_helper_from "$main" "$helper" '
376 '"$expected_dir" "$expected_digest" || return 1',
377 'source_release_selftest_helper_from "$helper" "$main" '
378 '"$expected_dir" "$expected_digest" || return 1',
382 '[[ "$resolved" == "$expected_dir" && -f "$main" && ! -L "$main" &&',
386 (
'"$(stat -c \'%h\' "$main")" == "1"',
'"1" == "1"', loader_diagnostic),
387 (
'"$(stat -c \'%a\' "$main")" == "755"',
'"755" == "755"', loader_diagnostic),
388 (
'("$main_owner" == "0" || "$main_owner" == "$caller_uid")',
"true", loader_diagnostic),
390 '("$caller_uid" != "0" || ("$main_owner" == "0" && "$main_group" == "0"))',
394 (
'-f "$helper" && ! -L "$helper"',
'-e "$helper"', loader_diagnostic),
395 (
'"$(stat -c \'%h\' "$helper")" == "1"',
'"1" == "1"', loader_diagnostic),
396 (
'"$(stat -c \'%a\' "$helper")" == "644"',
'"644" == "644"', loader_diagnostic),
397 (
'"$(stat -c \'%u\' "$helper")" == "$main_owner"',
"true", loader_diagnostic),
398 (
'"$(stat -c \'%g\' "$helper")" == "$main_group"',
"true", loader_diagnostic),
402def _release_loader_fd_mutations() -> tuple[tuple[str, str, list[str]], ...]:
403 """Return loader descriptor, digest, source, and dispatch mutations."""
404 loader_diagnostic = [
"dev-box release selftest loader authority drifted"]
406 (
'exec 7<"$helper"',
'exec 7<"$main"', loader_diagnostic),
407 (
'exec 8<"$helper"',
'exec 8<"$main"', loader_diagnostic),
408 (
'"$(stat -Lc \'%d:%i\' /proc/self/fd/7)" == "$identity"',
"true", loader_diagnostic),
409 (
'"$(stat -Lc \'%d:%i\' /proc/self/fd/8)" == "$identity"',
"true", loader_diagnostic),
410 (
'digest="$(sha256sum <&7)"',
'digest="$expected_digest"', loader_diagnostic),
411 (
'[[ "$digest" == "$expected_digest" ]]',
'[[ -n "$digest" ]]', loader_diagnostic),
412 (
"release_selftest_open_checkpoint || {",
"true || {", loader_diagnostic),
413 (
'source_path="/proc/self/fd/8"',
'source_path="$helper"', loader_diagnostic),
414 (
'source "$source_path" || source_status=$?',
":", loader_diagnostic),
415 (
'[[ "$source_status" == "0" ]] || return "$source_status"',
":", loader_diagnostic),
417 ' elif [ "${1:-}" = "--selftest-uv-cache-contract" ]; then\n'
418 " load_release_selftest_helper || exit 1",
419 ' elif [ "${1:-}" = "--selftest-uv-cache-contract" ]; then\n true',
421 "dev-box provisioner contract selftest is not the production dispatch",
422 "dev-box release selftest dispatcher is not load-bearing",
428def _rebind_release_helper(provisioner: str, helper_source: str) -> str:
429 """Rebind the exact helper raw digest after a semantic helper mutation."""
430 helper_digest = hashlib.sha256(helper_source.encode(
"utf-8")).hexdigest()
432 r'(?m)^( RELEASE_SELFTEST_RAW_SHA256=")[0-9a-f]{64}("$)',
433 rf
"\g<1>{helper_digest}\g<2>",
439def _release_loader_helper_failures(provisioner: str, selftest_source: str) -> list[str]:
440 """Prove source-parent and hostile runtime directions after digest rebinding."""
442 parent_mutation = _mutate_once(
444 '"${BASH_SOURCE[1]##*/}" == "provision_dev_box_toolchain.sh"',
447 rebound = _rebind_release_helper(provisioner, parent_mutation)
448 if provisioner_findings(rebound, parent_mutation) != [
449 "dev-box release selftest source boundary drifted"
451 failures.append(
"uv release selftest parent mutation passed")
454 "release_selftest_loader_refusals || return 1",
455 ": # loader refusal matrix removed",
456 "dev-box provisioner contract selftest call chain drifted",
459 "safe parent-symlink main-symlink main-hardlink main-mode",
460 "safe main-symlink main-hardlink main-mode",
461 "dev-box release selftest hostile runtime matrix drifted",
464 "helper-symlink helper-hardlink helper-mode digest inplace path-replace return-42",
465 "helper-symlink helper-hardlink helper-mode digest inplace path-replace",
466 "dev-box release selftest hostile runtime matrix drifted",
469 '[[ "$status" == "42" && -z "${RA8_RELEASE_LOADER_MARKER:-}" ]]',
470 '[[ "$status" != "0" ]]',
471 "dev-box release selftest hostile runtime matrix drifted",
474 'source_release_selftest_helper_from "$main" "$helper" "$directory" "$digest"',
475 'source_release_selftest_helper_from "$helper" "$main" "$directory" "$digest"',
476 "dev-box release selftest hostile runtime matrix drifted",
479 for old, new, diagnostic
in helper_mutations:
480 changed = _mutate_once(selftest_source, old, new)
481 rebound = _rebind_release_helper(provisioner, changed)
482 if provisioner_findings(rebound, changed) != [diagnostic]:
483 failures.append(f
"uv release selftest runtime mutation passed: {old}")
487def _release_loader_mutation_failures(provisioner: str, selftest_source: str) -> list[str]:
488 """Prove every split-helper loader and call-site safeguard must fire."""
490 mutations = (*_release_loader_path_mutations(), *_release_loader_fd_mutations())
491 for old, new, expected
in mutations:
492 changed = _mutate_once(provisioner, old, new)
493 if provisioner_findings(changed, selftest_source) != expected:
494 failures.append(f
"uv release selftest loader mutation passed: {old}")
495 failures.extend(_release_loader_helper_failures(provisioner, selftest_source))
499def provisioner_mutation_failures(provisioner: str, selftest_source: str) -> list[str]:
500 """Prove check/apply shell commands and both marker directions are bound."""
502 if provisioner_findings(provisioner, selftest_source):
503 failures.append(
"live uv provisioner semantic contract failed")
505 f
"uv provisioner mutation passed: {old}"
506 for old, new
in provisioner_mutations()
507 if not provisioner_findings(
508 *_mutate_provisioner_pair(provisioner, selftest_source, old, new)
512 f
"hollow uv provisioner selftest passed policy: {name}"
514 "uv_bootstrap_apply_run",
516 "release_tmp_identity",
517 "release_tmp_root_is_safe",
518 "release_tmp_is_safe",
519 "release_tmp_pending_cleanup",
520 "release_tmp_cleanup_owned",
522 "release_tmp_signal",
523 "install_release_tmp_traps",
524 "release_tmp_allocation_checkpoint",
526 "release_tmp_path_is_absent",
527 "release_tmp_signal_case",
528 "release_tmp_signal_child",
529 "release_tmp_replacement_refusal",
530 "release_tmp_wrong_owner_refusal",
531 "release_tmp_contract_selftest",
532 "uv_cache_check_scenario_selftest",
533 "python_selftest_tmp_identity",
534 "python_selftest_suite_is_safe",
535 "python_selftest_tmp_is_safe",
536 "python_selftest_tmp_cleanup",
537 "python_selftest_suite_cleanup",
538 "python_selftest_pending_cleanup",
539 "python_selftest_suite_candidate",
540 "python_selftest_allocation_signal",
541 "python_selftest_allocation_signal_child",
542 "python_selftest_allocation_signal_case",
543 "python_selftest_replacement_refusal",
544 "python_bytecode_invocation_selftest",
545 "python_no_bytecode_residue_selftest",
546 "uv_cache_contract_selftest",
548 if not provisioner_findings(
550 (_hollow_shell_function(provisioner, name), selftest_source)
551 if f
" {name}() {{" in provisioner
552 else (provisioner, _hollow_shell_function(selftest_source, name))
556 failures.extend(_release_loader_mutation_failures(provisioner, selftest_source))