|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Offline verifier for the agentic-commerce accountability example.""" |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import hashlib |
| 6 | +import json |
| 7 | +import sys |
| 8 | +from pathlib import Path |
| 9 | +from typing import Any |
| 10 | + |
| 11 | + |
| 12 | +def digest(value: Any) -> str: |
| 13 | + encoded = json.dumps(value, sort_keys=True, separators=(",", ":")).encode() |
| 14 | + return "sha256:" + hashlib.sha256(encoded).hexdigest() |
| 15 | + |
| 16 | + |
| 17 | +def verify(bundle: dict[str, Any]) -> list[str]: |
| 18 | + errors: list[str] = [] |
| 19 | + grant = bundle["authority_grant"] |
| 20 | + request = bundle["purchase_request"] |
| 21 | + decision = bundle["policy_decision"] |
| 22 | + evidence = bundle["runtime_evidence"] |
| 23 | + receipt = bundle["purchase_receipt"] |
| 24 | + if request["operation"] not in grant["allowed_operations"]: |
| 25 | + errors.append("operation is outside delegated authority") |
| 26 | + if request["currency"] != grant["currency"]: |
| 27 | + errors.append("currency differs from delegated authority") |
| 28 | + if request["merchant_id"] not in grant["allowed_merchants"]: |
| 29 | + errors.append("merchant is outside delegated authority") |
| 30 | + if request["amount_minor"] > grant["max_amount_minor"]: |
| 31 | + errors.append("amount exceeds delegated authority") |
| 32 | + if decision["request_digest"] != digest(request): |
| 33 | + errors.append("policy decision is not bound to the purchase request") |
| 34 | + if decision["authority_digest"] != digest(grant): |
| 35 | + errors.append("policy decision is not bound to the authority grant") |
| 36 | + if evidence["policy_decision_digest"] != digest(decision): |
| 37 | + errors.append("runtime evidence is not bound to the policy decision") |
| 38 | + if receipt["request_digest"] != digest(request): |
| 39 | + errors.append("receipt is not bound to the purchase request") |
| 40 | + if receipt["runtime_evidence_digest"] != digest(evidence): |
| 41 | + errors.append("receipt is not bound to the runtime evidence") |
| 42 | + if decision["outcome"] != "allow": |
| 43 | + errors.append("policy decision did not allow the purchase") |
| 44 | + return errors |
| 45 | + |
| 46 | + |
| 47 | +def main() -> int: |
| 48 | + if len(sys.argv) != 2: |
| 49 | + print("usage: python verify_purchase.py <bundle.json>", file=sys.stderr) |
| 50 | + return 2 |
| 51 | + bundle = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8")) |
| 52 | + errors = verify(bundle) |
| 53 | + if errors: |
| 54 | + print("REJECTED") |
| 55 | + for error in errors: |
| 56 | + print(f"- {error}") |
| 57 | + return 1 |
| 58 | + print("ACCEPTED: authority, decision, runtime evidence, and receipt are linked") |
| 59 | + return 0 |
| 60 | + |
| 61 | + |
| 62 | +if __name__ == "__main__": |
| 63 | + raise SystemExit(main()) |
0 commit comments