#!/usr/bin/env python3 """Clean-room offline verifier for CAIN governance contracts (cain.contract.v1). Written from the spec in platform-gateway/cain_governance_contract.py's docstring and the evidence bundle's CONTRACT_SPEC.md. It imports NOTHING from CAIN: standard library + `cryptography` only. It re-implements the canonical form, digests, signatures, structural rules, risk scoring and the decision function independently, so a bug in the runtime shows up as a disagreement here (tests/test_governance_contract_cleanroom.py diffs the two). python3 scripts/contract_verify_offline.py export.json --issuer-key [--tenant T] [--at-ms N] Input: the JSON produced by GovernanceContractFabric.export(contract_id). Exit 0 if every check passes. Without --issuer-key the issuer key inside the export is used and the result says SELF_ASSERTED_KEY: that proves only internal consistency, not who issued it. """ from __future__ import annotations import argparse import base64 import hashlib import json import os import re import sys import unicodedata from cryptography.exceptions import InvalidSignature from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey SECTION_NAMES = ["header", "subject", "purpose", "capability", "authority", "policy", "risk", "action", "execution_path", "environment", "evidence_policy", "conditions", "validity", "annotations"] US = b"\x1f" LIMIT = 1 << 53 # -------------------------------------------------------------------------------------------- canonical form class Bad(Exception): pass def _walk(v, where="$"): if v is None or v is True or v is False: return t = type(v) if t is int: if v <= -LIMIT or v >= LIMIT: raise Bad(f"{where}: integer out of range") elif t is float: raise Bad(f"{where}: float") elif t is str: if unicodedata.normalize("NFC", v) != v or "\x00" in v: raise Bad(f"{where}: non-NFC or NUL string") elif t is list: for n, x in enumerate(v): _walk(x, f"{where}[{n}]") elif t is dict: for k in v: if type(k) is not str or not re.fullmatch(r"[a-z0-9_]{1,64}", k): raise Bad(f"{where}: bad key {k!r}") _walk(v[k], f"{where}.{k}") else: raise Bad(f"{where}: type {t.__name__}") def canon(v) -> bytes: _walk(v) return json.dumps(v, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode() def h(b: bytes) -> str: return hashlib.sha256(b).hexdigest() def fp_of(body) -> str: digests = {} for name in SECTION_NAMES: digests[name] = h(b"CAIN/contract/v1/section" + US + name.encode() + US + canon(body[name])) return h(b"CAIN/contract/v1/fingerprint" + US + canon(digests)) def req_hash(req) -> str: return h(b"CAIN/contract/v1/request" + US + canon(req)) def grant_of(snapshot) -> str: return h(b"CAIN/contract/v1/grant" + US + canon(snapshot)) def sig_ok(pub_b64, msg, sig_b64) -> bool: try: Ed25519PublicKey.from_public_bytes(base64.b64decode(pub_b64, validate=True)).verify( base64.b64decode(sig_b64, validate=True), msg) return True except (InvalidSignature, ValueError, TypeError): return False # -------------------------------------------------------------------------------------------- spec rules KINDS = {"openshell": ["exec"], "memvault": ["memory_write", "memory_read"], "scitt": ["evidence_register"]} ENGINE = {"openshell": "cain_openshell_gateway", "memvault": "cain_memvault", "scitt": "cain_scitt_clearinghouse"} BASE = {"exec": 40, "memory_write": 25, "memory_read": 10, "evidence_register": 5} CLASSES = ["low", "medium", "high", "critical"] TRUST = {"low": 0, "medium": 1, "high": 2} def score(body) -> int: s = BASE.get(body["action"]["kind"], 50) s += 0 if body["action"]["request_hash"] else 20 s += min(body["capability"]["max_uses"], 10) v = body["validity"] s += 10 if v["expires_at_ms"] - v["not_before_ms"] > 900_000 else 0 s += 0 if body["conditions"] else 10 s += 0 if body["evidence_policy"]["scitt_required"] else 10 return min(s, 100) def klass(sc: int) -> str: for threshold, name in ((75, "critical"), (50, "high"), (25, "medium")): if sc >= threshold: return name return "low" def structural(body) -> list: """Independent subset of the validator: the rules an auditor most needs. Returns a list of problems.""" p = [] if sorted(body) != sorted(SECTION_NAMES): return ["sections differ from the 14 required"] hd = body["header"] if hd.get("schema") != "cain.contract.v1": p.append("schema") if not re.fullmatch(r"ctr_[0-9a-f]{32}", str(hd.get("contract_id"))): p.append("contract_id") ver = hd.get("version") if type(ver) is not int or ver < 1: p.append("version") elif (ver == 1) != (hd.get("supersedes") == ""): p.append("supersedes/version mismatch") prod, kind = body["policy"].get("product"), body["action"].get("kind") if kind not in KINDS.get(prod, []): p.append("action kind does not belong to product (confusion)") if body["capability"].get("action") != f"{prod}.{kind}": p.append("capability.action != product.kind") ep = body["execution_path"] if ep.get("product") != prod or ep.get("engine") != ENGINE.get(prod) or ep.get("adapter_version") != "1": p.append("execution_path mismatch or downgrade") if body["authority"].get("source") != "rig": p.append("authority source is not rig") ch = body["authority"].get("agent_chain") or [] if not ch or ch[-1] != body["subject"].get("agent_id") or len(set(ch)) != len(ch): p.append("agent_chain does not end at the subject") if body["environment"].get("model_runtime_digest") != body["subject"].get("runtime_digest"): p.append("model_runtime_digest != subject.runtime_digest") v = body["validity"] span = v["expires_at_ms"] - v["not_before_ms"] if not 1000 <= span <= 86_400_000: p.append("validity window out of bounds") try: sc = score(body) declared = body["risk"]["risk_class"] if declared not in CLASSES or CLASSES.index(declared) < CLASSES.index(klass(sc)): p.append(f"risk downgrade: declared {declared}, computed {klass(sc)} ({sc})") if sc > body["risk"]["max_risk_score"]: p.append("risk score above declared ceiling") if declared == "critical" and (not body["action"]["request_hash"] or body["capability"]["max_uses"] != 1 or span > 300_000): p.append("critical contract not pinned / single-use / short") if declared == "high" and not body["action"]["request_hash"] and not body["conditions"]: p.append("high contract neither pinned nor conditioned") except (KeyError, TypeError): p.append("risk section malformed") return p # -------------------------------------------------------------------------------------------- decision (re-derived) def _under(path, root): path = os.path.normpath(path) root = root.rstrip("/") or "/" return root == "/" or path == root or path.startswith(root + "/") def _scope_has(res, sc): if sc == "*": return True if sc[-1:] == "*": return res.startswith(sc[:-1]) return res == sc or res.startswith(sc.rstrip("/") + "/") def _request_shape_ok(kind, r) -> bool: if type(r) is not dict: return False try: if len(canon(r)) > 64 * 1024: return False except Bad: return False s = lambda x: type(x) is str and x != "" # noqa: E731 if kind == "exec": if set(r) != {"argv", "cwd", "timeout_s"}: return False av = r["argv"] if type(av) is not list or not 1 <= len(av) <= 64 or any(type(a) is not str or len(a) > 4096 for a in av): return False cwd = r["cwd"] if type(cwd) is not str or not cwd.startswith("/") or len(cwd) > 512 or ".." in cwd.split("/") or \ any(ch in cwd for ch in "\0\n\r"): return False return type(r["timeout_s"]) is int and 1 <= r["timeout_s"] <= 60 if kind == "memory_write": return set(r) == {"namespace", "memory_key", "content", "source_type", "source_id"} and \ all(s(r[k]) for k in ("namespace", "memory_key", "content", "source_type")) and type(r["source_id"]) is str if kind == "memory_read": return set(r) == {"namespace", "query", "top_k", "min_trust"} and s(r["query"]) and s(r["namespace"]) and \ type(r["top_k"]) is int and 1 <= r["top_k"] <= 50 and r["min_trust"] in TRUST if kind == "evidence_register": return set(r) == {"payload_type", "subject", "body"} and type(r["body"]) is dict and bool(r["body"]) and \ all(type(r[k]) is str and 0 < len(r[k]) <= 256 for k in ("payload_type", "subject")) return False def _condition_holds(op, arg, kind, r, at_ms) -> bool: if op == "argv0_in": a0 = r["argv"][0] return "/" not in a0 and a0 in arg if op == "max_argc": return len(r["argv"]) <= arg if op == "cwd_under": return any(_under(r["cwd"], x) for x in arg) if op == "max_timeout_s": return r["timeout_s"] <= arg if op == "namespace_in": return r["namespace"] in arg if op == "source_type_in": return r["source_type"] in arg if op == "min_trust": return TRUST[r["min_trust"]] >= TRUST[arg] if op == "max_content_bytes": text = r["content"] if kind == "memory_write" else canon(r["body"]).decode() return len(text.encode()) <= arg if op == "max_top_k": return r["top_k"] <= arg if op == "payload_type_in": return r["payload_type"] in arg if op == "utc_hour_window": return arg[0] <= (at_ms // 3_600_000) % 24 < arg[1] return False def decision(rp) -> tuple: """Independent derivation of the runtime's decide(); check order follows the spec.""" b, at = rp["contract"], rp["decided_at_ms"] if rp["tenant"] != b["header"]["tenant"]: return "DENY", "TENANT_MISMATCH" if rp["state_before"] != "ACTIVE": return "DENY", "STATE_" + rp["state_before"] if at < b["validity"]["not_before_ms"]: return "DENY", "NOT_YET_VALID" if at >= b["validity"]["expires_at_ms"]: return "DENY", "EXPIRED" if rp["uses_before"] >= b["capability"]["max_uses"]: return "DENY", "USES_EXHAUSTED" snap = rp["snapshot"] if not snap.get("complete"): return "DENY", "AUTHORITY_UNKNOWN_AGENT" ag = snap["agents"] if not ag or ag[-1]["agent_id"] != b["subject"]["agent_id"]: return "DENY", "AUTHORITY_SUBJECT_MISMATCH" if [x["agent_id"] for x in ag] != b["authority"]["agent_chain"]: return "DENY", "AUTHORITY_CHAIN_MISMATCH" if any(x["status"] != "ACTIVE" for x in ag): return "DENY", "AUTHORITY_REVOKED" if ag[-1]["public_key_b64"] != b["subject"]["public_key_b64"]: return "DENY", "IDENTITY_SUBSTITUTION" if ag[-1]["runtime_digest"] != b["subject"]["runtime_digest"]: return "DENY", "MODEL_SUBSTITUTION" for x in ag: if "*" not in x["actions"] and b["capability"]["action"] not in x["actions"]: return "DENY", "AUTHORITY_AMPLIFICATION" if not any(_scope_has(b["capability"]["resource"], sc) for sc in x["scopes"]): return "DENY", "AUTHORITY_AMPLIFICATION" if (rp["runtime_digest"] or "") != b["subject"]["runtime_digest"]: return "DENY", "MODEL_SUBSTITUTION" if rp["environment_digest"] != b["environment"]["environment_digest"]: return "DENY", "ENVIRONMENT_DRIFT" if rp["policy_digest"] != b["policy"]["policy_digest"]: return "DENY", "POLICY_DRIFT" kind, r = b["action"]["kind"], rp["request"] if not _request_shape_ok(kind, r): return "DENY", "MALFORMED_REQUEST" rh = req_hash(r) if b["action"]["request_hash"] and b["action"]["request_hash"] != rh: return "DENY", "REQUEST_NOT_PINNED" inv = rp["invocation"] if type(inv) is not dict or sorted(inv) != ["nonce", "request_hash", "signature_b64", "ts_ms"]: return "DENY", "POP_MISSING" if inv["request_hash"] != rh: return "DENY", "POP_REQUEST_MISMATCH" if type(inv["ts_ms"]) is not int or abs(at - inv["ts_ms"]) > 60_000: return "DENY", "POP_STALE" if type(inv["nonce"]) is not str or not re.fullmatch(r"[0-9a-f]{32}", inv["nonce"]): return "DENY", "POP_MALFORMED" msg = b"CAIN/contract/v1/invoke" + US + canon({"fp": fp_of(b), "nonce": inv["nonce"], "request_hash": rh, "ts_ms": inv["ts_ms"]}) if not sig_ok(b["subject"]["public_key_b64"], msg, inv["signature_b64"]): return "DENY", "POP_INVALID" if rp.get("nonce_used"): return "DENY", "POP_REPLAY" res = b["capability"]["resource"] inside = {"exec": lambda: _under(r["cwd"], res), "memory_write": lambda: res == "memvault/ns/" + r["namespace"], "memory_read": lambda: res == "memvault/ns/" + r["namespace"], "evidence_register": lambda: res == "scitt/" + r["payload_type"]}[kind]() if not inside: return "DENY", "RESOURCE_OUTSIDE_CONTRACT" conds = sorted(b["conditions"], key=lambda c: c["op"]) for c in conds: arg = c["arg"] if c["op"] == "cwd_under": arg = [os.path.normpath(x) for x in arg] if not _condition_holds(c["op"], arg, kind, r, at): return "DENY", "CONDITION_" + c["op"].upper() return "ALLOW", "OK" # -------------------------------------------------------------------------------------------- the verifier def verify(export: dict, issuer_key_b64: str = "", tenant: str = "", at_ms: int = -1) -> dict: checks, problems = {}, [] def mark(name, ok, why=""): checks[name] = bool(ok) if not ok: problems.append(f"{name}: {why}" if why else name) body = export.get("contract") try: raw = canon(body) mark("canonical_encoding", json.loads(raw) == body) fp = fp_of(body) mark("fingerprint", fp == export.get("fingerprint"), "recomputed fingerprint differs") except (Bad, KeyError, TypeError) as exc: mark("canonical_encoding", False, str(exc)) return {"ok": False, "checks": checks, "problems": problems} st = structural(body) mark("structure_and_risk", not st, "; ".join(st)) key = issuer_key_b64 or export.get("issuer_public_key_b64", "") checks["issuer_key_pinned"] = bool(issuer_key_b64) if issuer_key_b64 and export.get("issuer_public_key_b64") not in ("", None, issuer_key_b64): mark("issuer_key_matches_pin", False, "export names a different issuer key than the pinned one") mark("issuer_signature", sig_ok(key, b"CAIN/contract/v1/issuer" + US + fp.encode() + US + str(export.get("authority_digest", "")).encode(), export.get("issuer_sig", "")), "issuer signature does not verify") subj_key = body["subject"]["public_key_b64"] if export.get("consent_mode") == "carried": pred = export.get("predecessor") or {} pb = pred.get("body") ok = False why = "predecessor missing" if pb: pfp = fp_of(pb) only_annotations = all(pb[s] == body[s] for s in SECTION_NAMES if s not in ("header", "validity", "annotations")) hdr_ok = (pb["header"]["lineage_id"] == body["header"]["lineage_id"] and pb["header"]["tenant"] == body["header"]["tenant"] and pb["header"]["schema"] == body["header"]["schema"] and body["header"]["version"] == pb["header"]["version"] + 1 and body["header"]["supersedes"] == pfp) val_ok = all(pb["validity"][k] == body["validity"][k] for k in ("not_before_ms", "expires_at_ms")) sig = sig_ok(subj_key, b"CAIN/contract/v1/subject" + US + pfp.encode(), export.get("subject_sig", "")) ok = only_annotations and hdr_ok and val_ok and sig and export.get("consent_from") == pfp why = "carried consent is valid only for annotation-only amendments with the predecessor's signature" mark("subject_consent", ok, why) else: mark("subject_consent", sig_ok(subj_key, b"CAIN/contract/v1/subject" + US + fp.encode(), export.get("subject_sig", "")), "subject consent signature does not verify") if tenant: mark("tenant", body["header"]["tenant"] == tenant, "contract tenant differs from expected") if at_ms >= 0: v = body["validity"] mark("validity_at_time", v["not_before_ms"] <= at_ms < v["expires_at_ms"], "outside validity window") rv = export.get("revocation") if rv is not None: unsigned = {k: x for k, x in rv.items() if k != "signature_b64"} good = sig_ok(key, b"CAIN/contract/v1/revocation" + US + canon(unsigned), rv.get("signature_b64", "")) and \ rv.get("fingerprint") == fp mark("revocation_statement", good, "revocation statement invalid") checks["revoked"] = True if export.get("state") != "REVOKED": mark("revocation_state_consistent", False, "signed revocation exists but state is not REVOKED") replays, allowed_decisions = [], set() for i, item in enumerate(export.get("receipts", [])): rc, rp = item["receipt"], item["replay"] unsigned = {k: x for k, x in rc.items() if k not in ("receipt_hash", "signature_b64")} try: dig = h(canon(unsigned)) except Bad as exc: mark(f"receipt[{i}].hash", False, str(exc)) continue mark(f"receipt[{i}].hash", dig == rc.get("receipt_hash"), "receipt hash mismatch") mark(f"receipt[{i}].signature", sig_ok(key, b"CAIN/contract/v1/receipt" + US + dig.encode(), rc.get("signature_b64", "")), "receipt signature") mark(f"receipt[{i}].binding", rc.get("contract_fingerprint") == fp and rc.get("tenant") == body["header"]["tenant"] and rc.get("contract_version") == body["header"]["version"], "receipt bound to a different contract/tenant/version") if rc.get("kind") == "outcome": # an outcome must follow an ALLOW decision of this contract, once link = rc.get("decision_receipt_hash") mark(f"receipt[{i}].outcome_link", link in allowed_decisions, "outcome without a preceding ALLOW decision") allowed_decisions.discard(link) continue if rc.get("kind") != "decision" or rp is None: mark(f"receipt[{i}].kind", False, "unknown receipt kind or missing replay record") continue if rc.get("decision") == "ALLOW": allowed_decisions.add(rc.get("receipt_hash")) bound = (fp_of(rp["contract"]) == rc["contract_fingerprint"] and grant_of(rp["snapshot"]) == rc["authority_snapshot_digest"] and rp["decided_at_ms"] == rc["decided_at_ms"] and bool(rp.get("nonce_used")) == bool(rc.get("nonce_used"))) got = decision(rp) same = list(got) == [rc["decision"], rc["reason"]] mark(f"receipt[{i}].replay", bound and same, f"replay gives {list(got)}, receipt says {[rc['decision'], rc['reason']]}, inputs_bound={bound}") replays.append({"recorded": [rc["decision"], rc["reason"]], "replayed": list(got), "bound": bound}) return {"ok": not problems, "checks": checks, "problems": problems, "replays": replays, "key_status": "PINNED" if issuer_key_b64 else "SELF_ASSERTED_KEY", "fingerprint": fp} def main(argv=None) -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("export") ap.add_argument("--issuer-key", default="") ap.add_argument("--tenant", default="") ap.add_argument("--at-ms", type=int, default=-1) a = ap.parse_args(argv) with open(a.export, "rb") as f: exp = json.loads(f.read()) res = verify(exp, a.issuer_key, a.tenant, a.at_ms) print(json.dumps(res, indent=1, sort_keys=True)) return 0 if res["ok"] else 1 if __name__ == "__main__": sys.exit(main())