Repository navigation
feat(governance): compute plan_hash over the plan as supplied - #1934
Conversation
plan_hash is defined over one sync_plans plan exactly as the buyer sent it. A parsed SyncPlansRequest fills schema defaults such as budget.accounting_mode, so hashing the model or its model_dump() yields a value no buyer or auditor can reproduce. - Add adcp.governance.compute_plan_hash and PLAN_HASH_EXCLUDED_FIELDS: RFC 8785 + SHA-256 + unpadded base64url, stripping only the six top-level bookkeeping fields. Unknown fields and ext stay in the preimage. Parsed models are rejected with TypeError. - issue_governance_authorization accepts plan= as an alternative to plan_hash=. - Add the keyword-only ToolContext.raw_request. For sync_plans and check_governance the dispatcher sets it to a private copy of the request taken before skill middleware, pre-validation hooks, version conversion and model parsing; RequestContext carries it for decisioning platforms. - Document that model_dump() is not a hash preimage and that context factories must return a fresh context per call. Refs #1852 Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Ladon verdict: Approve
Approve.
Clean, additive PR. Adds compute_plan_hash (hash over buyer-supplied plan bytes excluding six fixed bookkeeping fields) and threads the as-supplied request to governance handlers via ToolContext.raw_request, snapshotted before middleware/hooks/version-conversion/parsing. Changes are keyword-only params and defaulted fields — backward compatible on the public surface, correctly carrying feat(governance): with no break. 545 lines of tests cover the spec vectors, the mutating-middleware path, and A2A number-coercion bit-exactness.
Decision-table walk:
- Row 1 (critical/high): no findings — skip.
- Row 2 (gated paths):
gated_paths: false— skip. - Row 3 (high-risk deletion): all high-risk reasons are
(modified), none(deleted)— skip. - Row 4 (medium data-loss/schema/infra): no medium findings — skip.
- Row 5 (high-risk modified + medium): no medium findings — skip.
- Row 6 (sticky escalate): no prior decision — skip.
- Row 7 (no-auto-approve team): no team match — skip.
- Row 8 (≥3 medium): zero medium findings — skip.
- Row 9: approve.
high_risk: true is a heuristic signal only; all matched files are (modified) with no medium-or-higher concerns, so the modifications are presumed safe. No semver, forward-compat, import-layering, generated-code, credential, CI-gate, or version-pathway concerns surfaced.
Refs #1852. Covers items 1 and 2 of the plan in that thread; items 3–5 are not in this PR.
Why
plan_hashis defined over onesync_plansplan exactly as the buyer supplied it. A parsedSyncPlansRequestis not a valid preimage: parsing fillsbudget.accounting_mode(still defaulted on specmain) and, on the 3.2 schema this SDK pins,human_review_required. Hashing the model, or itsmodel_dump(), therefore produces a hash no buyer or auditor can reproduce. Against the vendored vectors, every vector that parses hashes differently aftermodel_dump().Item 1:
compute_plan_hashadcp.governance.compute_plan_hash(plan: Mapping[str, Any]) -> str:base64url_no_pad(SHA-256(RFC 8785(plan))), with only the six top-level bookkeeping fields removed (PLAN_HASH_EXCLUDED_FIELDS). Unknown fields andextstay in, so a future preimage field such as 3.4'shuman_overrideis hashed without an SDK change. Omitted,falseandnullstay distinct; no schema default is applied.TypeErrorwith a pointer to the raw mapping, rather than returning a hash that cannot match.issue_governance_authorization(plan=...)hashes the plan for you.plan_hash=still works; passing both or neither raisesTypeError.Item 2: handlers get the as-supplied request
ToolContext.raw_request: Mapping[str, Any] | None: keyword-only, so positional construction of existing subclasses such asAccountAwareToolContextkeeps its field order; defaultNone; excluded fromreprand equality because plans are commercially sensitive.sync_plansandcheck_governance, the handler gets a deep copy of the request as decoded from the transport, taken before skill middleware, pre-validation hooks, version conversion, unknown-field handling and model parsing. Every other tool getsNone, so a reused context never carries a stale request. All public factories (serve,create_mcp_server,create_a2a_server) dispatch through this path._dispatch_with_middleware(shared by MCP and A2A) therefore snapshots governance requests before the chain runs and hands the snapshot tocreate_tool_callerthrough a task-scopedContextVar, the same place thesync_reporting_receiptsrewrite guard already sits. Middleware rewrites still reach the parsed request; onlyraw_requestkeeps the buyer's copy.raw_requestonto whatever context thecontext_factoryreturns. The docstring and the guide now say the factory must return a freshToolContextper call, because a shared instance would let one request read another buyer's plan._build_request_contextcopies it toRequestContext.raw_request, soCampaignGovernancePlatform.sync_plans(req, ctx)readsctx.raw_request["plans"][i].docs/handler-authoring.mdgains "Hashing governance plans", which says plainly thatmodel_dump()is not a hash preimage; theGovernanceHandlerandCampaignGovernancePlatformdocstrings point atraw_request.Cross-SDK note
Python's
rfc8785raisesIntegerDomainErrorfor integers beyond ±(2^53−1), andcompute_plan_hashlets thatValueErrorthrough, as its docstring says. A JavaScript implementation would silently round such a value to a double and hash the rounded number. A plan carrying an out-of-range integer therefore fails loudly here instead of producing a hash that disagrees with other SDKs.Branch
main. Theplan_hashprofile and its eleven vectors are part of AdCP 3.2 (vendored undersrc/adcp/_compliance/3.2.x/test-vectors/plan-hash), and the governance handlers and JWS issuance live onmain. The vectors on specmainare byte-identical to the vendored 3.2.7 set.nextpicks this up with its regular merge frommain.Tests
tests/test_plan_hash.py:compute_plan_hashis the helper that slice can call;1e5 == 100000.0 == 100000), omitted/false/nullhuman_review_required, a schema-defaultedaccounting_mode,extand unknown fields, top-level-only stripping (nestedstatus/versionstay; look-alike fields stay), no Unicode normalization, input not mutated,TypeErrorfor models and non-mappings,ValueErrorfor NaN and out-of-range integers;issue_governance_authorization(plan=...);GovernanceHandlerunder strict validation receives the plan unmodified; capture happens before a rewriting pre-validation hook;check_governancereceivespayloadas supplied; handler mutation doesn't leak back; other tools and reused contexts getNone; a decisioningCampaignGovernancePlatformreceives it onctx.raw_request;reprdoesn't show it. (There is nosync_plansversion converter today, so no test claims capture before conversion.)Structandrestore_struct_integers) givecompute_plan_hash(ctx.raw_request["plans"][0])equal to the spec hash. The same runs with a middleware that rewrites the plan in place show the parsed request rewritten andraw_requestunchanged. Those middleware cases fail without the snapshot fix.Locally: full
pytest tests/,ruff check src/,black --check,mypy src/adcp/,mypy --strict tests/type_checks/, and the pyright adopter suite.🤖 Generated with Claude Code