Human-originated authority and NIST cybersecurity guidance · Chapter 19 of 27

Appendix E. Executable reference implementations and complete test source

On this page
  1. E.1. authority_model.py
  2. E.2. privacy_model.py
  3. E.3. state_model.py
  4. E.4. import_oscal_catalog.py
  5. E.5. check_requirement_closure.py
  6. E.6. run_public_example.py
  7. E.7. test_authority_model.py
  8. E.8. test_catalog_import.py
  9. E.9. test_closure_checker.py
  10. E.10. regenerate_public_example.py

These listings are the exact review-source files supplied in reference_code/. The authority model uses ECDSA P-256 through the installed cryptography package for synthetic signed records, a trusted test registry, and a local SQLite transaction for modeled effects. It does not implement the private-reference enrollment engine, hardware key custody, real attestation, live TLS, distributed consensus, or an external exactly-once transaction protocol. Those contracts are specified in A and D. [D2; R4]

The model's role is inspectability: it makes signature checks, fixed policy predicates, ancestry links, expiry, epoch, action binding, and atomic local state transitions executable. register_fixture explicitly creates synthetic appraisal inputs; it is never an acceptable production admission endpoint. A production adapter derives the actual request, peer, cost, channel, and runtime evidence independently of an untrusted application. The stored geometry digest is an input binding, not an implementation of the geometric construction.

The original record-completeness checker and its synthetic tests are retained from the preceding package. Its result concerns record structure and declared state; it does not authenticate evidence or decide NIST compliance. The new catalog importer preserves source structure from an independently supplied local file. The privacy model demonstrates a sufficient small masking construction and exposed-interpretation contrasts; the state explorer checks the stated finite domain.

E.1. authority_model.py

SHA-256: 812757c60fadf86ae8ab29dd93e59866a521f5664a948062808800a0f5b2c685.

"""HTTP6 review model, not the production Rosario-Wang engine or a TEE.

Executable scope: signed delegation, restrictive policy intersection, context-bound
requests, and a local SQLite one-use/effect ledger with central ancestry budgets.
Trusted inputs: admission-authority key, registry bindings, current time/epoch,
and independently authenticated actual peer/channel/request. Tests supply fixtures.
TEST-CANON-1 accepts printable ASCII JSON and safe integers; it is not full JCS.
"""
from __future__ import annotations
import copy
import hashlib
import json
import secrets
import sqlite3
from pathlib import Path
from typing import Any
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec

class Rejected(ValueError):
    """The review gate rejects the requested transition."""

def canonical(value: Any) -> bytes:
    def check(x: Any) -> None:
        if x is None or type(x) is bool:
            return
        if type(x) is int and abs(x) <= 9007199254740991:
            return
        if isinstance(x, str) and all(32 <= ord(c) <= 126 for c in x):
            return
        if isinstance(x, list):
            for item in x:
                check(item)
            return
        if isinstance(x, dict) and all(isinstance(k, str) for k in x):
            for k, v in x.items():
                check(k)
                check(v)
            return
        raise Rejected("TEST-CANON-1 type or range")
    check(value)
    return json.dumps(value, sort_keys=True, ensure_ascii=True,
                      separators=(",", ":"), allow_nan=False).encode("ascii")

def digest(value: Any) -> str:
    return hashlib.sha256(canonical(value)).hexdigest()

def new_key():
    return ec.generate_private_key(ec.SECP256R1())

def public_hex(key) -> str:
    return key.public_key().public_bytes(
        serialization.Encoding.X962,
        serialization.PublicFormat.UncompressedPoint).hex()

def signed(key, domain: str, body: dict) -> dict:
    frozen = copy.deepcopy(body)
    sig = key.sign(canonical([domain, frozen]), ec.ECDSA(hashes.SHA256()))
    return {"body": frozen, "signature": sig.hex()}

def verify(public: str, domain: str, envelope: dict) -> dict:
    try:
        if set(envelope) != {"body", "signature"}:
            raise Rejected("envelope shape")
        key = ec.EllipticCurvePublicKey.from_encoded_point(
            ec.SECP256R1(), bytes.fromhex(public))
        key.verify(bytes.fromhex(envelope["signature"]),
                   canonical([domain, envelope["body"]]),
                   ec.ECDSA(hashes.SHA256()))
        return envelope["body"]
    except (KeyError, TypeError, ValueError, InvalidSignature) as exc:
        raise Rejected("signature or encoding") from exc

def validate_policy(p: dict) -> None:
    required = {"version", "tenant", "allow", "deny", "role_snapshot",
                "can_mint", "max_depth", "templates", "budget"}
    if not isinstance(p, dict) or set(p) != required:
        raise Rejected("policy fields")
    if p["version"] != "http6.review-policy.v1":
        raise Rejected("policy version")
    if type(p["can_mint"]) is not bool:
        raise Rejected("mint flag")
    if not isinstance(p["tenant"], str) or not p["tenant"]:
        raise Rejected("tenant")
    if len(p["role_snapshot"]) != 64:
        raise Rejected("role snapshot")
    if not isinstance(p["templates"], list) or not all(
            isinstance(x, str) and x for x in p["templates"]):
        raise Rejected("templates")
    for name in ("max_depth", "budget"):
        if type(p[name]) is not int or p[name] < 0:
            raise Rejected("nonnegative integer required")
    for effect in ("allow", "deny"):
        if not isinstance(p[effect], list):
            raise Rejected("rules")
        for rule in p[effect]:
            if set(rule) != {"operation", "destination", "resource", "data_class"}:
                raise Rejected("complete request rule required")
            if not all(isinstance(x, str) and x for x in rule.values()):
                raise Rejected("rule values")
            if effect == "allow" and "*" in rule.values():
                raise Rejected("review profile uses exact allow matches")
    canonical(p)

def valid_request(q: dict) -> None:
    fields = {"tenant", "operation", "destination", "resource",
              "data_class", "payload_digest", "cost"}
    if not isinstance(q, dict) or set(q) != fields:
        raise Rejected("request fields")
    if type(q["cost"]) is not int or q["cost"] < 0:
        raise Rejected("request cost")
    for name in fields - {"cost"}:
        if not isinstance(q[name], str) or not q[name]:
            raise Rejected("request attribute")
    canonical(q)

def policy_allows(p: dict, q: dict) -> bool:
    try:
        validate_policy(p)
        valid_request(q)
        def match(rule):
            return all(v == "*" or q[k] == v for k, v in rule.items())
        return (p["tenant"] == q["tenant"]
                and any(match(r) for r in p["allow"])
                and not any(match(r) for r in p["deny"]))
    except (KeyError, TypeError, ValueError):
        return False

