aien-receipts
Append-only AIEN verification receipts, indexed by repository and exact source commit. Read verdicts, signatures and retained logs before making a claim.
Brought by drakestapleton
aien-receipts / tools / replay_receipt.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Admit and replay receipts listed in index/receipt_index.json (DRA-167). |
| 3 | |
| 4 | `admit` computes one index entry live from pinned commits. `replay` fetches an |
| 5 | indexed entry again by its pinned commits, checks the shelf bytes against the |
| 6 | recorded SHA-256, recomputes every other field (correction precedence, bundle |
| 7 | signature and trust anchor, source provenance, issue_or_gate) and compares it |
| 8 | with the index. Both also read the current HEAD of the shelf repository and |
| 9 | refuse an entry when the correction file there differs from the one at the |
| 10 | pinned commit, and replay refuses any entry or index field it does not know. |
| 11 | The last line printed is the verdict. Rules: docs/receipt-index.md. |
| 12 | |
| 13 | Exit codes for one entry: 0 PASS, 1 FAIL (an authenticated FAIL verdict), |
| 14 | 2 NOT_RUN (an input could not be reached, or a usage error), 3 REJECTED (bytes, |
| 15 | signature, binding, correction binding, a newer correction at the shelf HEAD, |
| 16 | an unknown field or index drift), 4 REFUSED (admission refused by a shelf |
| 17 | correction or by the source-provenance check). |
| 18 | `replay --all` exits 0 only when every entry reproduces exactly as indexed. |
| 19 | |
| 20 | Needs Python 3, Git and OpenSSL 3 (Ed25519). Repository convention: the only |
| 21 | other tooling in this repository (audit/tools) is Python with unittest. |
| 22 | """ |
| 23 | import argparse |
| 24 | import hashlib |
| 25 | import json |
| 26 | import os |
| 27 | import subprocess |
| 28 | import sys |
| 29 | import tempfile |
| 30 | |
| 31 | INDEX_SCHEMA = "aien.receipt-index.v2" |
| 32 | BUNDLE_SCHEMA = "aien-verification-bundle/1" |
| 33 | CORRECTION_SCHEMA = "aien.omega-evidence.receipt-correction.v1" |
| 34 | SHELF_OWNER = "aien-dev" |
| 35 | # Each kind lives on exactly one shelf; the index cannot point a kind elsewhere. |
| 36 | SHELF_REPOS = {"signed-bundle": "aien-dev/aien-receipts", "omega-qualification-receipt": "aien-dev/omega-evidence"} |
| 37 | KINDS = tuple(SHELF_REPOS) |
| 38 | # Every field an index may carry. Replay rejects anything else (UNKNOWN_FIELD / SCHEMA). |
| 39 | INDEX_FIELDS = {"schema", "index_version", "issue", "generated_by", "independence", "admission_check", |
| 40 | "precedence", "exit_codes", "scope", "excluded", "generated_utc", "entries"} |
| 41 | _ENTRY_COMMON = {"id", "kind", "issue_or_gate", "shelf", "source", "correction", "historical_verdict", |
| 42 | "effective_verdict", "effective_basis", "replay"} |
| 43 | ENTRY_FIELDS = {"signed-bundle": _ENTRY_COMMON | {"trust_anchor", "signature", "gates"}, |
| 44 | "omega-qualification-receipt": _ENTRY_COMMON} |
| 45 | # Effective basis of a signed bundle. Taken on trust: see docs/receipt-index.md, "Values taken on trust". |
| 46 | BUNDLE_BASIS = "authenticated bundle verdict (this shelf has no correction records)" |
| 47 | UNVERIFIED_ISSUE_BASIS = "UNVERIFIED: not derivable from the receipt; text supplied at admission" |
| 48 | EXIT = {"PASS": 0, "FAIL": 1, "NOT_RUN": 2, "REJECTED": 3, "REFUSED": 4} |
| 49 | # DER SubjectPublicKeyInfo prefix for a raw 32-byte Ed25519 public key. |
| 50 | SPKI_ED25519 = bytes.fromhex("302a300506032b6570032100") |
| 51 | # Bundle vocabulary of aien-sovereign-core@c26f4d7a tools/aien-test/src/bundle.rs. |
| 52 | STATUSES = ("run", "cached", "not_run", "blocked") |
| 53 | VERDICTS = ("PASS", "FAIL", "NOT_RUN", "BLOCKED_HARDWARE", "BLOCKED_OPERATOR", "MISSING_IMPLEMENTATION") |
| 54 | EXACTNESS = ("EXACT", "BOUNDED", "APPROXIMATE", "ADVISORY") |
| 55 | RECEIPT_ID_SCHEMES = ("sha256-canonical-json", "aien-proof-blake3") |
| 56 | # Omega receipts name their implementation commit in one of these fields, first match wins. |
| 57 | SOURCE_COMMIT_FIELDS = ("qualified_implementation_commit", "git_commit") |
| 58 | ADMITTED_HISTORICAL_STATUS = "QUALIFIED / PASS" |
| 59 | DEFAULT_INDEX = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "index", "receipt_index.json") |
| 60 | |
| 61 | |
| 62 | class Rejected(Exception): |
| 63 | def __init__(self, code, detail): |
| 64 | super().__init__(f"{code}: {detail}") |
| 65 | self.code = code |
| 66 | |
| 67 | |
| 68 | class NotRun(Exception): |
| 69 | pass |
| 70 | |
| 71 | |
| 72 | def sha256(data): |
| 73 | return hashlib.sha256(data).hexdigest() |
| 74 | |
| 75 | |
| 76 | def is_hex(s, n): |
| 77 | return isinstance(s, str) and len(s) == n and all(c in "0123456789abcdef" for c in s) |
| 78 | |
| 79 | |
| 80 | # ------------------------------------------------------------- canonical JSON |
| 81 | # Port of evidence::canonical (aien-sovereign-core@c26f4d7a): sorted keys by |
| 82 | # UTF-8 bytes, compact, integers only, minimal escapes. |
| 83 | |
| 84 | def _canon_str(s, out): |
| 85 | out.append('"') |
| 86 | for ch in s: |
| 87 | if ch == '"': |
| 88 | out.append('\\"') |
| 89 | elif ch == "\\": |
| 90 | out.append("\\\\") |
| 91 | elif ch == "\n": |
| 92 | out.append("\\n") |
| 93 | elif ch == "\r": |
| 94 | out.append("\\r") |
| 95 | elif ch == "\t": |
| 96 | out.append("\\t") |
| 97 | elif ord(ch) < 0x20: |
| 98 | out.append("\\u%04x" % ord(ch)) |
| 99 | else: |
| 100 | out.append(ch) |
| 101 | out.append('"') |
| 102 | |
| 103 | |
| 104 | def _canon_val(v, out): |
| 105 | if v is None: |
| 106 | out.append("null") |
| 107 | elif v is True: |
| 108 | out.append("true") |
| 109 | elif v is False: |
| 110 | out.append("false") |
| 111 | elif isinstance(v, int): |
| 112 | if not -(1 << 63) <= v < (1 << 64): |
| 113 | raise ValueError(f"integer out of range: {v}") |
| 114 | out.append(str(v)) |
| 115 | elif isinstance(v, float): |
| 116 | raise ValueError(f"floating point not allowed: {v!r}") |
| 117 | elif isinstance(v, str): |
| 118 | _canon_str(v, out) |
| 119 | elif isinstance(v, list): |
| 120 | out.append("[") |
| 121 | for i, x in enumerate(v): |
| 122 | if i: |
| 123 | out.append(",") |
| 124 | _canon_val(x, out) |
| 125 | out.append("]") |
| 126 | elif isinstance(v, dict): |
| 127 | out.append("{") |
| 128 | for i, k in enumerate(sorted(v, key=lambda k: k.encode("utf-8"))): |
| 129 | if i: |
| 130 | out.append(",") |
| 131 | _canon_str(k, out) |
| 132 | out.append(":") |
| 133 | _canon_val(v[k], out) |
| 134 | out.append("}") |
| 135 | else: |
| 136 | raise ValueError(f"not a JSON value: {type(v).__name__}") |
| 137 | |
| 138 | |
| 139 | def canonical(v): |
| 140 | out = [] |
| 141 | _canon_val(v, out) |
| 142 | return "".join(out).encode("utf-8") |
| 143 | |
| 144 | |
| 145 | def parse_json(raw, what): |
| 146 | def no_dupes(pairs): |
| 147 | d = {} |
| 148 | for k, v in pairs: |
| 149 | if k in d: |
| 150 | raise ValueError(f"duplicate key {k!r}") |
| 151 | d[k] = v |
| 152 | return d |
| 153 | |
| 154 | def no_constant(name): |
| 155 | raise ValueError(f"non-JSON constant {name}") |
| 156 | |
| 157 | try: |
| 158 | return json.loads(raw.decode("utf-8"), object_pairs_hook=no_dupes, parse_constant=no_constant) |
| 159 | except (UnicodeDecodeError, ValueError) as e: |
| 160 | raise Rejected("SCHEMA", f"{what} is not valid JSON: {e}") |
| 161 | |
| 162 | |
| 163 | # ------------------------------------------------------------- git fetching |
| 164 | |
| 165 | class Git: |
| 166 | """Blobless, shallow fetches of exact commits into a local cache.""" |
| 167 | |
| 168 | def __init__(self, cache, remote_base): |
| 169 | self.cache = cache |
| 170 | self.base = remote_base.rstrip("/") + "/" |
| 171 | self.heads = {} # repository -> HEAD commit, read once per run by ls-remote |
| 172 | |
| 173 | def _git(self, d, *args): |
| 174 | try: |
| 175 | return subprocess.run(["git", "-C", d, *args], capture_output=True) |
| 176 | except FileNotFoundError: |
| 177 | raise NotRun("git is not installed") |
| 178 | |
| 179 | def _repo(self, repository): |
| 180 | d = os.path.join(self.cache, repository.replace("/", "__") + ".git") |
| 181 | if not os.path.isdir(d): |
| 182 | os.makedirs(d) |
| 183 | for args in (("init", "-q", "--bare"), |
| 184 | ("remote", "add", "origin", self.base + repository), |
| 185 | ("config", "remote.origin.promisor", "true"), |
| 186 | ("config", "remote.origin.partialclonefilter", "blob:none")): |
| 187 | if self._git(d, *args).returncode: |
| 188 | raise NotRun(f"cannot initialise cache {d}") |
| 189 | if repository not in self.heads: |
| 190 | # A reused cache must still talk to the remote named on this run. |
| 191 | if self._git(d, "remote", "set-url", "origin", self.base + repository).returncode: |
| 192 | raise NotRun(f"cannot configure cache {d}") |
| 193 | r = self._git(d, "ls-remote", "origin", "HEAD") |
| 194 | if r.returncode: |
| 195 | raise NotRun(f"cannot reach {self.base + repository}: {_last(r.stderr)}") |
| 196 | head = r.stdout.decode().split("\t", 1)[0].strip() |
| 197 | if not is_hex(head, 40): |
| 198 | raise NotRun(f"{self.base + repository} reports no HEAD commit") |
| 199 | self.heads[repository] = head |
| 200 | return d |
| 201 | |
| 202 | def head(self, repository): |
| 203 | """The commit the remote's HEAD names at the moment this run first reached it.""" |
| 204 | self._repo(repository) |
| 205 | return self.heads[repository] |
| 206 | |
| 207 | def _present(self, d, commit, depth): |
| 208 | if self._git(d, "cat-file", "-e", commit + "^{commit}").returncode: |
| 209 | return False |
| 210 | return depth == 1 or self._git(d, "rev-parse", "--verify", "-q", commit + "^1^{commit}").returncode == 0 |
| 211 | |
| 212 | def has_commit(self, repository, commit, depth=1): |
| 213 | """True if the commit exists upstream; False only on an explicit 'not our ref'.""" |
| 214 | if not is_hex(commit, 40): |
| 215 | return False |
| 216 | d = self._repo(repository) |
| 217 | if self._present(d, commit, depth): |
| 218 | return True |
| 219 | r = self._git(d, "fetch", "-q", f"--depth={depth}", "--filter=blob:none", "origin", commit) |
| 220 | if r.returncode == 0: |
| 221 | return self._git(d, "cat-file", "-e", commit + "^{commit}").returncode == 0 |
| 222 | if b"not our ref" in r.stderr or b"couldn't find remote ref" in r.stderr: |
| 223 | return False |
| 224 | raise NotRun(f"cannot fetch {repository}@{commit}: {_last(r.stderr)}") |
| 225 | |
| 226 | def read(self, repository, commit, path): |
| 227 | """Bytes of path at commit, or None when the path is absent there.""" |
| 228 | if not self.has_commit(repository, commit): |
| 229 | raise Rejected("COMMIT_ABSENT", f"{repository}@{commit} does not exist upstream") |
| 230 | d = self._repo(repository) |
| 231 | tree = self._git(d, "ls-tree", "--name-only", commit, "--", path) |
| 232 | if tree.returncode: |
| 233 | raise NotRun(f"cannot list {repository}@{commit}: {_last(tree.stderr)}") |
| 234 | if tree.stdout.decode().strip() != path: |
| 235 | return None |
| 236 | blob = self._git(d, "cat-file", "blob", f"{commit}:{path}") |
| 237 | if blob.returncode: |
| 238 | raise NotRun(f"cannot fetch {repository}@{commit}:{path}: {_last(blob.stderr)}") |
| 239 | return blob.stdout |
| 240 | |
| 241 | def first_parent(self, repository, commit): |
| 242 | if not self.has_commit(repository, commit, depth=2): |
| 243 | raise Rejected("COMMIT_ABSENT", f"{repository}@{commit} does not exist upstream") |
| 244 | r = self._git(self._repo(repository), "rev-parse", "--verify", "-q", commit + "^1") |
| 245 | return r.stdout.decode().strip() if r.returncode == 0 else None |
| 246 | |
| 247 | |
| 248 | def _last(stderr): |
| 249 | lines = stderr.decode(errors="replace").strip().splitlines() |
| 250 | return lines[-1] if lines else "no diagnostic" |
| 251 | |
| 252 | |
| 253 | # ------------------------------------------------------------- signed bundles |
| 254 | |
| 255 | def ed25519_verify(pubkey_hex, sig_hex, message): |
| 256 | with tempfile.TemporaryDirectory() as t: |
| 257 | paths = {n: os.path.join(t, n) for n in ("pub.der", "sig.bin", "msg.bin")} |
| 258 | for name, data in (("pub.der", SPKI_ED25519 + bytes.fromhex(pubkey_hex)), |
| 259 | ("sig.bin", bytes.fromhex(sig_hex)), ("msg.bin", message)): |
| 260 | with open(paths[name], "wb") as f: |
| 261 | f.write(data) |
| 262 | try: |
| 263 | r = subprocess.run(["openssl", "pkeyutl", "-verify", "-pubin", "-keyform", "DER", |
| 264 | "-inkey", paths["pub.der"], "-rawin", "-in", paths["msg.bin"], |
| 265 | "-sigfile", paths["sig.bin"]], capture_output=True) |
| 266 | except FileNotFoundError: |
| 267 | raise NotRun("openssl is not installed") |
| 268 | if r.returncode == 0 and b"Signature Verified Successfully" in r.stdout: |
| 269 | return True |
| 270 | if r.returncode == 1 and b"Signature Verification Failure" in r.stdout: |
| 271 | return False |
| 272 | raise NotRun(f"openssl could not run the Ed25519 check: {_last(r.stderr)}") |
| 273 | |
| 274 | |
| 275 | def _schema(cond, detail): |
| 276 | if not cond: |
| 277 | raise Rejected("SCHEMA", detail) |
| 278 | |
| 279 | |
| 280 | def validate_bundle(b): |
| 281 | """Shape check of bundle.rs validate(); returns [(gate, required, status, verdict)].""" |
| 282 | _schema(isinstance(b, dict), "bundle must be an object") |
| 283 | _schema(b.get("schema") == BUNDLE_SCHEMA, f"schema must be {BUNDLE_SCHEMA}") |
| 284 | _schema(isinstance(b.get("repository"), str), "repository must be a string") |
| 285 | for k, n in (("commit", 40), ("tree_digest", 64), ("graph_digest", 64)): |
| 286 | _schema(is_hex(b.get(k), n), f"{k} must be {n} lower-case hex characters") |
| 287 | _schema(b.get("receipt_id_scheme") in RECEIPT_ID_SCHEMES, "receipt_id_scheme is not allowed") |
| 288 | _schema(b.get("verdict") in ("PASS", "FAIL", "NOT_RUN"), "verdict is not allowed") |
| 289 | for k in ("started_utc", "finished_utc"): |
| 290 | _schema(isinstance(b.get(k), str), f"{k} must be a string") |
| 291 | ex = b.get("executor") |
| 292 | _schema(isinstance(ex, dict) and is_hex(ex.get("id"), 64) and isinstance(ex.get("class"), str) |
| 293 | and is_hex(ex.get("machine_digest"), 64), "executor is malformed") |
| 294 | checks = b.get("checks") |
| 295 | _schema(isinstance(checks, list), "checks must be an array") |
| 296 | entries = [] |
| 297 | for i, c in enumerate(checks): |
| 298 | _schema(isinstance(c, dict), f"checks[{i}] must be an object") |
| 299 | gate = c.get("gate") |
| 300 | _schema(isinstance(gate, str), f"checks[{i}].gate must be a string") |
| 301 | _schema(is_hex(c.get("check_id"), 64), f"checks[{i}].check_id malformed") |
| 302 | _schema(c.get("exactness") in EXACTNESS, f"checks[{i}].exactness not allowed") |
| 303 | _schema(isinstance(c.get("required"), bool), f"checks[{i}].required must be a bool") |
| 304 | _schema(not (c["required"] and c["exactness"] == "ADVISORY"), f"checks[{i}] ADVISORY cannot be required") |
| 305 | _schema(c.get("status") in STATUSES, f"checks[{i}].status not allowed") |
| 306 | _schema(c.get("verdict") in VERDICTS, f"checks[{i}].verdict not allowed") |
| 307 | _schema(isinstance(c.get("backend"), str), f"checks[{i}].backend must be a string") |
| 308 | if c["status"] == "run": |
| 309 | _schema(is_hex(c.get("receipt"), 64), f"checks[{i}].receipt malformed") |
| 310 | elif c["status"] == "cached": |
| 311 | r = c.get("resolution") |
| 312 | _schema(isinstance(r, dict) and is_hex(r.get("resolved_from"), 64), f"checks[{i}].resolution malformed") |
| 313 | else: |
| 314 | _schema(c["verdict"] != "PASS", f"checks[{i}] status {c['status']} cannot carry PASS") |
| 315 | entries.append((gate, c["required"], c["status"], c["verdict"])) |
| 316 | gates = [e[0] for e in entries] |
| 317 | _schema(len(gates) == len(set(gates)), "checks[] lists a gate twice") |
| 318 | return entries |
| 319 | |
| 320 | |
| 321 | def compute_verdict(entries): |
| 322 | required = [e for e in entries if e[1]] |
| 323 | if any(e[3] == "FAIL" for e in required): |
| 324 | return "FAIL" |
| 325 | if all(e[2] in ("run", "cached") and e[3] == "PASS" for e in required): |
| 326 | return "PASS" |
| 327 | return "NOT_RUN" |
| 328 | |
| 329 | |
| 330 | def evaluate_bundle(git, shelf, raw, craw): |
| 331 | parts = shelf["path"].split("/") |
| 332 | if len(parts) != 3 or parts[2] != "bundle.json" or not is_hex(parts[1], 40): |
| 333 | raise Rejected("PATH_BINDING", f"{shelf['path']} is not <repo>/<sha>/bundle.json") |
| 334 | if craw is not None: |
| 335 | # BUNDLE_BASIS asserts that this shelf has no correction records; refuse rather than ignore one. |
| 336 | raise Rejected("CORRECTION_UNSUPPORTED", f"{correction_path(shelf['path'])} exists; bundle corrections" |
| 337 | " have no admission rule yet") |
| 338 | source = {"repository": f"{SHELF_OWNER}/{parts[0]}", "commit": parts[1]} |
| 339 | b = parse_json(raw, shelf["path"]) |
| 340 | entries = validate_bundle(b) |
| 341 | sig = b.get("signature") |
| 342 | _schema(isinstance(sig, dict) and sig.get("alg") == "ed25519", "signature.alg must be ed25519") |
| 343 | _schema(is_hex(sig.get("pubkey"), 64) and is_hex(sig.get("sig"), 128), "signature members malformed") |
| 344 | base = git.first_parent(source["repository"], source["commit"]) |
| 345 | if base is None: |
| 346 | raise Rejected("NO_TRUST_ANCHOR", f"{source['commit']} has no parent to read .aien/ from") |
| 347 | pub = git.read(source["repository"], base, ".aien/verify.pub") |
| 348 | always = git.read(source["repository"], base, ".aien/always") |
| 349 | if pub is None or always is None: |
| 350 | raise Rejected("NO_TRUST_ANCHOR", f"{source['repository']}@{base} lacks .aien/verify.pub or .aien/always") |
| 351 | pub = pub.decode().strip() |
| 352 | _schema(is_hex(pub, 64), ".aien/verify.pub must be 64 hex characters") |
| 353 | required = [ln.strip() for ln in always.decode().splitlines() if ln.strip() and not ln.startswith("#")] |
| 354 | # verify() order in bundle.rs: key known, signature, repository, commit, executor, required, verdict. |
| 355 | if sig["pubkey"] != pub: |
| 356 | raise Rejected("UNKNOWN_KEY", "bundle key is not the base-branch .aien/verify.pub") |
| 357 | try: |
| 358 | message = canonical({k: v for k, v in b.items() if k != "signature"}) |
| 359 | except ValueError as e: |
| 360 | raise Rejected("SCHEMA", f"not canonical-encodable: {e}") |
| 361 | if not ed25519_verify(pub, sig["sig"], message): |
| 362 | raise Rejected("BAD_SIGNATURE", "signature does not verify over the canonical bytes") |
| 363 | if b["repository"] != "github.com/" + source["repository"]: |
| 364 | raise Rejected("REPOSITORY_MISMATCH", f"bundle {b['repository']}, shelf path {source['repository']}") |
| 365 | if b["commit"] != source["commit"]: |
| 366 | raise Rejected("COMMIT_MISMATCH", f"bundle {b['commit']}, shelf path {source['commit']}") |
| 367 | if b["executor"]["id"] != sha256(bytes.fromhex(pub)): |
| 368 | raise Rejected("UNKNOWN_EXECUTOR", "executor.id is not sha256(verify.pub)") |
| 369 | for g in required: |
| 370 | found = [e for e in entries if e[0] == g] |
| 371 | if not found: |
| 372 | raise Rejected("MISSING_REQUIRED_CHECK", g) |
| 373 | if not found[0][1]: |
| 374 | raise Rejected("SCHEMA", f"{g} is required by the gate but marked optional in the bundle") |
| 375 | computed = compute_verdict(entries) |
| 376 | if computed != b["verdict"]: |
| 377 | raise Rejected("VERDICT_INCONSISTENT", f"declared {b['verdict']}, computed {computed}") |
| 378 | gates = [e[0] for e in entries if e[1]] |
| 379 | return { |
| 380 | "issue_or_gate": {"value": f"{source['repository']} required gates: {', '.join(gates) or 'none'}", |
| 381 | "basis": "bundle repository and the gate of every required check", "verified": True}, |
| 382 | "source": source, |
| 383 | "trust_anchor": {"repository": source["repository"], "commit": base, |
| 384 | "rule": "first parent of the source commit", "verify_pub": pub, "always": required}, |
| 385 | "signature": "VERIFIED (OpenSSL Ed25519 over canonical bytes without the signature member)", |
| 386 | "gates": [{k: c[k] for k in ("gate", "backend", "exactness", "required", "status", "verdict")} |
| 387 | for c in b["checks"]], |
| 388 | "correction": None, |
| 389 | "historical_verdict": b["verdict"], |
| 390 | "effective_verdict": b["verdict"], |
| 391 | "effective_basis": BUNDLE_BASIS, |
| 392 | } |
| 393 | |
| 394 | |
| 395 | # ------------------------------------------------------------- omega receipts |
| 396 | |
| 397 | def omega_issue_or_gate(d): |
| 398 | """Issue or gate named by the receipt itself, or None when the receipt names none.""" |
| 399 | milestone, contract = d.get("milestone"), d.get("contract_id") |
| 400 | if not isinstance(milestone, str) or not milestone.strip(): |
| 401 | return None |
| 402 | if isinstance(contract, str) and contract.strip(): |
| 403 | return {"value": f"Omega {milestone} qualification ({contract})", |
| 404 | "basis": "receipt fields milestone and contract_id", "verified": True} |
| 405 | return {"value": f"Omega {milestone} qualification", "basis": "receipt field milestone", "verified": True} |
| 406 | |
| 407 | |
| 408 | def evaluate_omega(git, shelf, raw, source_repository, craw): |
| 409 | d = parse_json(raw, shelf["path"]) |
| 410 | _schema(isinstance(d, dict), "receipt must be an object") |
| 411 | # The receipts do not name their source repository; it is taken from the index (docs, "Values taken on trust"). |
| 412 | _schema(isinstance(source_repository, str) and source_repository.startswith(SHELF_OWNER + "/") |
| 413 | and source_repository.count("/") == 1, f"source.repository must be {SHELF_OWNER}/<name>") |
| 414 | historical = d.get("status") |
| 415 | if historical != ADMITTED_HISTORICAL_STATUS: |
| 416 | raise Rejected("UNSUPPORTED_STATUS", f"status {historical!r} is not {ADMITTED_HISTORICAL_STATUS!r}") |
| 417 | correction = None |
| 418 | if craw is not None: |
| 419 | cpath = correction_path(shelf["path"]) |
| 420 | c = parse_json(craw, cpath) |
| 421 | _schema(isinstance(c, dict) and c.get("schema") == CORRECTION_SCHEMA, f"{cpath} schema") |
| 422 | corr = c.get("corrects") or {} |
| 423 | if (corr.get("repository"), corr.get("path"), corr.get("sha256")) != ( |
| 424 | shelf["repository"], shelf["path"], sha256(raw)): |
| 425 | raise Rejected("CORRECTION_UNBOUND", f"{cpath} does not name these receipt bytes") |
| 426 | disp = c.get("disposition") or {} |
| 427 | _schema(isinstance(disp.get("supersedes_historical_status_for_admission"), bool) |
| 428 | and isinstance(disp.get("qualification_claim"), str), f"{cpath} disposition malformed") |
| 429 | correction = {"path": cpath, "sha256": sha256(craw), "correction_id": c.get("correction_id"), |
| 430 | "recorded_on": c.get("recorded_on"), |
| 431 | "supersedes_historical_status_for_admission": |
| 432 | disp["supersedes_historical_status_for_admission"], |
| 433 | "qualification_claim": disp["qualification_claim"]} |
| 434 | field = next((f for f in SOURCE_COMMIT_FIELDS if is_hex(d.get(f), 40)), None) |
| 435 | commit = d[field] if field else None |
| 436 | resolves = bool(commit) and git.has_commit(source_repository, commit) |
| 437 | artifacts = [] |
| 438 | arts = d.get("artifacts") if isinstance(d.get("artifacts"), dict) else {} |
| 439 | for path in sorted(arts): |
| 440 | v = arts[path] |
| 441 | digest = v.get("sha256") if isinstance(v, dict) else None |
| 442 | if not is_hex(digest, 64): |
| 443 | result = "no-digest" |
| 444 | elif path.startswith("build/"): |
| 445 | result = "not-recoverable (build output)" |
| 446 | elif not resolves: |
| 447 | result = "commit-unresolved" |
| 448 | else: |
| 449 | src = git.read(source_repository, commit, path) |
| 450 | result = "absent" if src is None else ("match" if sha256(src) == digest else "mismatch") |
| 451 | artifacts.append({"path": path, "sha256": digest, "at_source_commit": result}) |
| 452 | source_ok = (resolves and any(a["at_source_commit"] == "match" for a in artifacts) |
| 453 | and all(a["at_source_commit"] in ("match", "not-recoverable (build output)", "no-digest") |
| 454 | for a in artifacts)) |
| 455 | rc = d.get("receipt_commit") |
| 456 | receipt_commit = {"value": rc, "resolves": git.has_commit(source_repository, rc) if is_hex(rc, 40) else None} |
| 457 | if correction and correction["supersedes_historical_status_for_admission"]: |
| 458 | effective, basis = correction["qualification_claim"], f"shelf correction {correction['correction_id']}" |
| 459 | elif not source_ok: |
| 460 | effective, basis = "REFUSED_SOURCE_PROVENANCE", "index source check (no superseding shelf correction)" |
| 461 | else: |
| 462 | effective, basis = "PASS", "historical status; named source commit resolves and source digests match" |
| 463 | return { |
| 464 | "issue_or_gate": omega_issue_or_gate(d), |
| 465 | "source": {"repository": source_repository, "commit_field": field, "commit": commit, |
| 466 | "commit_resolves": resolves, "receipt_commit": receipt_commit, "artifacts": artifacts, |
| 467 | "source_check": "PASS" if source_ok else "FAIL"}, |
| 468 | "correction": correction, |
| 469 | "historical_verdict": historical, |
| 470 | "effective_verdict": effective, |
| 471 | "effective_basis": basis, |
| 472 | } |
| 473 | |
| 474 | |
| 475 | # ------------------------------------------------------------- admit / replay |
| 476 | |
| 477 | def correction_path(path): |
| 478 | return path[:-len(".json")] + ".correction.json" |
| 479 | |
| 480 | |
| 481 | def evaluate(git, kind, shelf_loc, source_repository, raw, stated_issue=None): |
| 482 | """Recompute an entry. stated_issue is used only when the receipt names no issue or gate.""" |
| 483 | if kind not in KINDS: |
| 484 | raise Rejected("SCHEMA", f"unknown kind {kind!r}") |
| 485 | repo, commit, path = shelf_loc["repository"], shelf_loc["commit"], shelf_loc["path"] |
| 486 | if repo != SHELF_REPOS[kind]: |
| 487 | raise Rejected("SHELF_REPOSITORY", f"{kind} receipts live in {SHELF_REPOS[kind]}, not {repo}") |
| 488 | _schema(isinstance(path, str) and path.endswith(".json"), "shelf.path must name a .json file") |
| 489 | shelf = {"repository": repo, "commit": commit, "path": path, "sha256": sha256(raw), "bytes": len(raw)} |
| 490 | # A correction may land after the pinned commit. The one at the shelf HEAD must be the one pinned. |
| 491 | cpath = correction_path(path) |
| 492 | craw = git.read(repo, commit, cpath) |
| 493 | head = git.head(repo) |
| 494 | at_head = craw if head == commit else git.read(repo, head, cpath) |
| 495 | if at_head != craw: |
| 496 | state = "is absent" if at_head is None else f"has sha256 {sha256(at_head)}" |
| 497 | pinned = "absent" if craw is None else f"sha256 {sha256(craw)}" |
| 498 | raise Rejected("STALE_CORRECTION", f"{cpath} at {repo} HEAD {head} {state}; at the indexed commit " |
| 499 | f"{commit} it is {pinned}. Re-admit the entry at the HEAD") |
| 500 | if kind == "signed-bundle": |
| 501 | out = evaluate_bundle(git, shelf, raw, craw) |
| 502 | else: |
| 503 | out = evaluate_omega(git, shelf, raw, source_repository, craw) |
| 504 | if out["issue_or_gate"] is None: |
| 505 | if not isinstance(stated_issue, str) or not stated_issue.strip(): |
| 506 | raise Rejected("SCHEMA", "the receipt names no issue or gate; supply one (it is recorded UNVERIFIED)") |
| 507 | out["issue_or_gate"] = {"value": stated_issue, "basis": UNVERIFIED_ISSUE_BASIS, "verified": False} |
| 508 | return {"kind": kind, "shelf": shelf, **out} |
| 509 | |
| 510 | |
| 511 | def fetch_shelf(git, shelf_loc): |
| 512 | raw = git.read(shelf_loc["repository"], shelf_loc["commit"], shelf_loc["path"]) |
| 513 | if raw is None: |
| 514 | raise Rejected("SHELF_PATH_ABSENT", f"{shelf_loc['path']} absent at {shelf_loc['repository']}@{shelf_loc['commit']}") |
| 515 | return raw |
| 516 | |
| 517 | |
| 518 | def exit_for(effective): |
| 519 | if effective in ("PASS", "FAIL", "NOT_RUN"): |
| 520 | return EXIT[effective] |
| 521 | if effective.startswith("REFUSED"): |
| 522 | return EXIT["REFUSED"] |
| 523 | return EXIT["NOT_RUN"] |
| 524 | |
| 525 | |
| 526 | def replay_command(eid): |
| 527 | return f"python3 tools/replay_receipt.py replay {eid}" |
| 528 | |
| 529 | |
| 530 | def replay_entry(git, entry, override=None): |
| 531 | """Returns (rc, last line, reproduced). Prints the evidence lines before it.""" |
| 532 | eid = entry.get("id", "?") |
| 533 | try: |
| 534 | kind = entry.get("kind") |
| 535 | if kind not in KINDS: |
| 536 | raise Rejected("SCHEMA", f"unknown kind {kind!r}") |
| 537 | unknown = sorted(set(entry) - ENTRY_FIELDS[kind]) |
| 538 | if unknown: |
| 539 | raise Rejected("UNKNOWN_FIELD", "the index entry carries fields this tool does not check: " |
| 540 | + ", ".join(unknown)) |
| 541 | if not isinstance(eid, str) or not eid or ":" in eid: |
| 542 | raise Rejected("SCHEMA", "id must be a non-empty string without ':'") |
| 543 | if entry.get("replay") != replay_command(eid): |
| 544 | raise Rejected("INDEX_DRIFT", "recomputed fields differ from the index: replay") |
| 545 | shelf = entry.get("shelf") |
| 546 | _schema(isinstance(shelf, dict) and all(isinstance(shelf.get(k), str) for k in |
| 547 | ("repository", "commit", "path", "sha256")), "shelf malformed") |
| 548 | print(f"entry: {eid} ({kind})") |
| 549 | if override is not None: |
| 550 | with open(override, "rb") as f: |
| 551 | raw = f.read() |
| 552 | print(f"shelf: local override {override} (not fetched)") |
| 553 | else: |
| 554 | raw = fetch_shelf(git, shelf) |
| 555 | print(f"shelf: fetched {shelf['repository']}@{shelf['commit']}:{shelf['path']}") |
| 556 | got = sha256(raw) |
| 557 | print(f"digest: sha256={got} expected={shelf['sha256']}") |
| 558 | if got != shelf["sha256"]: |
| 559 | raise Rejected("DIGEST_MISMATCH", f"sha256 {got} != indexed {shelf['sha256']}") |
| 560 | issue = entry.get("issue_or_gate") |
| 561 | computed = evaluate(git, kind, shelf, (entry.get("source") or {}).get("repository"), raw, |
| 562 | issue.get("value") if isinstance(issue, dict) else None) |
| 563 | drift = sorted(k for k in computed if computed[k] != entry.get(k)) |
| 564 | if drift: |
| 565 | raise Rejected("INDEX_DRIFT", "recomputed fields differ from the index: " + ", ".join(drift)) |
| 566 | i = computed["issue_or_gate"] |
| 567 | if i["verified"]: |
| 568 | print(f"issue_or_gate: derived from the {i['basis']}: {i['value']}") |
| 569 | else: |
| 570 | print(f"issue_or_gate: UNVERIFIED (index text; the receipt names no issue or gate): {i['value']}") |
| 571 | if computed.get("signature"): |
| 572 | print(f"signature: {computed['signature']}; key from {computed['trust_anchor']['repository']}" |
| 573 | f"@{computed['trust_anchor']['commit']}:.aien/verify.pub") |
| 574 | head = git.head(shelf["repository"]) |
| 575 | if computed["correction"]: |
| 576 | c = computed["correction"] |
| 577 | print(f"correction: {c['path']} sha256={c['sha256']} supersedes={c['supersedes_historical_status_for_admission']}" |
| 578 | f" claim={c['qualification_claim']}; identical at shelf HEAD {head}") |
| 579 | else: |
| 580 | print(f"correction: none at the shelf commit or at shelf HEAD {head}") |
| 581 | if kind == "omega-qualification-receipt": |
| 582 | s = computed["source"] |
| 583 | print(f"source: {s['repository']}@{s['commit']} resolves={s['commit_resolves']} source_check={s['source_check']}" |
| 584 | " (repository taken from the index: the receipt does not name it)") |
| 585 | eff = computed["effective_verdict"] |
| 586 | print(f"historical: {computed['historical_verdict']}; effective basis: {computed['effective_basis']}") |
| 587 | rc = exit_for(eff) |
| 588 | mark = "" if i["verified"] else " issue_or_gate=UNVERIFIED" |
| 589 | return rc, f"REPLAY {eid}: {eff} rc={rc}{mark}", True |
| 590 | except Rejected as e: |
| 591 | return EXIT["REJECTED"], f"REPLAY {eid}: REJECTED {e} rc={EXIT['REJECTED']}", False |
| 592 | except NotRun as e: |
| 593 | return EXIT["NOT_RUN"], f"REPLAY {eid}: NOT_RUN {e} rc={EXIT['NOT_RUN']}", False |
| 594 | |
| 595 | |
| 596 | def load_index(path): |
| 597 | with open(path, "rb") as f: |
| 598 | idx = parse_json(f.read(), path) |
| 599 | if not isinstance(idx, dict) or idx.get("schema") != INDEX_SCHEMA or not isinstance(idx.get("entries"), list): |
| 600 | raise Rejected("SCHEMA", f"{path} is not an {INDEX_SCHEMA} index") |
| 601 | unknown = sorted(set(idx) - INDEX_FIELDS) |
| 602 | if unknown: |
| 603 | raise Rejected("UNKNOWN_FIELD", f"{path} carries index fields this tool does not know: " + ", ".join(unknown)) |
| 604 | if not isinstance(idx.get("index_version"), int) or not all(isinstance(e, dict) for e in idx["entries"]): |
| 605 | raise Rejected("SCHEMA", f"{path}: index_version must be an integer and every entry an object") |
| 606 | ids = [e.get("id") for e in idx["entries"]] |
| 607 | if len(ids) != len(set(ids)): |
| 608 | raise Rejected("SCHEMA", f"{path} repeats an entry id") |
| 609 | return idx |
| 610 | |
| 611 | |
| 612 | def parse_shelf_arg(s): |
| 613 | try: |
| 614 | repo_commit, path = s.split(":", 1) |
| 615 | repository, commit = repo_commit.split("@", 1) |
| 616 | except ValueError: |
| 617 | raise SystemExit("--shelf must be OWNER/REPO@COMMIT:PATH") |
| 618 | return {"repository": repository, "commit": commit, "path": path} |
| 619 | |
| 620 | |
| 621 | def main(argv=None): |
| 622 | ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) |
| 623 | ap.add_argument("--cache", help="git object cache directory (default: a fresh temporary directory)") |
| 624 | ap.add_argument("--remote-base", default="https://github.com/", help="prefix for OWNER/REPO fetch URLs") |
| 625 | sub = ap.add_subparsers(dest="cmd", required=True) |
| 626 | r = sub.add_parser("replay", help="replay indexed entries") |
| 627 | r.add_argument("id", nargs="?") |
| 628 | r.add_argument("--all", action="store_true") |
| 629 | r.add_argument("--index", default=DEFAULT_INDEX) |
| 630 | r.add_argument("--bytes", help="replay these local bytes instead of the fetched shelf file (controls)") |
| 631 | a = sub.add_parser("admit", help="compute a new index entry from pinned commits") |
| 632 | a.add_argument("--kind", required=True, choices=KINDS) |
| 633 | a.add_argument("--shelf", required=True, help="OWNER/REPO@COMMIT:PATH") |
| 634 | a.add_argument("--source-repo", help="implementation repository (omega-qualification-receipt)") |
| 635 | a.add_argument("--id", required=True, help="entry id (no ':' characters)") |
| 636 | a.add_argument("--issue-or-gate", help="issue or gate, only for a receipt that names none (recorded UNVERIFIED)") |
| 637 | args = ap.parse_args(argv) |
| 638 | if args.cmd == "replay" and bool(args.id) == bool(args.all): |
| 639 | ap.error("replay needs exactly one of ID or --all") |
| 640 | if args.cmd == "admit" and args.kind == "omega-qualification-receipt" and not args.source_repo: |
| 641 | ap.error("--source-repo is required for omega-qualification-receipt") |
| 642 | with tempfile.TemporaryDirectory() as tmp: |
| 643 | git = Git(args.cache or tmp, args.remote_base) |
| 644 | if args.cmd == "admit": |
| 645 | shelf = parse_shelf_arg(args.shelf) |
| 646 | try: |
| 647 | raw = fetch_shelf(git, shelf) |
| 648 | computed = evaluate(git, args.kind, shelf, args.source_repo, raw, args.issue_or_gate) |
| 649 | except Rejected as e: |
| 650 | print(f"ADMIT {args.id}: REJECTED {e} rc=3") |
| 651 | return EXIT["REJECTED"] |
| 652 | except NotRun as e: |
| 653 | print(f"ADMIT {args.id}: NOT_RUN {e} rc=2") |
| 654 | return EXIT["NOT_RUN"] |
| 655 | if args.issue_or_gate is not None and computed["issue_or_gate"]["verified"]: |
| 656 | print(f"ADMIT {args.id}: NOT_RUN --issue-or-gate given, but the receipt names its own " |
| 657 | f"({computed['issue_or_gate']['value']}); drop the option rc=2") |
| 658 | return EXIT["NOT_RUN"] |
| 659 | if not args.id or ":" in args.id: |
| 660 | ap.error("--id must be non-empty and contain no ':'") |
| 661 | entry = {"id": args.id, "issue_or_gate": computed["issue_or_gate"], **computed, |
| 662 | "replay": replay_command(args.id)} |
| 663 | print(json.dumps(entry, indent=1, ensure_ascii=False)) |
| 664 | return 0 |
| 665 | try: |
| 666 | idx = load_index(args.index) |
| 667 | except OSError as e: |
| 668 | print(f"REPLAY: NOT_RUN cannot load index: {e} rc=2") |
| 669 | return EXIT["NOT_RUN"] |
| 670 | except Rejected as e: |
| 671 | print(f"REPLAY: REJECTED index {args.index}: {e} rc=3") |
| 672 | return EXIT["REJECTED"] |
| 673 | if args.id: |
| 674 | entry = next((e for e in idx["entries"] if e.get("id") == args.id), None) |
| 675 | if entry is None: |
| 676 | print(f"REPLAY {args.id}: NOT_RUN no such entry in {args.index} rc=2") |
| 677 | return EXIT["NOT_RUN"] |
| 678 | rc, last, _ = replay_entry(git, entry, args.bytes) |
| 679 | print(last) |
| 680 | return rc |
| 681 | worst, bad = 0, 0 |
| 682 | for entry in idx["entries"]: |
| 683 | rc, last, reproduced = replay_entry(git, entry) |
| 684 | print(last) |
| 685 | if not reproduced: |
| 686 | bad += 1 |
| 687 | worst = max(worst, rc) |
| 688 | n = len(idx["entries"]) |
| 689 | print(f"INDEX {os.path.basename(args.index)} v{idx.get('index_version')}: " |
| 690 | f"{n - bad}/{n} entries reproduce as indexed rc={worst}") |
| 691 | return worst |
| 692 | |
| 693 | |
| 694 | if __name__ == "__main__": |
| 695 | sys.exit(main()) |