ra8-firmware 0.1.0
Bare-metal firmware for the Renesas RA8 family (RA8D2 / RA8P1)
Loading...
Searching...
No Matches
hil_convergence_safety_python_authority.py
Go to the documentation of this file.
1# SPDX-License-Identifier: MIT
2# Copyright (c) 2026 Brighton Sikarskie
3"""Validate locked Python deployment across HIL and CI execution boundaries."""
4
5from __future__ import annotations
6
7from typing import cast
8
9import yaml
10
11
12class FixtureError(ValueError):
13 """A structural policy lookup no longer has one exact task target."""
14
15
16def _tasks(source: str, label: str) -> tuple[list[dict[str, object]], list[str]]:
17 """Parse one role task list with attribution."""
18 try:
19 value = yaml.safe_load(source)
20 except yaml.YAMLError:
21 return [], [f"{label}: malformed YAML"]
22 if not isinstance(value, list) or any(not isinstance(item, dict) for item in value):
23 return [], [f"{label}: expected a task list"]
24 return cast(list[dict[str, object]], value), []
25
26
27def _named(tasks: list[dict[str, object]], name: str) -> tuple[int, dict[str, object]]:
28 """Return one uniquely named top-level task."""
29 matches = [(index, task) for index, task in enumerate(tasks) if task.get("name") == name]
30 if len(matches) != 1:
31 message = f"task {name!r} is missing or duplicated"
32 raise FixtureError(message)
33 return matches[0]
34
35
36def _named_loop(source: str, name: str, label: str) -> tuple[list[object], list[str]]:
37 """Return one exact Ansible task loop for deployment-policy checks."""
38 tasks, errors = _tasks(source, label)
39 if errors:
40 return [], errors
41 try:
42 _, task = _named(tasks, name)
43 except FixtureError as exc:
44 return [], [f"{label}: {exc}"]
45 loop = task.get("loop")
46 if not isinstance(loop, list):
47 return [], [f"{label}: task {name!r} has no literal loop"]
48 return loop, []
49
50
51def _authority(source: str, destination: str, mode: str) -> dict[str, str]:
52 """Build one exact source-to-destination authority manifest row."""
53 return {"src": source, "dest": destination, "mode": mode}
54
55
56def _expected_hil_manifest() -> list[dict[str, str]]:
57 """Return the canonical HIL Python execution-authority manifest."""
58 root = "{{ role_path }}/../../../../"
59 return [
60 _authority(f"{root}pyproject.toml", "pyproject.toml", "0644"),
61 _authority(f"{root}uv.lock", "uv.lock", "0644"),
62 _authority(f"{root}scripts/dev/bootstrap_uv.py", "bootstrap_uv.py", "0755"),
63 _authority(f"{root}scripts/dev/bootstrap_uv_exec.py", "bootstrap_uv_exec.py", "0644"),
64 _authority(f"{root}scripts/dev/uv_release.json", "uv_release.json", "0644"),
65 _authority(
66 f"{root}scripts/dev/verify_locked_environment.py",
67 "verify_locked_environment.py",
68 "0755",
69 ),
70 _authority("{{ role_path }}/files/requirements.lock", "requirements.lock", "0644"),
71 ]
72
73
74def _context_deployment_errors(inputs: dict[str, str], helper: str) -> list[str]:
75 """Require the helper in the devcontainer context and image policy."""
76 errors: list[str] = []
77 if inputs["dockerignore"].splitlines().count(f"!{helper}") != 1:
78 errors.append("devcontainer context: bootstrap execution helper is not allowlisted")
79 docker_copy = "COPY scripts/dev/bootstrap_uv.py \\\n scripts/dev/bootstrap_uv_exec.py \\"
80 if inputs["dockerfile"].count(docker_copy) != 1:
81 errors.append("devcontainer Dockerfile: bootstrap execution helper is not copied")
82 image = inputs["devcontainer_image"]
83 if (
84 image.splitlines().count(f"!{helper}") != 1
85 or image.splitlines().count(f"644 {helper}") != 1
86 ):
87 errors.append("devcontainer image policy: bootstrap execution helper is not canonical")
88 return errors
89
90
91def _hil_manifest_errors(source: str) -> list[str]:
92 """Require the one exact HIL Python execution-authority manifest."""
93 tasks, errors = _tasks(source, "HIL")
94 if errors:
95 return errors
96 try:
97 _, manifest_task = _named(tasks, "Define the one HIL Python execution-authority manifest")
98 except FixtureError as exc:
99 return [f"HIL: {exc}"]
100 facts = manifest_task.get("ansible.builtin.set_fact")
101 actual = facts.get("hil_bench_python_authorities") if isinstance(facts, dict) else None
102 if actual != _expected_hil_manifest():
103 return ["HIL: shared Python execution-authority manifest is not exact"]
104 return []
105
106
107def _ci_stage_spec(helper: str) -> list[dict[str, str]]:
108 """Return the exact CI root-context staging manifest."""
109 return [
110 _authority(".dockerignore", ".dockerignore", "0644"),
111 _authority("pyproject.toml", "pyproject.toml", "0644"),
112 _authority("uv.lock", "uv.lock", "0644"),
113 _authority("scripts/dev/bootstrap_uv.py", "scripts/dev/bootstrap_uv.py", "0755"),
114 _authority(helper, helper, "0644"),
115 _authority(
116 "scripts/dev/managed_python_env.py", "scripts/dev/managed_python_env.py", "0755"
117 ),
118 _authority(
119 "scripts/dev/managed_python_env_checks.py",
120 "scripts/dev/managed_python_env_checks.py",
121 "0755",
122 ),
123 _authority("scripts/dev/uv_release.json", "scripts/dev/uv_release.json", "0644"),
124 ]
125
126
127def _ci_readback_spec(helper: str) -> list[str]:
128 """Return the exact CI root-context readback manifest."""
129 return [
130 ".dockerignore",
131 "pyproject.toml",
132 "scripts/dev/bootstrap_uv.py",
133 helper,
134 "scripts/dev/managed_python_env.py",
135 "scripts/dev/managed_python_env_checks.py",
136 "scripts/dev/uv_release.json",
137 "uv.lock",
138 ]
139
140
141def _ci_presence_spec(helper: str) -> list[str]:
142 """Return every CI root-context input that must be present."""
143 return [
144 ".dockerignore",
145 ".devcontainer/Dockerfile",
146 "pyproject.toml",
147 "runner/Dockerfile",
148 "scripts/dev/bootstrap_uv.py",
149 helper,
150 "scripts/dev/managed_python_env.py",
151 "scripts/dev/managed_python_env_checks.py",
152 "scripts/dev/uv_release.json",
153 "uv.lock",
154 ]
155
156
157def _ci_deployment_errors(source: str, helper: str) -> list[str]:
158 """Require all CI root-context authority loops to remain exact."""
159 specs = (
160 ("Stage the root-context Python lock and bootstrap inputs", _ci_stage_spec(helper)),
161 ("Read back every staged root-context authority byte-for-byte", _ci_readback_spec(helper)),
162 (
163 "Assert both Dockerfiles and every locked Python input arrived",
164 _ci_presence_spec(helper),
165 ),
166 )
167 errors: list[str] = []
168 for task_name, wanted in specs:
169 loop, loop_errors = _named_loop(source, task_name, "CI runner")
170 errors.extend(loop_errors)
171 if loop != wanted:
172 errors.append(f"CI runner: {task_name} authority list is not exact")
173 return errors
174
175
176def _wsl_deployment_errors(stage: str, wsl: str, helper: str) -> list[str]:
177 """Require WSL staging and path proof to cover the execution helper."""
178 errors: list[str] = []
179 if stage.count(f' "{helper}",') != 1:
180 errors.append("fleet WSL stage: bootstrap execution helper is not archived")
181 proof = ' f"{stage}/scripts/dev/bootstrap_uv_exec.py",'
182 if wsl.count(proof) != 1:
183 errors.append("fleet WSL: bootstrap execution helper is not path-proven")
184 return errors
185
186
187def uv_helper_deployment_errors(inputs: dict[str, str]) -> list[str]:
188 """Require every deployed bootstrap to carry its adjacent execution helper."""
189 helper = "scripts/dev/bootstrap_uv_exec.py"
190 errors = _context_deployment_errors(inputs, helper)
191 errors.extend(_hil_manifest_errors(inputs["bench_role"]))
192 errors.extend(_ci_deployment_errors(inputs["ci_runner"], helper))
193 errors.extend(_wsl_deployment_errors(inputs["fleet_wsl_stage"], inputs["fleet_wsl"], helper))
194 return errors
195
196
197def _selected_hil_proof_tasks(
198 tasks: list[dict[str, object]],
199) -> tuple[list[tuple[int, dict[str, object]]], list[str]]:
200 """Select all uniquely named HIL Python authority proof tasks."""
201 names = (
202 "Stage the exact HIL Python project and bootstrap inputs",
203 "Inspect every deployed HIL Python execution authority without following links",
204 "Refuse check mode when any HIL Python authority needs apply",
205 "Prove every deployed HIL Python authority is regular and mode-exact",
206 "Read back every deployed HIL Python execution authority",
207 "Prove every deployed HIL Python authority is byte-exact",
208 )
209 selected: list[tuple[int, dict[str, object]]] = []
210 errors: list[str] = []
211 for name in names:
212 try:
213 selected.append(_named(tasks, name))
214 except FixtureError as exc:
215 errors.append(f"HIL: {exc}")
216 return selected, errors
217
218
219def _hil_stage_proof_is_exact(
220 stage: dict[str, object],
221 stat: dict[str, object],
222 refusal: dict[str, object],
223 identity: dict[str, object],
224) -> bool:
225 """Return whether HIL staging, no-follow stat, and mode proof are exact."""
226 return (
227 stage.get("loop") == "{{ hil_bench_python_authorities }}"
228 and stage.get("register") == "hil_bench_python_stage"
229 and stage.get("ansible.builtin.copy")
230 == {
231 "src": "{{ item.src }}",
232 "dest": "{{ hil_bench_python_context }}/{{ item.dest }}",
233 "owner": "root",
234 "group": "root",
235 "mode": "{{ item.mode }}",
236 }
237 and stat.get("loop") == "{{ hil_bench_python_authorities }}"
238 and stat.get("register") == "hil_bench_python_authority_stats"
239 and stat.get("ansible.builtin.stat")
240 == {"path": "{{ hil_bench_python_context }}/{{ item.dest }}", "follow": False}
241 and stat.get("changed_when") is False
242 and stat.get("check_mode") is False
243 and refusal.get("ansible.builtin.assert", {}).get("that")
244 == [
245 "not ansible_check_mode or (hil_bench_python_stage.results | "
246 "selectattr('changed') | list | length == 0)"
247 ]
248 and identity.get("ansible.builtin.assert", {}).get("that")
249 == [
250 "item.stat.exists",
251 "item.stat.isreg",
252 "not item.stat.islnk",
253 "item.stat.mode == item.item.mode",
254 ]
255 and identity.get("loop") == "{{ hil_bench_python_authority_stats.results }}"
256 )
257
258
259def _hil_readback_proof_is_exact(
260 readback: dict[str, object], byte_proof: dict[str, object]
261) -> bool:
262 """Return whether HIL authority readback and byte proof are exact."""
263 return (
264 readback.get("loop") == "{{ hil_bench_python_authorities }}"
265 and readback.get("register") == "hil_bench_python_authority_bytes"
266 and readback.get("ansible.builtin.slurp")
267 == {"src": "{{ hil_bench_python_context }}/{{ item.dest }}"}
268 and readback.get("changed_when") is False
269 and readback.get("check_mode") is False
270 and byte_proof.get("loop") == "{{ hil_bench_python_authority_bytes.results }}"
271 and byte_proof.get("ansible.builtin.assert", {}).get("that")
272 == [
273 "(item.content | b64decode | hash('sha256')) == "
274 "(lookup('file', item.item.src, rstrip=false) | hash('sha256'))"
275 ]
276 )
277
278
279def _hil_proof_order_errors(
280 tasks: list[dict[str, object]], selected: list[tuple[int, dict[str, object]]]
281) -> list[str]:
282 """Require every exact authority proof before Python execution."""
283 proof_indices = [index for index, _ in selected]
284 execution_indices = [
285 index
286 for index, task in enumerate(tasks)
287 if "hil_bench_python_context" in str(task.get("ansible.builtin.command", {}))
288 ]
289 if proof_indices != sorted(proof_indices) or (
290 execution_indices and proof_indices[-1] >= min(execution_indices)
291 ):
292 return ["HIL: Python execution can precede exact deployed-authority proof"]
293 return []
294
295
296def hil_python_authority_errors(source: str) -> list[str]:
297 """Require one fail-closed HIL authority proof before Python execution."""
298 tasks, errors = _tasks(source, "HIL")
299 if errors:
300 return errors
301 selected, errors = _selected_hil_proof_tasks(tasks)
302 if errors:
303 return errors
304 stage, stat, refusal, identity, readback, byte_proof = [task for _, task in selected]
305 exact = _hil_stage_proof_is_exact(stage, stat, refusal, identity)
306 exact = exact and _hil_readback_proof_is_exact(readback, byte_proof)
307 if not exact:
308 errors.append("HIL: Python authority copy/readback/mode proof is not exact")
309 errors.extend(_hil_proof_order_errors(tasks, selected))
310 return errors
#define min(x, y)
Untyped minimum shim used by the SOUP's buffer clamping.
Definition xz_config.h:157