def instance_id(public: str, nonce: str, parent: str | None, epoch: int) -> str:
    return digest(["instance-v1", public, nonce, parent, epoch])

def make_grant(signer, child_key, policy: dict, parent: dict | None,
               profile: str, epoch: int, now: int, expires: int,
               measurement: str) -> dict:
    """Record constructor, NOT a production admission API.

    A root caller is the separately authenticated human-admission authority.
    A child caller must first apply mint_child's authorization checks.
    """
    validate_policy(policy)
    if type(now) is not int or type(expires) is not int or expires <= now:
        raise Rejected("lifetime")
    parent_hash = digest(parent["body"]) if parent else None
    nonce, public = secrets.token_hex(16), public_hex(child_key)
    iid = instance_id(public, nonce, parent_hash, epoch)
    root = parent["body"]["root"] if parent else iid
    body = {"version": "http6.review-grant.v1", "instance": iid,
            "public_key": public, "birth_nonce": nonce, "parent": parent_hash,
            "root": root, "epoch": epoch, "profile": profile,
            "issued": now, "expires": expires, "measurement": measurement,
            "policy": copy.deepcopy(policy), "policy_digest": digest(policy)}
    return signed(signer, "grant-v1", body)

def register_fixture(registry: dict, grant: dict) -> None:
    """TEST HARNESS ONLY: stands for successful external runtime appraisal."""
    b = grant["body"]
    registry[b["instance"]] = {"public_key": b["public_key"],
                              "measurement": b["measurement"],
                              "active": True}

def verify_chain(chain: list[dict], anchor: str, registry: dict,
                 current_epoch: int, now: int, revoked: set[str]) -> list[dict]:
    if not chain or len(chain) > 32:
        raise Rejected("chain length")
    bodies, seen = [], set()
    for pos, envelope in enumerate(chain):
        pub = anchor if pos == 0 else bodies[-1]["public_key"]
        b = verify(pub, "grant-v1", envelope)
        fields = {"version", "instance", "public_key", "birth_nonce", "parent",
                  "root", "epoch", "profile", "issued", "expires",
                  "measurement", "policy", "policy_digest"}
        if set(b) != fields or b["version"] != "http6.review-grant.v1":
            raise Rejected("grant fields")
        validate_policy(b["policy"])
        if b["policy_digest"] != digest(b["policy"]):
            raise Rejected("policy commitment")
        if b["epoch"] != current_epoch or not b["issued"] <= now < b["expires"]:
            raise Rejected("epoch or lifetime")
        expected_parent = digest(bodies[-1]) if bodies else None
        if b["parent"] != expected_parent:
            raise Rejected("parent link")
        iid = instance_id(b["public_key"], b["birth_nonce"], b["parent"], b["epoch"])
        if b["instance"] != iid or iid in seen or iid in revoked:
            raise Rejected("instance, cycle or revocation")
        if b["root"] != (bodies[0]["root"] if bodies else iid):
            raise Rejected("root identity")
        reg = registry.get(iid, {})
        if (reg.get("active") is not True or reg.get("public_key") != b["public_key"]
                or reg.get("measurement") != b["measurement"]):
            raise Rejected("registered runtime binding")
        if bodies:
            p = bodies[-1]
            if not p["policy"]["can_mint"]:
                raise Rejected("parent may not mint")
            if b["profile"] != p["profile"] or b["expires"] > p["expires"]:
                raise Rejected("profile or lifetime expansion")
            if b["measurement"] not in p["policy"]["templates"]:
                raise Rejected("template")
        for depth, ancestor in enumerate(bodies):
            if pos - depth > ancestor["policy"]["max_depth"]:
                raise Rejected("depth ceiling")
        bodies.append(b)
        seen.add(iid)
    return bodies

def mint_child(chain, anchor, registry, epoch, now, revoked,
               signer, child_key, policy, expires, measurement):
    bodies = verify_chain(chain, anchor, registry, epoch, now, revoked)
    p = bodies[-1]
    if public_hex(signer) != p["public_key"]:
        raise Rejected("wrong issuer key")
    grant = make_grant(signer, child_key, policy, chain[-1], p["profile"],
                       epoch, now, expires, measurement)
    # Staging a binding here is test-only; production uses fresh appraised evidence.
    staged = copy.deepcopy(registry)
    register_fixture(staged, grant)
    verify_chain(chain + [grant], anchor, staged, epoch, now, revoked)
    return grant

class Ledger:
    """Local transactional model. Effects are rows in this same database.

    Every independent connection uses BEGIN IMMEDIATE. No claim of distributed
    consensus or exactly-once external side effects is made by this component.
    """
    def __init__(self, path: str | Path):
        self.path = str(path)
        with self.connect() as db:
            db.executescript('''
              CREATE TABLE IF NOT EXISTS budgets(
                id TEXT PRIMARY KEY, ceiling INTEGER NOT NULL, spent INTEGER NOT NULL);
              CREATE TABLE IF NOT EXISTS challenges(
                token TEXT PRIMARY KEY, binding TEXT NOT NULL, consumed INTEGER NOT NULL);
              CREATE TABLE IF NOT EXISTS effects(
                token TEXT PRIMARY KEY, request_digest TEXT NOT NULL);
            ''')
    def connect(self):
        db = sqlite3.connect(self.path, timeout=20, isolation_level=None)
        db.execute("PRAGMA synchronous=FULL")
        return db
    def add_budget(self, identifier: str, ceiling: int):
        if type(ceiling) is not int or ceiling < 0:
            raise Rejected("budget")
        with self.connect() as db:
            db.execute("INSERT INTO budgets VALUES(?,?,0)", (identifier, ceiling))
    def issue(self, token: str, binding: str):
        with self.connect() as db:
            db.execute("INSERT INTO challenges VALUES(?,?,0)", (token, binding))
    def consume(self, token: str, binding: str, ancestors: list[str],
                cost: int, request_digest: str) -> None:
        if type(cost) is not int or cost < 0 or not ancestors:
            raise Rejected("cost or ancestry")
        if len(ancestors) != len(set(ancestors)):
            raise Rejected("duplicate ancestry")
        db = self.connect()
        try:
            db.execute("BEGIN IMMEDIATE")
            cur = db.execute(
                "UPDATE challenges SET consumed=1 WHERE token=? AND binding=? AND consumed=0",
                (token, binding))
            if cur.rowcount != 1:
                raise Rejected("unissued, altered or consumed challenge")
            for aid in ancestors:
                cur = db.execute(
                    "UPDATE budgets SET spent=spent+? WHERE id=? AND spent+?<=ceiling",
                    (cost, aid, cost))
                if cur.rowcount != 1:
                    raise Rejected("ancestral budget")
            db.execute("INSERT INTO effects VALUES(?,?)", (token, request_digest))
            db.execute("COMMIT")
        except Exception:
            if db.in_transaction:
                db.execute("ROLLBACK")
            raise
        finally:
            db.close()
    def effect_count(self) -> int:
        with self.connect() as db:
            return db.execute("SELECT COUNT(*) FROM effects").fetchone()[0]

