#!/usr/bin/env python3 """Verify a CAIN-42 E82 external reproduction attestation. Imports only the Python standard library and `cryptography`. It imports no CAIN code. The attestation is signed over canonical JSON of the whole object minus `signature_b64`. """ from __future__ import annotations import argparse import base64 import hashlib import json import sys from pathlib import Path from typing import Any, Dict, List from cryptography.exceptions import InvalidSignature from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey EXPECTED = { "merkle_root": "63868034b46e901f2cec392cd25c22ab947516e594543e02155857a9c31c5ac9", "bundle_zip_sha256": "484f4dfe54cc83de618f3ff420427afacacb5a3201ae3309590435336e63096f", "manifest_sha256": "c0fa080c79d6a0af0289b351c2a8366f3fb3512e99189aa9d577565df6228f54", "file_count": 240, "checks_passed": 55, "checks_total": 55, } def canonical(obj: Any) -> bytes: return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode() def verify(path: Path, *, expected_merkle: str = EXPECTED["merkle_root"], expected_zip: str = EXPECTED["bundle_zip_sha256"], pinned_key: str = "") -> Dict[str, Any]: checks: List[Dict[str, Any]] = [] def add(name: str, ok: bool, detail: Any = "") -> None: checks.append({"check": name, "ok": bool(ok), "detail": detail}) try: body = json.loads(Path(path).read_text()) except Exception as exc: return {"ok": False, "checks": [{"check": "json", "ok": False, "detail": f"{type(exc).__name__}:{exc}"}], "schema": "cain42.external_reproduction.verification.v1"} add("schema", body.get("schema") == "cain42.external_reproduction.v1", body.get("schema")) add("nonce_length", len(str(body.get("nonce", ""))) >= 16, len(str(body.get("nonce", "")))) att = body.get("attestor", {}) add("attestor_identity", all(att.get(k) for k in ("name", "organization", "email")), {k: bool(att.get(k)) for k in ("name", "organization", "email")}) ind = body.get("independence", {}) add("no_cain_code_imported", ind.get("no_cain_code_imported") is True, ind.get("no_cain_code_imported")) add("independence_statement", len(str(ind.get("statement", ""))) >= 10, len(str(ind.get("statement", "")))) add("project_affiliation_false", ind.get("project_affiliation") is False, ind.get("project_affiliation")) env = body.get("environment", {}) add("environment_complete", all(env.get(k) for k in ("os", "python", "cryptography")), {k: bool(env.get(k)) for k in ("os", "python", "cryptography")}) art = body.get("artifact", {}) add("merkle_root", art.get("merkle_root") == expected_merkle, art.get("merkle_root")) add("bundle_zip_sha256", art.get("bundle_zip_sha256") == expected_zip, art.get("bundle_zip_sha256")) add("manifest_sha256", art.get("manifest_sha256") == EXPECTED["manifest_sha256"], art.get("manifest_sha256")) add("file_count", int(art.get("file_count", -1)) == EXPECTED["file_count"], art.get("file_count")) res = body.get("result", {}) add("result_ok", res.get("ok") is True, res.get("ok")) add("checks_passed", int(res.get("checks_passed", -1)) == EXPECTED["checks_passed"], res.get("checks_passed")) add("checks_total", int(res.get("checks_total", -1)) == EXPECTED["checks_total"], res.get("checks_total")) add("result_merkle", res.get("merkle_root") == expected_merkle, res.get("merkle_root")) add("timestamp_present", len(str(body.get("timestamp_utc", ""))) >= 20, body.get("timestamp_utc")) add("commands_present", bool(body.get("commands")), len(body.get("commands", []))) pub = str(body.get("public_key_b64", "")) sig = str(body.get("signature_b64", "")) if pinned_key: add("pinned_key", pub == pinned_key, pub[:16]) try: key = Ed25519PublicKey.from_public_bytes(base64.b64decode(pub)) key.verify(base64.b64decode(sig), canonical({k: v for k, v in body.items() if k != "signature_b64"})) add("signature", True) except (InvalidSignature, ValueError, TypeError) as exc: add("signature", False, f"{type(exc).__name__}") ok = all(c["ok"] for c in checks) return {"schema": "cain42.external_reproduction.verification.v1", "ok": ok, "checks_passed": sum(1 for c in checks if c["ok"]), "checks_total": len(checks), "checks": checks, "evidence_class": "EXTERNAL_ATTESTATION" if ok else "INVALID", "note": "A valid attestation means this named attestor signed this result. It does " "not make the attestor a certification body."} def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("attestation") ap.add_argument("--expected-merkle", default=EXPECTED["merkle_root"]) ap.add_argument("--expected-zip", default=EXPECTED["bundle_zip_sha256"]) ap.add_argument("--pinned-key", default="") ap.add_argument("--json", default="") args = ap.parse_args() rep = verify(Path(args.attestation), expected_merkle=args.expected_merkle, expected_zip=args.expected_zip, pinned_key=args.pinned_key) text = json.dumps(rep, indent=1, sort_keys=True) if args.json: Path(args.json).write_text(text) print(text) return 0 if rep["ok"] else 1 if __name__ == "__main__": raise SystemExit(main())