workflow-coordinator 0.1.0b1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- workflow_coordinator/__init__.py +1 -0
- workflow_coordinator/adapter.py +150 -0
- workflow_coordinator/claude_adapter.py +289 -0
- workflow_coordinator/codex_adapter.py +395 -0
- workflow_coordinator/codex_adapter_smoke.py +231 -0
- workflow_coordinator/commissioning.py +432 -0
- workflow_coordinator/evidence.py +481 -0
- workflow_coordinator/execution_boundary.py +187 -0
- workflow_coordinator/frontdoor/__init__.py +1 -0
- workflow_coordinator/frontdoor/archive.py +1496 -0
- workflow_coordinator/frontdoor/audit.py +589 -0
- workflow_coordinator/frontdoor/cli.py +42 -0
- workflow_coordinator/frontdoor/config.py +287 -0
- workflow_coordinator/frontdoor/init.py +228 -0
- workflow_coordinator/frontdoor/journal.py +284 -0
- workflow_coordinator/frontdoor/lifecycle.py +1093 -0
- workflow_coordinator/frontdoor/plan.py +311 -0
- workflow_coordinator/frontdoor/postrun.py +254 -0
- workflow_coordinator/frontdoor/preservation.py +132 -0
- workflow_coordinator/frontdoor/report.py +222 -0
- workflow_coordinator/frontdoor/request.py +170 -0
- workflow_coordinator/frontdoor/verify.py +137 -0
- workflow_coordinator/git_facts.py +1258 -0
- workflow_coordinator/implementation_identity.py +68 -0
- workflow_coordinator/model.py +958 -0
- workflow_coordinator/operator.py +1915 -0
- workflow_coordinator/persistence.py +599 -0
- workflow_coordinator/prompt.py +272 -0
- workflow_coordinator/proof_harness.py +295 -0
- workflow_coordinator/reducer.py +2006 -0
- workflow_coordinator/resources/agent_operating_contract_v6.txt +97 -0
- workflow_coordinator/resources/roles/reviewer.txt +41 -0
- workflow_coordinator/resources/roles/simple-self-check.txt +6 -0
- workflow_coordinator/resources/roles/worker.txt +24 -0
- workflow_coordinator/serialization.py +2392 -0
- workflow_coordinator/slice4.py +411 -0
- workflow_coordinator/structured_result_schema.py +266 -0
- workflow_coordinator/vertical.py +597 -0
- workflow_coordinator-0.1.0b1.dist-info/METADATA +120 -0
- workflow_coordinator-0.1.0b1.dist-info/RECORD +44 -0
- workflow_coordinator-0.1.0b1.dist-info/WHEEL +5 -0
- workflow_coordinator-0.1.0b1.dist-info/entry_points.txt +2 -0
- workflow_coordinator-0.1.0b1.dist-info/licenses/LICENSE +21 -0
- workflow_coordinator-0.1.0b1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,481 @@
|
|
|
1
|
+
"""Policy-bound preparation and execution of A2 evidence commands."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import stat
|
|
10
|
+
import subprocess
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from types import MappingProxyType
|
|
14
|
+
from typing import Mapping, Protocol, Sequence
|
|
15
|
+
|
|
16
|
+
from .model import (
|
|
17
|
+
COORDINATOR_HARD_MAX_EVIDENCE_TIMEOUT_SECONDS,
|
|
18
|
+
EvidenceCommand,
|
|
19
|
+
Observation,
|
|
20
|
+
StatFingerprint,
|
|
21
|
+
UntrustedDiagnosticCapture,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
UNTRUSTED_DIAGNOSTIC_CAPTURE_LIMIT_BYTES = 16_384
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
ENVIRONMENT_POLICY = "coordinator-inherited-environment-v1"
|
|
29
|
+
CWD_POLICY = "canonical-repository-root-v1"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class EvidencePreparationError(ValueError):
|
|
33
|
+
"""A selected policy command could not be prepared during admission."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class ExecutableResolutionError(OSError):
|
|
37
|
+
"""An authored executable cannot resolve to an executable regular file."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True)
|
|
41
|
+
class EnvironmentSnapshot:
|
|
42
|
+
values: Mapping[str, str]
|
|
43
|
+
path_source: str
|
|
44
|
+
path_digest: str
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True)
|
|
48
|
+
class ExecutableResolution:
|
|
49
|
+
invocation_path: str
|
|
50
|
+
canonical_path: str
|
|
51
|
+
stat_fingerprint: StatFingerprint
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True)
|
|
55
|
+
class PreparedEvidenceCommand:
|
|
56
|
+
command_name: str
|
|
57
|
+
authored_argv: tuple[str, ...]
|
|
58
|
+
argv_digest: str
|
|
59
|
+
timeout_seconds: int
|
|
60
|
+
repository: Path
|
|
61
|
+
environment: EnvironmentSnapshot
|
|
62
|
+
admission_resolution: ExecutableResolution
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class EvidenceRunner(Protocol):
|
|
66
|
+
"""Execution-only seam; command authority was already admitted and prepared."""
|
|
67
|
+
|
|
68
|
+
def observe(self, command: PreparedEvidenceCommand) -> Observation: ...
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class FailClosedEvidenceRunner:
|
|
72
|
+
"""Default execution seam that grants no authority and executes nothing."""
|
|
73
|
+
|
|
74
|
+
def observe(self, command: PreparedEvidenceCommand) -> Observation:
|
|
75
|
+
raise RuntimeError("evidence runner was not explicitly supplied")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
FAIL_CLOSED_EVIDENCE_RUNNER = FailClosedEvidenceRunner()
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def authored_argv_digest(argv: Sequence[str]) -> str:
|
|
82
|
+
encoded = json.dumps(
|
|
83
|
+
list(argv), ensure_ascii=True, separators=(",", ":")
|
|
84
|
+
).encode("utf-8")
|
|
85
|
+
return hashlib.sha256(encoded).hexdigest()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def snapshot_environment(environ: Mapping[str, str] | None = None) -> EnvironmentSnapshot:
|
|
89
|
+
values = dict(os.environ if environ is None else environ)
|
|
90
|
+
if "PATH" in values:
|
|
91
|
+
path_source = "inherited"
|
|
92
|
+
else:
|
|
93
|
+
values["PATH"] = os.defpath
|
|
94
|
+
path_source = "os.defpath"
|
|
95
|
+
path_digest = hashlib.sha256(
|
|
96
|
+
values["PATH"].encode("utf-8", errors="surrogateescape")
|
|
97
|
+
).hexdigest()
|
|
98
|
+
return EnvironmentSnapshot(MappingProxyType(values), path_source, path_digest)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _fingerprint(path: str) -> StatFingerprint:
|
|
102
|
+
facts = os.stat(path)
|
|
103
|
+
if not stat.S_ISREG(facts.st_mode) or not os.access(path, os.X_OK):
|
|
104
|
+
raise ExecutableResolutionError("selected executable is not an executable regular file")
|
|
105
|
+
return StatFingerprint(
|
|
106
|
+
st_dev=facts.st_dev,
|
|
107
|
+
st_ino=facts.st_ino,
|
|
108
|
+
st_mode=facts.st_mode,
|
|
109
|
+
st_size=facts.st_size,
|
|
110
|
+
st_mtime_ns=facts.st_mtime_ns,
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
DISCOVERABLE_SIBLING_PROBE_LIMIT = 5
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _discoverable_path_siblings(
|
|
118
|
+
authored_argv0: str,
|
|
119
|
+
repository: Path,
|
|
120
|
+
environment: EnvironmentSnapshot,
|
|
121
|
+
*,
|
|
122
|
+
limit: int = DISCOVERABLE_SIBLING_PROBE_LIMIT,
|
|
123
|
+
) -> tuple[str, ...]:
|
|
124
|
+
"""Bounded, read-only PATH probe for executable sibling names (e.g. ``python3``
|
|
125
|
+
for ``python``). Informational only: never selects or substitutes a resolution.
|
|
126
|
+
"""
|
|
127
|
+
|
|
128
|
+
if os.path.isabs(authored_argv0) or "/" in authored_argv0:
|
|
129
|
+
return ()
|
|
130
|
+
root = repository.resolve()
|
|
131
|
+
siblings: list[str] = []
|
|
132
|
+
seen: set[str] = set()
|
|
133
|
+
for entry in environment.values["PATH"].split(os.pathsep):
|
|
134
|
+
base = entry if os.path.isabs(entry) else os.path.join(root, entry)
|
|
135
|
+
try:
|
|
136
|
+
names = sorted(os.listdir(base))
|
|
137
|
+
except OSError:
|
|
138
|
+
continue
|
|
139
|
+
for name in names:
|
|
140
|
+
if name == authored_argv0 or not name.startswith(authored_argv0) or name in seen:
|
|
141
|
+
continue
|
|
142
|
+
try:
|
|
143
|
+
_fingerprint(os.path.join(base, name))
|
|
144
|
+
except OSError:
|
|
145
|
+
continue
|
|
146
|
+
seen.add(name)
|
|
147
|
+
siblings.append(name)
|
|
148
|
+
if len(siblings) >= limit:
|
|
149
|
+
return tuple(siblings)
|
|
150
|
+
return tuple(siblings)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def resolve_executable(
|
|
154
|
+
authored_argv0: str,
|
|
155
|
+
repository: Path,
|
|
156
|
+
environment: EnvironmentSnapshot,
|
|
157
|
+
) -> ExecutableResolution:
|
|
158
|
+
"""Resolve one POSIX executable with repository-root relative PATH semantics."""
|
|
159
|
+
|
|
160
|
+
root = repository.resolve()
|
|
161
|
+
candidates: list[str]
|
|
162
|
+
if os.path.isabs(authored_argv0):
|
|
163
|
+
candidates = [os.path.abspath(authored_argv0)]
|
|
164
|
+
elif "/" in authored_argv0:
|
|
165
|
+
candidates = [os.path.abspath(os.path.join(root, authored_argv0))]
|
|
166
|
+
else:
|
|
167
|
+
candidates = []
|
|
168
|
+
# ``str.split`` deliberately maps PATH="" to one empty entry.
|
|
169
|
+
for entry in environment.values["PATH"].split(os.pathsep):
|
|
170
|
+
base = entry if os.path.isabs(entry) else os.path.join(root, entry)
|
|
171
|
+
candidates.append(os.path.abspath(os.path.join(base, authored_argv0)))
|
|
172
|
+
for candidate in candidates:
|
|
173
|
+
try:
|
|
174
|
+
fingerprint = _fingerprint(candidate)
|
|
175
|
+
except (FileNotFoundError, NotADirectoryError, PermissionError, ExecutableResolutionError):
|
|
176
|
+
continue
|
|
177
|
+
return ExecutableResolution(
|
|
178
|
+
invocation_path=candidate,
|
|
179
|
+
canonical_path=os.path.realpath(candidate),
|
|
180
|
+
stat_fingerprint=fingerprint,
|
|
181
|
+
)
|
|
182
|
+
siblings = _discoverable_path_siblings(authored_argv0, repository, environment)
|
|
183
|
+
siblings_note = (
|
|
184
|
+
f"discoverable PATH siblings (informational only, not selected): {', '.join(siblings)}"
|
|
185
|
+
if siblings
|
|
186
|
+
else "no discoverable PATH siblings"
|
|
187
|
+
)
|
|
188
|
+
raise ExecutableResolutionError(
|
|
189
|
+
f"executable does not resolve to an executable regular file: {authored_argv0}"
|
|
190
|
+
f"; {siblings_note}"
|
|
191
|
+
"; supply a conforming environment by prepending its prepared bin/ directory to PATH"
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def prepare_evidence_commands(
|
|
196
|
+
selected_names: Sequence[str],
|
|
197
|
+
definitions: Mapping[str, EvidenceCommand],
|
|
198
|
+
repository: Path,
|
|
199
|
+
*,
|
|
200
|
+
environ: Mapping[str, str] | None = None,
|
|
201
|
+
environment: EnvironmentSnapshot | None = None,
|
|
202
|
+
) -> tuple[PreparedEvidenceCommand, ...]:
|
|
203
|
+
"""Snapshot the environment once and admission-resolve selected definitions."""
|
|
204
|
+
|
|
205
|
+
if environ is not None and environment is not None:
|
|
206
|
+
raise ValueError("supply either environ or a prepared environment snapshot")
|
|
207
|
+
active_environment = environment or snapshot_environment(environ)
|
|
208
|
+
prepared: list[PreparedEvidenceCommand] = []
|
|
209
|
+
for name in selected_names:
|
|
210
|
+
definition = definitions[name]
|
|
211
|
+
if (
|
|
212
|
+
isinstance(definition.timeout_seconds, bool)
|
|
213
|
+
or not isinstance(definition.timeout_seconds, int)
|
|
214
|
+
or not 1
|
|
215
|
+
<= definition.timeout_seconds
|
|
216
|
+
<= COORDINATOR_HARD_MAX_EVIDENCE_TIMEOUT_SECONDS
|
|
217
|
+
):
|
|
218
|
+
raise EvidencePreparationError(
|
|
219
|
+
f"evidence command {name}: timeout_seconds must be a non-boolean "
|
|
220
|
+
f"integer in 1..{COORDINATOR_HARD_MAX_EVIDENCE_TIMEOUT_SECONDS}"
|
|
221
|
+
)
|
|
222
|
+
try:
|
|
223
|
+
resolution = resolve_executable(definition.argv[0], repository, active_environment)
|
|
224
|
+
except ExecutableResolutionError as error:
|
|
225
|
+
raise EvidencePreparationError(f"evidence command {name}: {error}") from error
|
|
226
|
+
prepared.append(
|
|
227
|
+
PreparedEvidenceCommand(
|
|
228
|
+
command_name=name,
|
|
229
|
+
authored_argv=definition.argv,
|
|
230
|
+
argv_digest=authored_argv_digest(definition.argv),
|
|
231
|
+
timeout_seconds=definition.timeout_seconds,
|
|
232
|
+
repository=repository.resolve(),
|
|
233
|
+
environment=active_environment,
|
|
234
|
+
admission_resolution=resolution,
|
|
235
|
+
)
|
|
236
|
+
)
|
|
237
|
+
return tuple(prepared)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _stream_facts(value: bytes) -> tuple[int, str, bool]:
|
|
241
|
+
return len(value), hashlib.sha256(value).hexdigest(), bool(value)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _diagnostic_tail(value: bytes) -> tuple[str, bool]:
|
|
245
|
+
"""Base64 the last ``UNTRUSTED_DIAGNOSTIC_CAPTURE_LIMIT_BYTES`` of ``value``."""
|
|
246
|
+
|
|
247
|
+
truncated = len(value) > UNTRUSTED_DIAGNOSTIC_CAPTURE_LIMIT_BYTES
|
|
248
|
+
tail = value[-UNTRUSTED_DIAGNOSTIC_CAPTURE_LIMIT_BYTES:]
|
|
249
|
+
return base64.b64encode(tail).decode("ascii"), truncated
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _untrusted_diagnostic_capture(stdout: bytes, stderr: bytes) -> UntrustedDiagnosticCapture:
|
|
253
|
+
stdout_tail_base64, stdout_tail_truncated = _diagnostic_tail(stdout)
|
|
254
|
+
stderr_tail_base64, stderr_tail_truncated = _diagnostic_tail(stderr)
|
|
255
|
+
return UntrustedDiagnosticCapture(
|
|
256
|
+
stdout_tail_base64=stdout_tail_base64,
|
|
257
|
+
stdout_tail_truncated=stdout_tail_truncated,
|
|
258
|
+
stderr_tail_base64=stderr_tail_base64,
|
|
259
|
+
stderr_tail_truncated=stderr_tail_truncated,
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _observation(
|
|
264
|
+
command: PreparedEvidenceCommand,
|
|
265
|
+
*,
|
|
266
|
+
status: str,
|
|
267
|
+
executed_argv: tuple[str, ...],
|
|
268
|
+
summary: str,
|
|
269
|
+
resolution: ExecutableResolution | None,
|
|
270
|
+
exit_code: int | None = None,
|
|
271
|
+
signal: int | None = None,
|
|
272
|
+
error_class: str | None = None,
|
|
273
|
+
stdout: bytes | None = None,
|
|
274
|
+
stderr: bytes | None = None,
|
|
275
|
+
untrusted_diagnostic: UntrustedDiagnosticCapture | None = None,
|
|
276
|
+
) -> Observation:
|
|
277
|
+
stdout_facts = (None, None, None) if stdout is None else _stream_facts(stdout)
|
|
278
|
+
stderr_facts = (None, None, None) if stderr is None else _stream_facts(stderr)
|
|
279
|
+
return Observation(
|
|
280
|
+
provider=command.command_name,
|
|
281
|
+
status=status,
|
|
282
|
+
command_name=command.command_name,
|
|
283
|
+
command=executed_argv,
|
|
284
|
+
summary=summary,
|
|
285
|
+
artifact_ref=None,
|
|
286
|
+
argv_digest=command.argv_digest,
|
|
287
|
+
authored_argv0=command.authored_argv[0],
|
|
288
|
+
timeout_seconds=command.timeout_seconds,
|
|
289
|
+
cwd_policy=CWD_POLICY,
|
|
290
|
+
invocation_path=None if resolution is None else resolution.invocation_path,
|
|
291
|
+
canonical_path=None if resolution is None else resolution.canonical_path,
|
|
292
|
+
stat_fingerprint=None if resolution is None else resolution.stat_fingerprint,
|
|
293
|
+
environment_policy=ENVIRONMENT_POLICY,
|
|
294
|
+
path_source=command.environment.path_source,
|
|
295
|
+
path_digest=command.environment.path_digest,
|
|
296
|
+
exit_code=exit_code,
|
|
297
|
+
signal=signal,
|
|
298
|
+
error_class=error_class,
|
|
299
|
+
stdout_byte_count=stdout_facts[0],
|
|
300
|
+
stdout_sha256=stdout_facts[1],
|
|
301
|
+
stdout_body_omitted=stdout_facts[2],
|
|
302
|
+
stderr_byte_count=stderr_facts[0],
|
|
303
|
+
stderr_sha256=stderr_facts[1],
|
|
304
|
+
stderr_body_omitted=stderr_facts[2],
|
|
305
|
+
untrusted_diagnostic=untrusted_diagnostic,
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
class ProductionEvidenceRunner:
|
|
310
|
+
"""Execute an already-authorized prepared command without name authority."""
|
|
311
|
+
|
|
312
|
+
def observe(self, command: PreparedEvidenceCommand) -> Observation:
|
|
313
|
+
try:
|
|
314
|
+
resolution = resolve_executable(
|
|
315
|
+
command.authored_argv[0], command.repository, command.environment
|
|
316
|
+
)
|
|
317
|
+
except (OSError, ValueError) as error:
|
|
318
|
+
return _observation(
|
|
319
|
+
command,
|
|
320
|
+
status="error",
|
|
321
|
+
executed_argv=(),
|
|
322
|
+
summary=f"resolution_error:{type(error).__name__}",
|
|
323
|
+
resolution=None,
|
|
324
|
+
error_class=f"resolution:{type(error).__name__}",
|
|
325
|
+
)
|
|
326
|
+
executed = (resolution.invocation_path, *command.authored_argv[1:])
|
|
327
|
+
process: subprocess.Popen[bytes] | None = None
|
|
328
|
+
try:
|
|
329
|
+
process = subprocess.Popen(
|
|
330
|
+
executed,
|
|
331
|
+
shell=False,
|
|
332
|
+
cwd=command.repository,
|
|
333
|
+
stdin=subprocess.DEVNULL,
|
|
334
|
+
env=command.environment.values,
|
|
335
|
+
stdout=subprocess.PIPE,
|
|
336
|
+
stderr=subprocess.PIPE,
|
|
337
|
+
)
|
|
338
|
+
except (OSError, ValueError) as error:
|
|
339
|
+
return _observation(
|
|
340
|
+
command,
|
|
341
|
+
status="error",
|
|
342
|
+
executed_argv=executed,
|
|
343
|
+
summary=f"spawn_error:{type(error).__name__}",
|
|
344
|
+
resolution=resolution,
|
|
345
|
+
error_class=f"spawn:{type(error).__name__}",
|
|
346
|
+
)
|
|
347
|
+
try:
|
|
348
|
+
stdout, stderr = process.communicate(timeout=command.timeout_seconds)
|
|
349
|
+
except subprocess.TimeoutExpired:
|
|
350
|
+
process.kill()
|
|
351
|
+
process.wait()
|
|
352
|
+
if process.stdout is not None:
|
|
353
|
+
process.stdout.close()
|
|
354
|
+
if process.stderr is not None:
|
|
355
|
+
process.stderr.close()
|
|
356
|
+
return _observation(
|
|
357
|
+
command,
|
|
358
|
+
status="error",
|
|
359
|
+
executed_argv=executed,
|
|
360
|
+
summary=f"timeout after {command.timeout_seconds}s",
|
|
361
|
+
resolution=resolution,
|
|
362
|
+
error_class="timeout",
|
|
363
|
+
)
|
|
364
|
+
except Exception as error:
|
|
365
|
+
if process.poll() is None:
|
|
366
|
+
process.kill()
|
|
367
|
+
process.wait()
|
|
368
|
+
return _observation(
|
|
369
|
+
command,
|
|
370
|
+
status="error",
|
|
371
|
+
executed_argv=executed,
|
|
372
|
+
summary=f"communication_error:{type(error).__name__}",
|
|
373
|
+
resolution=resolution,
|
|
374
|
+
error_class=f"communication:{type(error).__name__}",
|
|
375
|
+
)
|
|
376
|
+
returncode = process.returncode
|
|
377
|
+
if returncode < 0:
|
|
378
|
+
return _observation(
|
|
379
|
+
command,
|
|
380
|
+
status="error",
|
|
381
|
+
executed_argv=executed,
|
|
382
|
+
summary=f"terminated by signal {-returncode}",
|
|
383
|
+
resolution=resolution,
|
|
384
|
+
signal=-returncode,
|
|
385
|
+
error_class="signal",
|
|
386
|
+
stdout=stdout,
|
|
387
|
+
stderr=stderr,
|
|
388
|
+
)
|
|
389
|
+
status = "pass" if returncode == 0 else "fail"
|
|
390
|
+
return _observation(
|
|
391
|
+
command,
|
|
392
|
+
status=status,
|
|
393
|
+
executed_argv=executed,
|
|
394
|
+
summary=f"exit {returncode}",
|
|
395
|
+
resolution=resolution,
|
|
396
|
+
exit_code=returncode,
|
|
397
|
+
stdout=stdout,
|
|
398
|
+
stderr=stderr,
|
|
399
|
+
untrusted_diagnostic=(
|
|
400
|
+
_untrusted_diagnostic_capture(stdout, stderr) if status == "fail" else None
|
|
401
|
+
),
|
|
402
|
+
)
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
PRODUCTION_EVIDENCE_RUNNER = ProductionEvidenceRunner()
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def observation_error(
|
|
409
|
+
observation: Observation, *, expected: PreparedEvidenceCommand
|
|
410
|
+
) -> str | None:
|
|
411
|
+
"""Validate an execution-only runner return against its prepared authority."""
|
|
412
|
+
|
|
413
|
+
if observation.provider != expected.command_name or observation.command_name != expected.command_name:
|
|
414
|
+
return "malformed trusted evidence: provider/command_name identity mismatch"
|
|
415
|
+
if observation.provider != observation.command_name:
|
|
416
|
+
return "malformed trusted evidence: provider and command_name must be equal"
|
|
417
|
+
if observation.status not in {"pass", "fail", "error", "not_run"}:
|
|
418
|
+
return f"malformed trusted evidence status: {observation.status}"
|
|
419
|
+
if not observation.summary:
|
|
420
|
+
return "malformed trusted evidence: empty summary"
|
|
421
|
+
if observation.argv_digest != expected.argv_digest:
|
|
422
|
+
return "malformed trusted evidence: authored argv digest mismatch"
|
|
423
|
+
if observation.authored_argv0 != expected.authored_argv[0]:
|
|
424
|
+
return "malformed trusted evidence: authored argv[0] mismatch"
|
|
425
|
+
if observation.timeout_seconds != expected.timeout_seconds:
|
|
426
|
+
return "malformed trusted evidence: timeout mismatch"
|
|
427
|
+
if not isinstance(observation.command, tuple) or any(
|
|
428
|
+
not isinstance(item, str) for item in observation.command
|
|
429
|
+
):
|
|
430
|
+
return "malformed trusted evidence: invalid command"
|
|
431
|
+
if observation.command and not observation.command[0]:
|
|
432
|
+
return "malformed trusted evidence: invalid command executable"
|
|
433
|
+
if observation.command and observation.command[1:] != expected.authored_argv[1:]:
|
|
434
|
+
return "malformed trusted evidence: executed argv tail mismatch"
|
|
435
|
+
if observation.artifact_ref is not None and (
|
|
436
|
+
not isinstance(observation.artifact_ref, str) or not observation.artifact_ref
|
|
437
|
+
):
|
|
438
|
+
return "malformed trusted evidence: invalid artifact reference"
|
|
439
|
+
if observation.status == "pass" and (
|
|
440
|
+
observation.exit_code != 0 or observation.signal is not None
|
|
441
|
+
):
|
|
442
|
+
return "malformed trusted evidence: pass outcome mismatch"
|
|
443
|
+
if observation.status == "fail" and (
|
|
444
|
+
isinstance(observation.exit_code, bool)
|
|
445
|
+
or not isinstance(observation.exit_code, int)
|
|
446
|
+
or observation.exit_code <= 0
|
|
447
|
+
or observation.signal is not None
|
|
448
|
+
):
|
|
449
|
+
return "malformed trusted evidence: fail outcome mismatch"
|
|
450
|
+
if observation.status == "error" and not observation.error_class:
|
|
451
|
+
return "malformed trusted evidence: error requires error_class"
|
|
452
|
+
for stream, byte_count, sha256, body_omitted in (
|
|
453
|
+
(
|
|
454
|
+
"stdout",
|
|
455
|
+
observation.stdout_byte_count,
|
|
456
|
+
observation.stdout_sha256,
|
|
457
|
+
observation.stdout_body_omitted,
|
|
458
|
+
),
|
|
459
|
+
(
|
|
460
|
+
"stderr",
|
|
461
|
+
observation.stderr_byte_count,
|
|
462
|
+
observation.stderr_sha256,
|
|
463
|
+
observation.stderr_body_omitted,
|
|
464
|
+
),
|
|
465
|
+
):
|
|
466
|
+
if byte_count is sha256 is body_omitted is None:
|
|
467
|
+
if observation.status in {"pass", "fail"}:
|
|
468
|
+
return f"malformed trusted evidence: incomplete or invalid {stream} facts"
|
|
469
|
+
continue
|
|
470
|
+
if (
|
|
471
|
+
isinstance(byte_count, bool)
|
|
472
|
+
or not isinstance(byte_count, int)
|
|
473
|
+
or byte_count < 0
|
|
474
|
+
or not isinstance(sha256, str)
|
|
475
|
+
or len(sha256) != 64
|
|
476
|
+
or any(character not in "0123456789abcdef" for character in sha256)
|
|
477
|
+
or not isinstance(body_omitted, bool)
|
|
478
|
+
or body_omitted != (byte_count > 0)
|
|
479
|
+
):
|
|
480
|
+
return f"malformed trusted evidence: incomplete or invalid {stream} facts"
|
|
481
|
+
return None
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""Opt-in Linux filesystem boundary; callers supply already-authorized grants.
|
|
2
|
+
|
|
3
|
+
This is not an authority resolver or a replacement for post-hop scope checks.
|
|
4
|
+
Sources must remain stable between validation and execution; do not use with a
|
|
5
|
+
hostile actor concurrently changing the mount tree.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from enum import Enum
|
|
11
|
+
import os
|
|
12
|
+
from pathlib import Path, PurePosixPath
|
|
13
|
+
import shutil
|
|
14
|
+
import stat
|
|
15
|
+
import subprocess
|
|
16
|
+
from typing import Sequence
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class BoundaryConfigurationError(ValueError):
|
|
20
|
+
"""The requested boundary cannot be represented safely."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class MountMode(Enum):
|
|
24
|
+
READ_ONLY = "read-only"
|
|
25
|
+
WRITABLE = "writable"
|
|
26
|
+
SCRATCH = "scratch"
|
|
27
|
+
EXTERNAL_SCRATCH = "external-scratch"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
# Fixed, short destination for the one caller-designated external scratch
|
|
31
|
+
# bind; nested inside the private /tmp tmpfs so it never substitutes for it.
|
|
32
|
+
EXTERNAL_SCRATCH_DESTINATION = PurePosixPath('/tmp/s')
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class Mount:
|
|
37
|
+
source: Path | None
|
|
38
|
+
destination: PurePosixPath
|
|
39
|
+
mode: MountMode
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class ValidatedBoundary:
|
|
44
|
+
repository: Path
|
|
45
|
+
mounts: tuple[Mount, ...]
|
|
46
|
+
binary: str
|
|
47
|
+
external_scratch: Path | None = None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _real_path(path: Path) -> Path:
|
|
51
|
+
if not path.is_absolute() or path != path.resolve(strict=False):
|
|
52
|
+
raise BoundaryConfigurationError(f"source must be an absolute real path: {path}")
|
|
53
|
+
if not path.exists():
|
|
54
|
+
raise BoundaryConfigurationError(f"source does not exist: {path}")
|
|
55
|
+
return path
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _check_writable_aliases(source: Path) -> None:
|
|
59
|
+
"""Reject non-directory inodes reachable through another name.
|
|
60
|
+
|
|
61
|
+
Do not follow symlinks: their targets are resolved inside the sandbox.
|
|
62
|
+
As with mount validation generally, the source tree must remain stable.
|
|
63
|
+
"""
|
|
64
|
+
try:
|
|
65
|
+
pending = [source]
|
|
66
|
+
while pending:
|
|
67
|
+
path = pending.pop()
|
|
68
|
+
info = path.lstat()
|
|
69
|
+
# Directory link counts include their subdirectories. Linux does
|
|
70
|
+
# not permit ordinary users to create hardlinks to directories.
|
|
71
|
+
# Every other inode type, including symlinks and special files,
|
|
72
|
+
# can have metadata changed through a writable hardlink alias.
|
|
73
|
+
if not stat.S_ISDIR(info.st_mode) and info.st_nlink != 1:
|
|
74
|
+
raise BoundaryConfigurationError(f"writable entry has hardlink aliases: {path}")
|
|
75
|
+
if stat.S_ISDIR(info.st_mode):
|
|
76
|
+
with os.scandir(path) as entries:
|
|
77
|
+
pending.extend(Path(entry.path) for entry in entries)
|
|
78
|
+
except OSError as exc:
|
|
79
|
+
raise BoundaryConfigurationError(f"cannot inspect writable source: {source}") from exc
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _check_no_overlap(path: Path, other: Path, message: str) -> None:
|
|
83
|
+
if path == other or path in other.parents or other in path.parents:
|
|
84
|
+
raise BoundaryConfigurationError(message)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def validate(
|
|
88
|
+
repository: Path,
|
|
89
|
+
mounts: Sequence[Mount],
|
|
90
|
+
*,
|
|
91
|
+
binary: str = "bwrap",
|
|
92
|
+
external_scratch: Path | None = None,
|
|
93
|
+
) -> ValidatedBoundary:
|
|
94
|
+
executable = shutil.which(binary)
|
|
95
|
+
if not executable or not os.path.isfile(executable) or not os.access(executable, os.X_OK):
|
|
96
|
+
raise BoundaryConfigurationError(f"bwrap is missing or not executable: {binary}")
|
|
97
|
+
repository = _real_path(Path(repository))
|
|
98
|
+
system_roots = tuple(Path(p).resolve() for p in ("/usr", "/bin", "/sbin", "/lib", "/lib64") if os.path.exists(p))
|
|
99
|
+
if any(repository == root or repository in root.parents or root in repository.parents for root in system_roots):
|
|
100
|
+
raise BoundaryConfigurationError("repository overlaps a system mount")
|
|
101
|
+
if not repository.is_dir() or not (repository / ".git").is_dir() or (repository / ".git").is_symlink():
|
|
102
|
+
raise BoundaryConfigurationError("repository must contain a real .git directory")
|
|
103
|
+
checked = []
|
|
104
|
+
destinations: list[PurePosixPath] = []
|
|
105
|
+
for mount in mounts:
|
|
106
|
+
if not isinstance(mount, Mount) or not isinstance(mount.mode, MountMode) or not isinstance(mount.destination, PurePosixPath):
|
|
107
|
+
raise BoundaryConfigurationError("invalid mount specification")
|
|
108
|
+
if mount.mode is MountMode.EXTERNAL_SCRATCH:
|
|
109
|
+
raise BoundaryConfigurationError(
|
|
110
|
+
"external scratch mounts must be requested via the external_scratch parameter, not constructed directly")
|
|
111
|
+
dest = mount.destination
|
|
112
|
+
if not dest.is_absolute() or '..' in dest.parts or str(dest) == '/':
|
|
113
|
+
raise BoundaryConfigurationError(f"invalid destination: {dest}")
|
|
114
|
+
if any(dest == other or dest in other.parents or other in dest.parents for other in destinations):
|
|
115
|
+
raise BoundaryConfigurationError(f"overlapping destinations: {dest}")
|
|
116
|
+
destinations.append(dest)
|
|
117
|
+
if mount.mode is MountMode.SCRATCH:
|
|
118
|
+
if mount.source is not None or dest != PurePosixPath('/tmp'):
|
|
119
|
+
raise BoundaryConfigurationError("scratch must be private tmpfs at /tmp")
|
|
120
|
+
else:
|
|
121
|
+
if mount.source is None:
|
|
122
|
+
raise BoundaryConfigurationError("bind source required")
|
|
123
|
+
source = _real_path(Path(mount.source))
|
|
124
|
+
try:
|
|
125
|
+
relative = source.relative_to(repository)
|
|
126
|
+
except ValueError as exc:
|
|
127
|
+
raise BoundaryConfigurationError("bind sources must be inside repository") from exc
|
|
128
|
+
if not relative.parts or '.git' in relative.parts or dest != PurePosixPath('/repo').joinpath(*relative.parts):
|
|
129
|
+
raise BoundaryConfigurationError("bind must map an existing non-.git repository subpath to its matching destination")
|
|
130
|
+
if not (source.is_file() or source.is_dir()):
|
|
131
|
+
raise BoundaryConfigurationError("only regular files and directories are supported")
|
|
132
|
+
if mount.mode is MountMode.WRITABLE:
|
|
133
|
+
_check_writable_aliases(source)
|
|
134
|
+
checked.append(Mount(source, dest, mount.mode))
|
|
135
|
+
continue
|
|
136
|
+
checked.append(mount)
|
|
137
|
+
if sum(m.mode is MountMode.SCRATCH for m in checked) != 1:
|
|
138
|
+
raise BoundaryConfigurationError("exactly one private scratch mount is required")
|
|
139
|
+
resolved_external_scratch: Path | None = None
|
|
140
|
+
if external_scratch is not None:
|
|
141
|
+
resolved_external_scratch = _real_path(Path(external_scratch))
|
|
142
|
+
if not resolved_external_scratch.is_dir():
|
|
143
|
+
raise BoundaryConfigurationError("external scratch root must be a directory")
|
|
144
|
+
_check_no_overlap(resolved_external_scratch, repository, "external scratch root overlaps the repository")
|
|
145
|
+
for root in system_roots:
|
|
146
|
+
_check_no_overlap(resolved_external_scratch, root, "external scratch root overlaps a system mount")
|
|
147
|
+
for mount in checked:
|
|
148
|
+
if mount.source is not None:
|
|
149
|
+
_check_no_overlap(resolved_external_scratch, mount.source, "external scratch root overlaps another mount's source")
|
|
150
|
+
for other_dest in destinations:
|
|
151
|
+
if other_dest == PurePosixPath('/tmp'):
|
|
152
|
+
continue # the external scratch bind is deliberately nested inside the private tmpfs
|
|
153
|
+
if (EXTERNAL_SCRATCH_DESTINATION == other_dest or EXTERNAL_SCRATCH_DESTINATION in other_dest.parents
|
|
154
|
+
or other_dest in EXTERNAL_SCRATCH_DESTINATION.parents):
|
|
155
|
+
raise BoundaryConfigurationError(f"external scratch destination overlaps another mount: {other_dest}")
|
|
156
|
+
_check_writable_aliases(resolved_external_scratch)
|
|
157
|
+
return ValidatedBoundary(repository, tuple(checked), executable, resolved_external_scratch)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def build_argv(boundary: ValidatedBoundary, command: Sequence[str]) -> list[str]:
|
|
161
|
+
# Revalidate at the execution boundary; callers cannot bypass validation by
|
|
162
|
+
# directly constructing the public dataclass.
|
|
163
|
+
boundary = validate(boundary.repository, boundary.mounts, binary=boundary.binary, external_scratch=boundary.external_scratch)
|
|
164
|
+
if not command or not command[0] or any(not isinstance(arg, str) for arg in command):
|
|
165
|
+
raise BoundaryConfigurationError("command must contain a nonempty executable and string arguments")
|
|
166
|
+
args = [boundary.binary, '--die-with-parent', '--dev', '/dev', '--ro-bind', '/usr', '/usr']
|
|
167
|
+
for path in ('/bin', '/sbin', '/lib', '/lib64'):
|
|
168
|
+
if os.path.islink(path):
|
|
169
|
+
args += ['--symlink', os.readlink(path), path]
|
|
170
|
+
elif os.path.exists(path):
|
|
171
|
+
args += ['--ro-bind', path, path]
|
|
172
|
+
args += ['--ro-bind', str(boundary.repository), '/repo', '--tmpfs', '/repo/.git', '--remount-ro', '/repo/.git']
|
|
173
|
+
for mount in boundary.mounts:
|
|
174
|
+
if mount.mode is MountMode.SCRATCH:
|
|
175
|
+
args += ['--tmpfs', str(mount.destination)]
|
|
176
|
+
else:
|
|
177
|
+
args += ['--bind' if mount.mode is MountMode.WRITABLE else '--ro-bind', str(mount.source), str(mount.destination)]
|
|
178
|
+
# Appended after the mounts loop so this bind always lands strictly after
|
|
179
|
+
# the private /tmp tmpfs mount, regardless of that mount's position above.
|
|
180
|
+
if boundary.external_scratch is not None:
|
|
181
|
+
args += ['--bind', str(boundary.external_scratch), str(EXTERNAL_SCRATCH_DESTINATION)]
|
|
182
|
+
return args + ['--chdir', '/repo', '--', *command]
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def run(boundary: ValidatedBoundary, command: Sequence[str]) -> subprocess.CompletedProcess[bytes]:
|
|
186
|
+
"""Run only through bwrap, returning its status and unmodified output bytes."""
|
|
187
|
+
return subprocess.run(build_argv(boundary, command), capture_output=True, check=False)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Installed command entry point."""
|