def action_body(leaf: dict, q: dict, channel: str, sequence: int,
                geometry: str, nonce: str, expires: int) -> dict:
    valid_request(q)
    b = leaf["body"]
    return {"instance": b["instance"], "epoch": b["epoch"],
            "profile": b["profile"], "policy_digest": b["policy_digest"],
            "lineage_digest": digest(b), "channel": channel,
            "sequence": sequence, "geometry_digest": geometry,
            "nonce": nonce, "expires": expires, "direction": "request",
            "request": copy.deepcopy(q)}

def authorize(chain, proof, anchor, registry, epoch, now, revoked,
              actual_request, actual_peer, channel, expected_sequence,
              expected_geometry, ledger: Ledger) -> str:
    bodies = verify_chain(chain, anchor, registry, epoch, now, revoked)
    leaf = bodies[-1]
    body = verify(leaf["public_key"], "action-v1", proof)
    expected = action_body(chain[-1], actual_request, channel,
                           expected_sequence, expected_geometry,
                           body["nonce"], body["expires"])
    if body != expected or not now < body["expires"] <= leaf["expires"]:
        raise Rejected("action context")
    if actual_peer != actual_request["destination"]:
        raise Rejected("actual peer")
    if not all(policy_allows(b["policy"], actual_request) for b in bodies):
        raise Rejected("inherited policy")
    # One server-issued nonce for a specific stream position is modeled by token.
    token = digest([epoch, leaf["instance"], channel, expected_sequence])
    ledger.consume(token, digest(body), [b["instance"] for b in bodies],
                   actual_request["cost"], digest(actual_request))
    return "permitted_once_in_local_model"

E.2. privacy_model.py

SHA-256: dd741894cf64bd37b86c5162994b06810c034ad068779556aed4d4003db2488a.

"""Exhaustive finite illustrations, not a test of a production RW binary.

The fixed circuit C (known to the observer) maps four secrets to two region
indices. Fresh hidden masks make their public distributions identical. Revealing
those masks with the binary, or publishing the plain indices, distinguishes them.
"""
from collections import Counter
from itertools import product
from fractions import Fraction
import json

def region(secret: int, ceremony: int) -> int:
    return (secret >> (ceremony % 2)) & 1

def distribution(secret: int, rounds: int, reveal_masks: bool = False):
    counts = Counter()
    for masks in product(range(2), repeat=rounds):
        witness = tuple(region(secret, i) ^ masks[i] for i in range(rounds))
        observed = (witness, masks) if reveal_masks else witness
        counts[observed] += 1
    return {k: Fraction(v, 2 ** rounds) for k, v in counts.items()}

def check() -> dict:
    results = {}
    for n in range(1, 7):
        ds = [distribution(s, n) for s in range(4)]
        results[f"fresh_private_mask_rounds_{n}"] = all(d == ds[0] for d in ds)
    public = [distribution(s, 2, True) for s in range(4)]
    results["disclosed_mask_view_distinguishes_secrets"] = len({
        repr(sorted(d.items())) for d in public}) == 4
    paths = [tuple(region(s, i) for i in range(2)) for s in range(4)]
    results["public_deterministic_partition_path_identifies_secret"] = len(set(paths)) == 4
    # A reused mask reveals a relation between two hidden membership indices.
    results["reused_mask_cancels_in_xor"] = all(
        ((a ^ z) ^ (b ^ z)) == (a ^ b)
        for a, b, z in product(range(2), repeat=3))
    return results

if __name__ == "__main__":
    result = check()
    print(json.dumps(result, indent=2))
    raise SystemExit(0 if all(result.values()) else 1)

E.3. state_model.py

SHA-256: 1a0f11871eb8c5535fed727cdb724b8a298bcc2991700833f08473efa6e27971.

"""Finite abstract transition exploration; cryptographic interfaces are assumed.

State: immutable permission masks for at most three instances, parent identifiers,
root liveness, consumed challenge bits and total consumption. No real RW engine.
"""
from collections import deque
import json

def explore():
    initial = ((3,), (-1,), True, 0, 0)
    todo, seen, transitions = deque([initial]), {initial}, 0
    while todo:
        state = todo.popleft()
        masks, parents, live, used, spent = state
        assert spent <= 2 and spent == used.bit_count()
        assert masks[0] == 3
        assert all((m & ~3) == 0 for m in masks)
        assert all(masks[i] & ~masks[parents[i]] == 0 for i in range(1,len(masks)))
        next_states = []
        if live:
            next_states.append((masks, parents, False, used, spent))
            if len(masks) < 3:
                for p in range(len(masks)):
                    for requested in range(4):
                        child = masks[p] & requested
                        next_states.append((masks+(child,),parents+(p,),live,used,spent))
            for p, permissions in enumerate(masks):
                for op in (1,2):
                    for nonce in (0,1):
                        if permissions & op and not (used & (1 << nonce)):
                            next_states.append((masks,parents,live,used|(1<<nonce),spent+1))
        # Fenced states have no effect-producing transition.
        for nxt in next_states:
            transitions += 1
            if nxt not in seen:
                seen.add(nxt);todo.append(nxt)
    return {'model':'finite-attenuation-and-consumption-v1','states':len(seen),
            'transitions':transitions,'invariants':'all checked in this finite model',
            'bounds':{'max_instances':3,'permission_bits':2,'challenge_positions':2},
            'production_assessment':False}
if __name__=='__main__':
    print(json.dumps(explore(),indent=2))

E.4. import_oscal_catalog.py

SHA-256: 65019610eb8aff835975bb8ea64b918526ab0d2d570087a01ad36c9ec770d279.

#!/usr/bin/env python3
"""Extract source-addressable OSCAL catalog entries from a local pinned file.

This is an inventory aid, not an automatic control selection or assessment.
Original statements/parameters are retained. A catalog without assessment
objectives still needs its separate assessment-procedure source and approval.
"""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path

MAX_BYTES = 100_000_000

