ra8-firmware 0.1.0
Bare-metal firmware for the Renesas RA8 family (RA8D2 / RA8P1)
Loading...
Searching...
No Matches
hil_convergence_safety_raw_digest_controls.py
Go to the documentation of this file.
1# SPDX-License-Identifier: MIT
2# Copyright (c) 2026 Brighton Sikarskie
3"""Exact load-bearing controls for the privileged raw-digest reader."""
4
5from __future__ import annotations
6
7import ast
8from dataclasses import dataclass
9
10
11@dataclass(frozen=True)
12class ImplementationControl:
13 """One exact control and its independently detectable mutation."""
14
15 label: str
16 function: str
17 token: str
18 replacement: str
19
20
21def _flag_controls(
22 function: str, scope: str, prefix: str, names: tuple[str, ...]
23) -> tuple[ImplementationControl, ...]:
24 """Return exact flag-use controls for one open boundary."""
25 return tuple(
26 ImplementationControl(f"{scope} {name}", function, f'| {prefix}["{name}"]', "| 0")
27 for name in names
28 )
29
30
31def _metadata_read_controls() -> tuple[ImplementationControl, ...]:
32 """Return exact identity, metadata, and bounded-read controls."""
33 return (
34 ImplementationControl(
35 "ctime identity", "_identity", "value.st_ctime_ns,", "value.st_mtime_ns,"
36 ),
37 ImplementationControl(
38 "intermediate directory mode",
39 "_open_directory",
40 "mode=_DIRECTORY_MODE,",
41 "mode=stat.S_IMODE(before.st_mode),",
42 ),
43 ImplementationControl(
44 "fixed read step",
45 "_read_exact_payload",
46 "requested = min(_READ_STEP_BYTES, before.st_size - offset)",
47 "requested = before.st_size - offset",
48 ),
49 ImplementationControl(
50 "root owner access",
51 "_root_metadata_error",
52 "(mode & _ROOT_MODE_REQUIRED) != _ROOT_MODE_REQUIRED",
53 "False",
54 ),
55 ImplementationControl(
56 "root forbidden mode bits",
57 "_root_metadata_error",
58 "mode & ~_ROOT_MODE_ALLOWED",
59 "False",
60 ),
61 ImplementationControl(
62 "single-link final file",
63 "_metadata_error",
64 "if not kind_ok or (policy.single_link and value.st_nlink != 1):",
65 "if not kind_ok:",
66 ),
67 ImplementationControl(
68 "exact pre-size EOF",
69 "_read_exact_payload",
70 'os.pread(fd, 1, before.st_size) != b""',
71 "False",
72 ),
73 )
74
75
76def _rewalk_dispatch_controls() -> tuple[ImplementationControl, ...]:
77 """Return exact rewalk and production-dispatch controls."""
78 return (
79 ImplementationControl(
80 "component post-rewalk identity",
81 "_post_rewalk",
82 "if identity != expected_directories[index]:",
83 "if False:",
84 ),
85 ImplementationControl(
86 "final post-rewalk identity",
87 "_post_rewalk",
88 "if _identity(after_path) != expected_file:",
89 "if False:",
90 ),
91 ImplementationControl(
92 "root post-rewalk identity",
93 "audit_live_errors",
94 "or _identity(before) != _identity(\n after_path\n )",
95 "or False",
96 ),
97 ImplementationControl(
98 "live target audit dispatch",
99 "audit_live_errors",
100 "errors.extend(_audit_all_targets(root_fd, values, context))",
101 "errors.extend(())",
102 ),
103 ImplementationControl(
104 "implementation audit dispatch",
105 "source_errors",
106 "errors = implementation_errors(authority_source)",
107 "errors: list[str] = []",
108 ),
109 ImplementationControl(
110 "control policy raw-pin dispatch",
111 "source_errors",
112 "control_error = _raw_target_error(_control_target(values), files, values)",
113 "control_error = None",
114 ),
115 ImplementationControl(
116 "control policy verification guard",
117 "source_errors",
118 "if control_error is not None:\n return [control_error]",
119 "if False:\n return [control_error]",
120 ),
121 ImplementationControl(
122 "control policy import",
123 "<module>",
124 "import hil_convergence_safety_raw_digest_controls as raw_digest_controls",
125 "",
126 ),
127 ImplementationControl(
128 "control policy error dispatch",
129 "implementation_errors",
130 "return raw_digest_controls.implementation_errors(source)",
131 "return []",
132 ),
133 )
134
135
136def _authority_condition_controls() -> tuple[ImplementationControl, ...]:
137 """Return exact owner and mode conditions with fail-open mutations."""
138 specs = (
139 "root owner|_root_metadata_error|"
140 "if authority is not None and value.st_uid != authority.root_uid:\n"
141 "root group|_root_metadata_error|"
142 "if authority is not None and value.st_gid != authority.root_gid:\n"
143 "final owner|_metadata_error|if value.st_uid != policy.uid:\n"
144 "final group|_metadata_error|if value.st_gid != policy.gid:\n"
145 "final mode|_metadata_error|if stat.S_IMODE(value.st_mode) != policy.mode:"
146 )
147 return tuple(
148 ImplementationControl(*line.split("|", 2), "if False:") for line in specs.splitlines()
149 )
150
151
152def _authority_cleanup_controls() -> tuple[ImplementationControl, ...]:
153 """Return exact validation dispatch and descriptor controls."""
154 return (
155 *_authority_condition_controls(),
156 ImplementationControl(
157 "target path validation dispatch",
158 "_raw_target_error",
159 "path_error = _target_path_error(path, pin_name, label)",
160 "path_error = None",
161 ),
162 ImplementationControl(
163 "required capabilities dispatch",
164 "audit_live_errors",
165 "flags, error = _required_flags(hooks)",
166 "flags, error = {}, None",
167 ),
168 ImplementationControl(
169 "descriptor close operation",
170 "_close_released_descriptor",
171 "os.close(fd)",
172 "None",
173 ),
174 ImplementationControl(
175 "ledger release before close",
176 "close_all",
177 "fd = self._fds.pop()\n"
178 " errors.extend(_close_released_descriptor(fd, label, self._hooks))",
179 "fd = self._fds[-1]\n"
180 " errors.extend(_close_released_descriptor(fd, label, self._hooks))",
181 ),
182 )
183
184
185def controls() -> tuple[ImplementationControl, ...]:
186 """Return every control whose removal must fire without relying on pins."""
187 directory_flags = ("O_DIRECTORY", "O_NOFOLLOW", "O_CLOEXEC", "O_NONBLOCK")
188 file_flags = ("O_NOFOLLOW", "O_CLOEXEC", "O_NONBLOCK")
189 return (
190 *_flag_controls("audit_live_errors", "root open", "flags", directory_flags),
191 *_flag_controls("_open_directory", "component open", "context.flags", directory_flags),
192 *_flag_controls("_open_final", "final open", "context.flags", file_flags),
193 *_metadata_read_controls(),
194 *_rewalk_dispatch_controls(),
195 *_authority_cleanup_controls(),
196 )
197
198
199def _function_nodes(source: str) -> tuple[ast.Module | None, dict[str, ast.FunctionDef]]:
200 """Parse uniquely named functions and methods without executing source."""
201 try:
202 tree = ast.parse(source)
203 except SyntaxError:
204 return None, {}
205 candidates: dict[str, list[ast.FunctionDef]] = {}
206 for node in ast.walk(tree):
207 if isinstance(node, ast.FunctionDef):
208 candidates.setdefault(node.name, []).append(node)
209 unique = {name: values[0] for name, values in candidates.items() if len(values) == 1}
210 return tree, unique
211
212
213def _diagnostic(control: ImplementationControl) -> str:
214 """Return the stable exact diagnostic for one missing live control."""
215 return f"raw digest implementation: required control is not unique: {control.label}"
216
217
218def _segment(
219 source: str,
220 function: str,
221 nodes: dict[str, ast.FunctionDef],
222) -> str | None:
223 """Return the exact function or module segment named by one control."""
224 if function == "<module>":
225 return source
226 node = nodes.get(function)
227 return None if node is None else ast.get_source_segment(source, node)
228
229
230def implementation_errors(source: str) -> list[str]:
231 """Reject removal or duplication of every load-bearing reader control."""
232 tree, nodes = _function_nodes(source)
233 if tree is None:
234 return ["raw digest implementation: source is not valid Python"]
235 return [
236 _diagnostic(control)
237 for control in controls()
238 if (segment := _segment(source, control.function, nodes)) is None
239 or segment.count(control.token) != 1
240 ]
241
242
243def implementation_mutations(source: str) -> tuple[tuple[str, str, str], ...]:
244 """Return exact one-control mutants and their required diagnostics."""
245 _tree, nodes = _function_nodes(source)
246 mutations = []
247 for control in controls():
248 segment = _segment(source, control.function, nodes)
249 if segment is None or segment.count(control.token) != 1:
250 continue
251 changed = source.replace(segment, segment.replace(control.token, control.replacement, 1), 1)
252 mutations.append((control.label, changed, _diagnostic(control)))
253 return tuple(mutations)