3"""Exact load-bearing controls for the privileged raw-digest reader."""
5from __future__
import annotations
8from dataclasses
import dataclass
11@dataclass(frozen=True)
12class ImplementationControl:
13 """One exact control and its independently detectable mutation."""
22 function: str, scope: str, prefix: str, names: tuple[str, ...]
23) -> tuple[ImplementationControl, ...]:
24 """Return exact flag-use controls for one open boundary."""
26 ImplementationControl(f
"{scope} {name}", function, f
'| {prefix}["{name}"]',
"| 0")
31def _metadata_read_controls() -> tuple[ImplementationControl, ...]:
32 """Return exact identity, metadata, and bounded-read controls."""
34 ImplementationControl(
35 "ctime identity",
"_identity",
"value.st_ctime_ns,",
"value.st_mtime_ns,"
37 ImplementationControl(
38 "intermediate directory mode",
40 "mode=_DIRECTORY_MODE,",
41 "mode=stat.S_IMODE(before.st_mode),",
43 ImplementationControl(
45 "_read_exact_payload",
46 "requested = min(_READ_STEP_BYTES, before.st_size - offset)",
47 "requested = before.st_size - offset",
49 ImplementationControl(
51 "_root_metadata_error",
52 "(mode & _ROOT_MODE_REQUIRED) != _ROOT_MODE_REQUIRED",
55 ImplementationControl(
56 "root forbidden mode bits",
57 "_root_metadata_error",
58 "mode & ~_ROOT_MODE_ALLOWED",
61 ImplementationControl(
62 "single-link final file",
64 "if not kind_ok or (policy.single_link and value.st_nlink != 1):",
67 ImplementationControl(
69 "_read_exact_payload",
70 'os.pread(fd, 1, before.st_size) != b""',
76def _rewalk_dispatch_controls() -> tuple[ImplementationControl, ...]:
77 """Return exact rewalk and production-dispatch controls."""
79 ImplementationControl(
80 "component post-rewalk identity",
82 "if identity != expected_directories[index]:",
85 ImplementationControl(
86 "final post-rewalk identity",
88 "if _identity(after_path) != expected_file:",
91 ImplementationControl(
92 "root post-rewalk identity",
94 "or _identity(before) != _identity(\n after_path\n )",
97 ImplementationControl(
98 "live target audit dispatch",
100 "errors.extend(_audit_all_targets(root_fd, values, context))",
103 ImplementationControl(
104 "implementation audit dispatch",
106 "errors = implementation_errors(authority_source)",
107 "errors: list[str] = []",
109 ImplementationControl(
110 "control policy raw-pin dispatch",
112 "control_error = _raw_target_error(_control_target(values), files, values)",
113 "control_error = None",
115 ImplementationControl(
116 "control policy verification guard",
118 "if control_error is not None:\n return [control_error]",
119 "if False:\n return [control_error]",
121 ImplementationControl(
122 "control policy import",
124 "import hil_convergence_safety_raw_digest_controls as raw_digest_controls",
127 ImplementationControl(
128 "control policy error dispatch",
129 "implementation_errors",
130 "return raw_digest_controls.implementation_errors(source)",
136def _authority_condition_controls() -> tuple[ImplementationControl, ...]:
137 """Return exact owner and mode conditions with fail-open mutations."""
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:"
148 ImplementationControl(*line.split(
"|", 2),
"if False:")
for line
in specs.splitlines()
152def _authority_cleanup_controls() -> tuple[ImplementationControl, ...]:
153 """Return exact validation dispatch and descriptor controls."""
155 *_authority_condition_controls(),
156 ImplementationControl(
157 "target path validation dispatch",
159 "path_error = _target_path_error(path, pin_name, label)",
162 ImplementationControl(
163 "required capabilities dispatch",
165 "flags, error = _required_flags(hooks)",
166 "flags, error = {}, None",
168 ImplementationControl(
169 "descriptor close operation",
170 "_close_released_descriptor",
174 ImplementationControl(
175 "ledger release before close",
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))",
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")
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(),
199def _function_nodes(source: str) -> tuple[ast.Module |
None, dict[str, ast.FunctionDef]]:
200 """Parse uniquely named functions and methods without executing source."""
202 tree = ast.parse(source)
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}
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}"
221 nodes: dict[str, ast.FunctionDef],
223 """Return the exact function or module segment named by one control."""
224 if function ==
"<module>":
226 node = nodes.get(function)
227 return None if node
is None else ast.get_source_segment(source, node)
230def implementation_errors(source: str) -> list[str]:
231 """Reject removal or duplication of every load-bearing reader control."""
232 tree, nodes = _function_nodes(source)
234 return [
"raw digest implementation: source is not valid Python"]
237 for control
in controls()
238 if (segment := _segment(source, control.function, nodes))
is None
239 or segment.count(control.token) != 1
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)
247 for control
in controls():
248 segment = _segment(source, control.function, nodes)
249 if segment
is None or segment.count(control.token) != 1:
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)