def extract(path: Path, expected_sha256: str, expected_version: str) -> dict:
    raw = path.read_bytes()
    if len(raw) > MAX_BYTES:
        raise ValueError('catalog exceeds configured size limit')
    observed = hashlib.sha256(raw).hexdigest()
    if observed != expected_sha256.lower():
        raise ValueError('catalog digest mismatch')
    document = json.loads(raw)
    catalog = document['catalog']
    metadata = catalog['metadata']
    if metadata['version'] != expected_version:
        raise ValueError('catalog edition mismatch')
    entries, seen = [], set()
    def controls(items, groups):
        for control in items:
            cid = control['id']
            if cid in seen:
                raise ValueError('duplicate control identifier: ' + cid)
            seen.add(cid)
            props = control.get('props', [])
            states = [p['value'] for p in props if p.get('name') == 'status']
            entries.append({
                'source_control_id': cid, 'title': control.get('title'),
                'group_path': list(groups), 'source_status': states or ['unspecified'],
                'parameters': control.get('params', []),
                'parts': control.get('parts', []), 'properties': props,
                'links': control.get('links', []),
                'applicability': 'pending_approved_selection',
                'assessment_objective_source': None,
                'implementation_assignment': None,
                'observed_result': None})
            controls(control.get('controls', []), groups)
    def groups(items, ancestry):
        for group in items:
            here = ancestry + [group['id']]
            controls(group.get('controls', []), here)
            groups(group.get('groups', []), here)
    controls(catalog.get('controls', []), [])
    groups(catalog.get('groups', []), [])
    return {'record_kind': 'unselected_source_catalog_extract',
            'source_file': path.name, 'source_digest': observed,
            'source_version': metadata['version'],
            'source_title': metadata.get('title'),
            'oscal_version': metadata.get('oscal-version'),
            'approved_by': None, 'scope_id': None,
            'source_control_count': len(entries), 'entries': entries,
            'next_steps': ['approve selection and boundary',
                           'resolve parameters',
                           'import applicable assessment objectives',
                           'assign implementations and actual evidence']}

def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('catalog', type=Path)
    p.add_argument('--sha256', required=True)
    p.add_argument('--version', required=True)
    p.add_argument('--output', required=True, type=Path)
    args = p.parse_args()
    try:
        result = extract(args.catalog, args.sha256, args.version)
        args.output.write_text(json.dumps(result, indent=2)+'\n',encoding='utf-8')
    except (ValueError, KeyError, TypeError, OSError) as exc:
        p.exit(2, 'Import rejected: '+str(exc)+'\n')
if __name__=='__main__':
    main()

E.5. check_requirement_closure.py

SHA-256: 0da8cae70fec9e1cce959783566f00d279dc8a20f7fde69420af70e834451b4f.

#!/usr/bin/env python3
"""Check completeness of an externally selected requirement inventory and evidence register.

This checks record structure and declared state. It does not authenticate artifacts,
verify NIST applicability, establish evidence truth, or perform a compliance assessment.
The caller must provide an independently approved, complete selected inventory.

Usage:
  python check_requirement_closure.py inventory.json register.json --as-of 2026-11-09T00:00:00Z
Exit codes: 0 structurally ready; 1 not ready; 2 invalid input.
"""
from __future__ import annotations
import argparse
import datetime as dt
import json
import re
import sys
from pathlib import Path
from typing import Any

HEX64 = re.compile(r"^[0-9a-fA-F]{64}$")
METHODS = {"examine", "interview", "test"}
UNRESOLVED = {"", "tbd", "pending", "unresolved", "unknown", "not_assessed"}

def populated(value: Any) -> bool:
    if value is None:
        return False
    if isinstance(value, str):
        return value.strip().lower() not in UNRESOLVED
    if isinstance(value, (list, dict)):
        return bool(value) and all(populated(v) for v in (value.values() if isinstance(value, dict) else value))
    return True  # False and zero may be explicit valid parameter values.

def time_value(value: Any) -> dt.datetime:
    if not isinstance(value, str):
        raise ValueError("timestamp must be an ISO-8601 string")
    result = dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
    if result.tzinfo is None:
        raise ValueError("timestamp must include timezone")
    return result.astimezone(dt.timezone.utc)

def unique_named(items: Any, key: str, path: str, errors: list[str]) -> dict[str, dict[str, Any]]:
    if not isinstance(items, list):
        errors.append(f"{path}: expected list")
        return {}
    indexed = {}
    for i, item in enumerate(items):
        if not isinstance(item, dict) or not isinstance(item.get(key), str) or not item[key].strip():
            errors.append(f"{path}[{i}]: missing string {key}")
            continue
        identifier = item[key]
        if identifier in indexed:
            errors.append(f"{path}: duplicate {identifier}")
        indexed[identifier] = item
    return indexed

def check(inventory: dict[str, Any], register: dict[str, Any], as_of: dt.datetime) -> dict[str, Any]:
    errors: list[str] = []
    if not isinstance(inventory, dict) or not isinstance(register, dict):
        raise ValueError("inventory and register must be JSON objects")
    if as_of.tzinfo is None:
        raise ValueError("as_of requires a timezone")
    for field in ("scope_id", "source_version", "approved_by"):
        if not populated(inventory.get(field)):
            errors.append(f"inventory.{field}: approved value required")
    digest = inventory.get("source_digest", "")
    if not isinstance(digest, str) or not HEX64.fullmatch(digest):
        errors.append("inventory.source_digest: 64-hex source digest required")
    if register.get("scope_id") != inventory.get("scope_id"):
        errors.append("register.scope_id: inventory mismatch")
    if register.get("inventory_digest") != digest:
        errors.append("register.inventory_digest: inventory mismatch")
    reqs = unique_named(inventory.get("requirements"), "id", "inventory.requirements", errors)
    records = unique_named(register.get("records"), "requirement_id", "register.records", errors)
    if not reqs:
        errors.append("inventory.requirements: nonempty approved selection required")
    missing = sorted(set(reqs) - set(records))
    extra = sorted(set(records) - set(reqs))
    if missing:
        errors.append("register: missing requirements " + ", ".join(missing))
    if extra:
        errors.append("register: unselected requirements " + ", ".join(extra))
    own_ok: dict[str, bool] = {}
    dependencies: dict[str, list[str]] = {}
    for rid, req in reqs.items():
        if rid not in records:
            own_ok[rid] = False
            dependencies[rid] = []
            continue
        rec = records[rid]
        before = len(errors)
        if rec.get("scope_id") != inventory.get("scope_id"):
            errors.append(f"{rid}: wrong evidence boundary")
        for field in ("implementation_owner", "implementation_ref"):
            if not populated(rec.get(field)):
                errors.append(f"{rid}.{field}: required")
        if rec.get("assessment_status") != "satisfied":
            errors.append(f"{rid}: assessment status must be satisfied; risk acceptance alone is not satisfaction")
        parameters = rec.get("parameters", {})
        if not isinstance(parameters, dict):
            errors.append(f"{rid}.parameters: expected object")
            parameters = {}
        required_params = req.get("parameters", [])
        if not isinstance(required_params, list) or not all(isinstance(x,str) for x in required_params):
            errors.append(f"{rid}: parameter inventory must be a string list")
            required_params = []
        for name in required_params:
            if name not in parameters or not populated(parameters[name]):
                errors.append(f"{rid}.parameters.{name}: unresolved")
        evidence = unique_named(rec.get("evidence", []), "id", f"{rid}.evidence", errors)
        if not evidence:
            errors.append(f"{rid}: evidence required")
        for eid, ev in evidence.items():
            if not isinstance(ev.get("digest"), str) or not HEX64.fullmatch(ev["digest"]):
                errors.append(f"{rid}.{eid}: artifact digest required")
            if ev.get("scope_id") != inventory.get("scope_id"):
                errors.append(f"{rid}.{eid}: evidence scope mismatch")
            if ev.get("implementation_ref") != rec.get("implementation_ref"):
                errors.append(f"{rid}.{eid}: evidence implementation mismatch")
            if not populated(ev.get("collector")):
                errors.append(f"{rid}.{eid}: collector required")
            try:
                collected = time_value(ev.get("collected_at"))
                valid_until = time_value(ev.get("valid_until"))
                if collected > as_of or valid_until <= as_of or valid_until <= collected:
                    errors.append(f"{rid}.{eid}: stale, future, or invalid evidence interval")
            except (ValueError, TypeError) as exc:
                errors.append(f"{rid}.{eid}: invalid evidence time ({exc})")
        objs = unique_named(rec.get("objectives", []), "id", f"{rid}.objectives", errors)
        expected_obj = req.get("objectives", [])
        if not isinstance(expected_obj,list) or not expected_obj or not all(isinstance(x,str) for x in expected_obj):
            errors.append(f"{rid}: nonempty objective inventory required")
            expected_obj = []
        if set(objs) != set(expected_obj):
            errors.append(f"{rid}: objective set mismatch")
        for oid, obj in objs.items():
            if obj.get("determination") != "satisfied":
                errors.append(f"{rid}.{oid}: objective not satisfied")
            if not populated(obj.get("reviewer")) or not populated(obj.get("observed")):
                errors.append(f"{rid}.{oid}: actual observation and reviewer required")
            methods = obj.get("methods", [])
            if not isinstance(methods, list) or not methods or not all(isinstance(m,str) and m in METHODS for m in methods):
                errors.append(f"{rid}.{oid}: valid justified assessment method required")
            refs = obj.get("evidence_ids", [])
            if not isinstance(refs,list) or not refs or not all(isinstance(x,str) and x in evidence for x in refs):
                errors.append(f"{rid}.{oid}: current evidence reference required")
        deps = rec.get("dependencies", [])
        if not isinstance(deps,list) or not all(isinstance(x,str) for x in deps):
            errors.append(f"{rid}.dependencies: expected requirement identifier list")
            deps = []
        dependencies[rid] = deps
        for dep in deps:
            if dep not in reqs:
                errors.append(f"{rid}: unresolved dependency {dep}")
        own_ok[rid] = len(errors) == before
    closed: dict[str,bool] = {}
    active: set[str] = set()
    def resolve(rid: str) -> bool:
        if rid in closed:
            return closed[rid]
        if rid in active:
            errors.append(f"{rid}: circular dependency needs explicit resolution")
            return False
        if rid not in own_ok:
            return False
        active.add(rid)
        # Evaluate all dependencies to expose all cycles even when local evidence fails.
        dep_ok = [resolve(dep) for dep in dependencies.get(rid, [])]
        result = own_ok[rid] and all(dep_ok)
        active.remove(rid)
        closed[rid] = result
        return result
    for rid in reqs:
        resolve(rid)
    ready = bool(reqs) and not errors and all(closed.values())
    return {
        "checker_scope": "record_completeness_only_not_a_NIST_or_product_assessment",
        "as_of": as_of.isoformat(),
        "structurally_ready": ready,
        "requirements_selected": len(reqs),
        "records_present_for_selection": len(set(reqs)&set(records)),
        "records_structurally_closed": sum(closed.values()),
        "missing_requirement_ids": missing,
        "errors": errors,
        "per_requirement_structural_closure": closed,
    }

def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("inventory", type=Path)
    parser.add_argument("register", type=Path)
    parser.add_argument("--as-of", required=True, help="Timezone-aware ISO-8601 assessment time")
    args=parser.parse_args()
    try:
        result=check(json.loads(args.inventory.read_text()),json.loads(args.register.read_text()),time_value(args.as_of))
    except (OSError, ValueError, TypeError, KeyError) as exc:
        print(json.dumps({"input_error": str(exc)},indent=2),file=sys.stderr)
        return 2
    print(json.dumps(result,indent=2))
    return 0 if result["structurally_ready"] else 1
if __name__ == "__main__":
    raise SystemExit(main())

E.6. run_public_example.py

SHA-256: 40186c6828a1b57d677772f139f767e34ff26bf667e73f7770f67ff8cf28704f.

"""Replay the public synthetic records; no private signing keys are needed."""
import json
from pathlib import Path
from tempfile import TemporaryDirectory
from authority_model import Ledger, digest, authorize, Rejected

ROOT = Path(__file__).resolve().parents[1]

def run():
    read = lambda name: json.loads((ROOT/'examples'/name).read_text())
    chain = [read('review_root_grant.json'),read('review_child_grant.json')]
    proof = read('review_action_proof.json')
    fixture = read('review_public_registry.json')
    request = read('review_request.json')
    with TemporaryDirectory() as directory:
        ledger = Ledger(Path(directory)/'review.sqlite')
        for g in chain:
            ledger.add_budget(g['body']['instance'],g['body']['policy']['budget'])
        b=proof['body']
        token=digest([b['epoch'],b['instance'],b['channel'],b['sequence']])
        ledger.issue(token,digest(b))
        args=dict(chain=chain,proof=proof,
                  anchor=fixture['admission_verifier_public_key'],
                  registry=fixture['registry'],epoch=fixture['epoch'],
                  now=fixture['now'],revoked=set(fixture['revoked']),
                  actual_request=request,actual_peer=request['destination'],
                  channel=b['channel'],expected_sequence=b['sequence'],
                  expected_geometry=b['geometry_digest'],ledger=ledger)
        first=authorize(**args)
        try:
            authorize(**args)
            replay='unexpected_accept'
        except Rejected:
            replay='rejected'
        return {'fixture_kind':fixture['fixture_kind'],'first':first,
                'replay':replay,'local_effect_count':ledger.effect_count()}

if __name__=='__main__':
    result=run(); print(json.dumps(result,indent=2))
    raise SystemExit(0 if result['replay']=='rejected'
                     and result['local_effect_count']==1 else 1)

E.7. test_authority_model.py

SHA-256: 6a451c3018dabff8d0288b4301dd50493f6f965720c6204012b219b4c3cde9f5.

"""Synthetic review-model tests. No production authentication or attestation."""
import copy
from concurrent.futures import ThreadPoolExecutor
import pytest
from authority_model import (
    Rejected, canonical, digest, new_key, public_hex, signed, make_grant,
    register_fixture, verify_chain, mint_child, policy_allows, Ledger,
    action_body, authorize, instance_id)
from privacy_model import check

RULE = {"operation": "report.publish", "destination": "reports.example",
        "resource": "daily", "data_class": "aggregate"}

def policy(mint=True, depth=4, budget=10):
    return {"version": "http6.review-policy.v1", "tenant": "acme",
            "allow": [dict(RULE)], "deny": [], "role_snapshot": "a" * 64,
            "can_mint": mint, "max_depth": depth,
            "templates": ["worker-v1"], "budget": budget}

def request():
    return {"tenant": "acme", **RULE, "payload_digest": "b" * 64, "cost": 1}

@pytest.fixture
def family(tmp_path):
    anchor, rootkey, childkey = new_key(), new_key(), new_key()
    root = make_grant(anchor, rootkey, policy(), None, "c"*64, 42, 10, 100, "root-v1")
    registry = {}
    register_fixture(registry, root)
    child = mint_child([root], public_hex(anchor), registry, 42, 20, set(),
                       rootkey, childkey, policy(False, 0), 90, "worker-v1")
    register_fixture(registry, child)
    ledger = Ledger(tmp_path / 'state.sqlite')
    for g in (root, child):
        ledger.add_budget(g['body']['instance'], g['body']['policy']['budget'])
    return dict(anchor=anchor, rootkey=rootkey, childkey=childkey,
                chain=[root, child], registry=registry, ledger=ledger)

def verify_family(f, **kwargs):
    args = dict(chain=f['chain'], anchor=public_hex(f['anchor']),
                registry=f['registry'], current_epoch=42, now=25, revoked=set())
    args.update(kwargs)
    return verify_chain(**args)

def prepare_action(f, q=None, seq=0):
    q = q or request()
    leaf = f['chain'][-1]
    b = action_body(leaf, q, 'channel-1', seq, 'd'*64, 'nonce-1', 70)
    proof = signed(f['childkey'], 'action-v1', b)
    token = digest([42, leaf['body']['instance'], 'channel-1', seq])
    f['ledger'].issue(token, digest(b))
    return proof

def execute(f, proof, **kwargs):
    args = dict(chain=f['chain'], proof=proof, anchor=public_hex(f['anchor']),
                registry=f['registry'], epoch=42, now=25, revoked=set(),
                actual_request=request(), actual_peer='reports.example',
                channel='channel-1', expected_sequence=0,
                expected_geometry='d'*64, ledger=f['ledger'])
    args.update(kwargs)
    return authorize(**args)

def test_chain_and_authorized_effect(family):
    assert len(verify_family(family)) == 2
    assert execute(family, prepare_action(family)).startswith('permitted_once')
    assert family['ledger'].effect_count() == 1

def test_replay(family):
    p = prepare_action(family)
    execute(family, p)
    with pytest.raises(Rejected): execute(family, p)
    assert family['ledger'].effect_count() == 1

@pytest.mark.parametrize('field,value', [
    ('operation','ledger.export'), ('destination','external.example'),
    ('resource','raw-ledger'), ('data_class','raw'), ('tenant','other')])
def test_complete_request_restrictions(field, value):
    q = request(); q[field] = value
    assert not policy_allows(policy(), q)

def test_deny_overrides():
    p = policy(); p['deny'] = [dict(RULE)]
    assert not policy_allows(p, request())

def test_missing_attribute():
    q=request(); del q['resource']
    assert not policy_allows(policy(), q)

def test_unknown_policy_field():
    p=policy(); p['ignore_ancestors']=True
    assert not policy_allows(p,request())

def test_child_local_expansion_cannot_override_root(family):
    f=family
    extra={**RULE,'operation':'ledger.export'}
    p=policy(False,0);p['allow'].append(extra)
    root=f['chain'][0]
    child=make_grant(f['rootkey'],f['childkey'],p,root,'c'*64,42,20,90,'worker-v1')
    register_fixture(f['registry'],child)
    f['chain']=[root,child]
    f['ledger'].add_budget(child['body']['instance'],10)
    q=request();q['operation']='ledger.export'
    proof=prepare_action(f,q)
    with pytest.raises(Rejected):execute(f,proof,actual_request=q)
    assert f['ledger'].effect_count()==0

@pytest.mark.parametrize('fault', [
    'policy', 'parent', 'profile', 'signature', 'root', 'expired',
    'revoked', 'epoch', 'registry', 'anchor', 'omitted_root'])
def test_reject_bad_chains(family, fault):
    f=family; chain=copy.deepcopy(f['chain']); kwargs={}
    if fault=='policy':chain[-1]['body']['policy']['allow']=[]
    elif fault=='parent':chain[-1]['body']['parent']='0'*64
    elif fault=='profile':
        b=chain[-1]['body'];b['profile']='e'*64
        chain[-1]=signed(f['rootkey'],'grant-v1',b)
    elif fault=='signature':chain[-1]['signature']='00'
    elif fault=='root':chain[-1]['body']['root']='0'*64
    elif fault=='expired':kwargs['now']=100
    elif fault=='revoked':kwargs['revoked']={chain[0]['body']['instance']}
    elif fault=='epoch':kwargs['current_epoch']=43
    elif fault=='registry':f['registry'][chain[-1]['body']['instance']]['active']=False
    elif fault=='anchor':kwargs['anchor']=public_hex(new_key())
    elif fault=='omitted_root':chain=chain[1:]
    with pytest.raises(Rejected):verify_family(f,chain=chain,**kwargs)

@pytest.mark.parametrize('fault', ['leaf_mints','wrong_template','long_life','wrong_signer'])
def test_reject_unauthorized_minting(family,fault):
    f=family;chain=f['chain'][:1]; signer=f['rootkey'];expiry=90;measurement='worker-v1'
    if fault=='leaf_mints':chain=f['chain'];signer=f['childkey']
    if fault=='wrong_template':measurement='unapproved'
    if fault=='long_life':expiry=110
    if fault=='wrong_signer':signer=new_key()
    with pytest.raises(Rejected):
        mint_child(chain,public_hex(f['anchor']),f['registry'],42,25,set(),
                   signer,new_key(),policy(False,0),expiry,measurement)

@pytest.mark.parametrize('field,value', [
    ('actual_peer','external.example'), ('channel','other-channel'),
    ('expected_sequence',1), ('expected_geometry','e'*64), ('epoch',43)])
def test_action_binding(family,field,value):
    with pytest.raises(Rejected):execute(family,prepare_action(family),**{field:value})

def test_action_payload_binding(family):
    q=request();q['payload_digest']='e'*64
    with pytest.raises(Rejected):execute(family,prepare_action(family),actual_request=q)

def test_unissued_challenge(family):
    b=action_body(family['chain'][-1],request(),'channel-1',0,'d'*64,'nonce-1',70)
    with pytest.raises(Rejected):execute(family,signed(family['childkey'],'action-v1',b))

def test_budget_rollback(family):
    f=family
    with f['ledger'].connect() as db:
        db.execute('UPDATE budgets SET ceiling=0 WHERE id=?',
                   (f['chain'][0]['body']['instance'],))
    proof=prepare_action(f)
    with pytest.raises(Rejected):execute(f,proof)
    with f['ledger'].connect() as db:
        assert db.execute('SELECT SUM(spent) FROM budgets').fetchone()[0]==0
        assert db.execute('SELECT consumed FROM challenges').fetchone()[0]==0
    assert f['ledger'].effect_count()==0

def test_concurrent_replay_one_effect(tmp_path):
    path=tmp_path/'race.sqlite';ledger=Ledger(path)
    ledger.add_budget('root',100);ledger.issue('token','binding')
    def run(_):
        try:
            Ledger(path).consume('token','binding',['root'],1,'request')
            return True
        except Rejected:return False
    with ThreadPoolExecutor(max_workers=8) as pool:results=list(pool.map(run,range(32)))
    assert sum(results)==1
    assert ledger.effect_count()==1

def test_shared_budget_race(tmp_path):
    path=tmp_path/'budget.sqlite';ledger=Ledger(path);ledger.add_budget('root',1)
    for i in range(8):ledger.issue(str(i),'binding')
    def run(i):
        try:
            Ledger(path).consume(str(i),'binding',['root'],1,'request');return True
        except Rejected:return False
    with ThreadPoolExecutor(max_workers=8) as pool:results=list(pool.map(run,range(8)))
    assert sum(results)==1

def test_restart_does_not_reset_consumption(tmp_path):
    path=tmp_path/'restart.sqlite';a=Ledger(path);a.add_budget('root',2);a.issue('t','b')
    a.consume('t','b',['root'],1,'q')
    with pytest.raises(Rejected):Ledger(path).consume('t','b',['root'],1,'q')

def test_canonical_order():
    assert canonical({'b':2,'a':1})==b'{"a":1,"b":2}'

@pytest.mark.parametrize('value',[1.2,float('nan'),'non-ascii-\u00e9',2**60])
def test_restricted_encoding(value):
    with pytest.raises(Rejected):canonical(value)

def test_finite_privacy_cases():
    assert all(check().values())

E.8. test_catalog_import.py

SHA-256: 331d0a2d71fab4785735d909d56b03624dc4cd4d6229f17a035a46f4f4ec0e0d.

import hashlib
import json
import pytest
from import_oscal_catalog import extract

@pytest.fixture
def catalog(tmp_path):
    doc={'catalog':{'metadata':{'version':'test-v1','title':'Synthetic','oscal-version':'1.1.2'},
       'groups':[{'id':'ac','controls':[{'id':'ac-3','title':'Access',
       'params':[{'id':'ac-3_prm_1','label':'source value'}],
       'parts':[{'id':'ac-3_smt','name':'statement','prose':'synthetic statement'}],
       'controls':[{'id':'ac-3.1','title':'Synthetic enhancement'}]}]}]}}
    path=tmp_path/'catalog.json';path.write_text(json.dumps(doc))
    return path,hashlib.sha256(path.read_bytes()).hexdigest()

def test_import_preserves_source(catalog):
    path,h=catalog;r=extract(path,h,'test-v1')
    assert r['source_control_count']==2
    assert r['entries'][0]['parts'][0]['id']=='ac-3_smt'
    assert r['approved_by'] is None
    assert r['entries'][0]['assessment_objective_source'] is None

def test_digest_rejection(catalog):
    with pytest.raises(ValueError):extract(catalog[0],'0'*64,'test-v1')

def test_version_rejection(catalog):
    with pytest.raises(ValueError):extract(*catalog,'wrong-version')

def test_duplicate_rejection(catalog):
    path,_=catalog;doc=json.loads(path.read_text())
    doc['catalog']['groups'][0]['controls'].append({'id':'ac-3','title':'Duplicate'})
    path.write_text(json.dumps(doc));h=hashlib.sha256(path.read_bytes()).hexdigest()
    with pytest.raises(ValueError):extract(path,h,'test-v1')

E.9. test_closure_checker.py

SHA-256: 3cfd43183f602d46448a75b77ec6cc4db958978b3ac19dba24203708eefce43f.

"""Synthetic checker tests. These are not HTTP6 implementation or NIST assessment tests."""
import copy,json,hashlib
from pathlib import Path
from check_requirement_closure import check,time_value
ROOT=Path(__file__).resolve().parent
AS_OF=time_value('2026-11-09T00:00:00Z')
inv={"scope_id":"synthetic-fixture-only","source_version":"synthetic-v1-not-a-NIST-catalog","approved_by":"synthetic-reviewer","source_digest":hashlib.sha256(b'synthetic fixture not authoritative NIST').hexdigest(),"requirements":[{"id":"SYN-001","parameters":["lease_seconds"],"objectives":["SYN-001-OBJ"]},{"id":"SYN-002","parameters":[],"objectives":["SYN-002-OBJ"]}]}
records=[]
for rid in ['SYN-001','SYN-002']:
    records.append({"requirement_id":rid,"scope_id":inv['scope_id'],"implementation_owner":"synthetic-owner","implementation_ref":"fixture-engine/v1","assessment_status":"satisfied","parameters":{"lease_seconds":60} if rid=='SYN-001' else {},"dependencies":["SYN-001"] if rid=='SYN-002' else [],"objectives":[{"id":rid+'-OBJ',"determination":"satisfied","reviewer":"synthetic-reviewer","observed":"Synthetic record field for parser tests only","methods":["test"],"evidence_ids":[rid+'-EV']}],"evidence":[{"id":rid+'-EV',"digest":hashlib.sha256(rid.encode()).hexdigest(),"scope_id":inv['scope_id'],"implementation_ref":"fixture-engine/v1","collector":"synthetic-collector","collected_at":"2026-11-01T00:00:00Z","valid_until":"2026-12-01T00:00:00Z"}]})
reg={"scope_id":inv['scope_id'],"inventory_digest":inv['source_digest'],"records":records}
(ROOT/'synthetic_inventory.json').write_text(json.dumps(inv,indent=2))
(ROOT/'synthetic_register.json').write_text(json.dumps(reg,indent=2))
tests=[]
def test(name,mutate,expected=False):
    i=copy.deepcopy(inv);r=copy.deepcopy(reg);mutate(i,r)
    out=check(i,r,AS_OF)
    assert out['structurally_ready'] is expected,(name,out)
    tests.append({'test':name,'expected_ready':expected,'actual_ready':out['structurally_ready'],'passed':True,'errors_detected':out['errors']})
test('complete_synthetic_records',lambda i,r:None,True)
test('missing_requirement',lambda i,r:r['records'].pop())
test('duplicate_record',lambda i,r:r['records'].append(copy.deepcopy(r['records'][0])))
test('unresolved_parameter',lambda i,r:r['records'][0]['parameters'].update(lease_seconds=None))
test('missing_objective',lambda i,r:r['records'][0].update(objectives=[]))
test('failed_objective',lambda i,r:r['records'][0]['objectives'][0].update(determination='not_satisfied'))
test('stale_evidence',lambda i,r:r['records'][0]['evidence'][0].update(valid_until='2026-11-08T00:00:00Z'))
test('wrong_environment',lambda i,r:r['records'][0]['evidence'][0].update(implementation_ref='different-engine/v2'))
test('missing_dependency',lambda i,r:r['records'][0].update(dependencies=['SYN-404']))
test('circular_dependency',lambda i,r:r['records'][0].update(dependencies=['SYN-002']))
test('unapproved_inventory',lambda i,r:i.update(approved_by=None))
test('empty_inventory',lambda i,r:i.update(requirements=[]))
test('risk_acceptance_not_satisfaction',lambda i,r:r['records'][0].update(assessment_status='risk_accepted'))
test('missing_observation',lambda i,r:r['records'][0]['objectives'][0].update(observed=None))
test('wrong_scope',lambda i,r:r.update(scope_id='another-boundary'))
test('invalid_source_digest',lambda i,r:i.update(source_digest='not-a-hash'))
test('future_evidence',lambda i,r:r['records'][0]['evidence'][0].update(collected_at='2026-11-10T00:00:00Z'))
test('zero_is_resolved_parameter',lambda i,r:r['records'][0]['parameters'].update(lease_seconds=0),True)
report={'scope':'synthetic_record_checker_tests_only','count':len(tests),'passed':len(tests),'tests':tests}
(ROOT/'closure_checker_test_results.json').write_text(json.dumps(report,indent=2))
print(f'{len(tests)} synthetic checker tests passed; no HTTP6 implementation assessment performed.')

E.10. regenerate_public_example.py

SHA-256: 790b69e308f9aa3decc36288ef6190d82bebe3d1a4ead463873c54f5184b474e.

"""Rebuild the public synthetic signed records with fresh ephemeral keys.

The script reads the request, policies, epoch, times, measurements, profile,
channel, sequence, geometry digest, and action nonce from the current records in
`examples/`, generates new P-256 keys, and rewrites review_root_grant.json,
review_child_grant.json, review_action_proof.json, and review_public_registry.json.
Private keys exist only in memory and are discarded when the script exits.
Birth nonces are drawn fresh by make_grant. The output is then replayed through
run_public_example.run(), and the script exits 1 unless the first use is accepted
and the replay is rejected.
"""
import copy
import json
from pathlib import Path
from authority_model import (new_key, public_hex, signed, make_grant, mint_child,
                             register_fixture, action_body)
from run_public_example import run

EXAMPLES = Path(__file__).resolve().parents[1] / 'examples'

def read(name):
    return json.loads((EXAMPLES / name).read_text())

def write(name, value):
    (EXAMPLES / name).write_text(json.dumps(value, indent=2) + '\n')

def regenerate():
    old_root = read('review_root_grant.json')['body']
    old_child = read('review_child_grant.json')['body']
    old_proof = read('review_action_proof.json')['body']
    old_fixture = read('review_public_registry.json')
    root_policy = read('review_policy.json')
    request = read('review_request.json')
    child_policy = copy.deepcopy(old_child['policy'])
    epoch = old_fixture['epoch']

    anchor, root_key, child_key = new_key(), new_key(), new_key()
    root = make_grant(anchor, root_key, root_policy, None, old_root['profile'],
                      epoch, old_root['issued'], old_root['expires'],
                      old_root['measurement'])
    registry = {}
    register_fixture(registry, root)
    child = mint_child([root], public_hex(anchor), registry, epoch,
                       old_child['issued'], set(old_fixture['revoked']),
                       root_key, child_key, child_policy, old_child['expires'],
                       old_child['measurement'])
    register_fixture(registry, child)
    proof = signed(child_key, 'action-v1',
                   action_body(child, request, old_proof['channel'],
                               old_proof['sequence'], old_proof['geometry_digest'],
                               old_proof['nonce'], old_proof['expires']))
    fixture = {'fixture_kind': old_fixture['fixture_kind'],
               'admission_verifier_public_key': public_hex(anchor),
               'registry': registry, 'epoch': epoch, 'now': old_fixture['now'],
               'revoked': old_fixture['revoked']}

    write('review_root_grant.json', root)
    write('review_child_grant.json', child)
    write('review_action_proof.json', proof)
    write('review_public_registry.json', fixture)
    return fixture['admission_verifier_public_key']

if __name__ == '__main__':
    anchor = regenerate()
    result = run()
    print(json.dumps({'admission_verifier_public_key': anchor, 'replay_check': result},
                     indent=2))
    raise SystemExit(0 if result['first'] == 'permitted_once_in_local_model'
                     and result['replay'] == 'rejected'
                     and result['local_effect_count'] == 1 else 1)