Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions docs/handler-authoring.md
Original file line number Diff line number Diff line change
Expand Up @@ -1498,6 +1498,53 @@ Buyer/governance-agent helpers live in `adcp.governance`:
- `issue_governance_authorization()` and
`verify_governance_authorization()` implement the compact-JWS profile and
the shared deterministic conformance vectors.
- `compute_plan_hash()` computes the `plan_hash` claim over one plan exactly
as supplied on `sync_plans`. `issue_governance_authorization(plan=...)`
calls it for you.

### Hashing governance plans

`plan_hash` is defined over the plan **as the buyer supplied it**. A parsed
model is not a hash preimage, and neither is its `model_dump()`: parsing
fills schema defaults (`budget.accounting_mode`, and `human_review_required`
on schema versions that still default it) and normalizes values, so the
dump hashes differently from the buyer's copy and every buyer-side or
auditor check fails.

The dispatcher therefore hands `sync_plans` and `check_governance` handlers
the request as supplied on `context.raw_request`: a private copy taken
after transport decoding but before skill middleware, pre-validation hooks,
version conversion, unknown-field handling and model parsing. Persist that
mapping and hash it:

```python
from adcp.governance import compute_plan_hash, issue_governance_authorization

class MyGovernanceAgent(GovernanceHandler):
async def handle_sync_plans(self, request, context=None):
for plan in context.raw_request["plans"]:
# Store the plan as supplied; compute_plan_hash strips only the
# six bookkeeping fields the spec lists.
await plans.save(plan["plan_id"], plan, plan_hash=compute_plan_hash(plan))
...

async def handle_check_governance(self, request, context=None):
plan = await plans.current(request.plan_id) # the stored, as-supplied mapping
token = issue_governance_authorization(
plan=plan,
payload=context.raw_request["payload"],
...,
)
```

`compute_plan_hash()` rejects a Pydantic model with a `TypeError` rather than
hashing a value that cannot match. The dispatcher writes `raw_request` onto
the context your `context_factory` returns, so the factory must build a fresh
`ToolContext` per call; a shared instance would let one request read another
buyer's plan. `raw_request` is `None` for other tools
and when a handler is called directly without the dispatcher. The
decisioning `CampaignGovernancePlatform` receives the same value on
`ctx.raw_request`.

### Alternative A2A wire formats

Expand Down
1 change: 1 addition & 0 deletions src/adcp/decisioning/dispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -1348,6 +1348,7 @@ def _build_request_context(
"caller_identity": caller_identity,
"tenant_id": tool_ctx.tenant_id,
"resolved_adcp_version": tool_ctx.resolved_adcp_version,
"raw_request": tool_ctx.raw_request,
"metadata": clean_metadata,
"transport": transport,
"account": account,
Expand Down
9 changes: 9 additions & 0 deletions src/adcp/decisioning/specialisms/governance.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,10 @@ def check_governance(
``modification``, or ``delivery`` and never exposes the buyer's plan or
original payload to the service.

Tokens bind hashes over supplied bytes: compute ``plan_hash`` over
the plan revision as supplied on ``sync_plans`` and the payload hash
over ``ctx.raw_request["payload"]``, never over ``req``'s dump.

:raises adcp.decisioning.AdcpError: for buyer-fixable
rejection (``PLAN_NOT_FOUND``, ``INVALID_REQUEST``).
``status: 'denied'`` on the response is the
Expand All @@ -139,6 +143,11 @@ def sync_plans(
The agent tracks plan state across the campaign lifecycle
(pending_approval → active → closed); transitions are emitted
via ``ctx.publish_status_change(resource_type='plan', ...)``.

``req`` is the parsed model with schema defaults filled in, so it is
not a ``plan_hash`` preimage. Persist each plan as supplied, from
``ctx.raw_request["plans"][i]``, and hash that mapping with
:func:`adcp.governance.compute_plan_hash`.
"""
...

Expand Down
85 changes: 83 additions & 2 deletions src/adcp/governance.py
Original file line number Diff line number Diff line change
Expand Up @@ -926,6 +926,74 @@ def compute_governed_payload_hash(payload: Mapping[str, Any]) -> str:
return b64url_encode(hashlib.sha256(rfc8785.dumps(business_payload)).digest())


PLAN_HASH_EXCLUDED_FIELDS: frozenset[str] = frozenset(
{
"version",
"status",
"syncedAt",
"revisionHistory",
"committedBudget",
"committedByType",
}
)
"""The closed set of top-level governance-agent bookkeeping fields removed
from a plan before computing ``plan_hash``.

The spec fixes this list; it must not be extended or shrunk. Every other
field on the plan, including ``ext`` and fields this SDK does not model, is
part of the preimage.
"""


def compute_plan_hash(plan: Mapping[str, Any]) -> str:
"""Compute the ``plan_hash`` claim for one plan, exactly as supplied.

Implements the AdCP campaign-governance plan-binding profile::

plan_hash = base64url_no_pad(SHA-256(JCS(plan_payload)))

``plan`` is a single element of the ``plans[]`` array as the buyer
supplied it on ``sync_plans`` (not the request envelope and not the
``plans`` array). Only the top-level bookkeeping fields in
:data:`PLAN_HASH_EXCLUDED_FIELDS` are removed; everything else is
hashed as-is, so key order does not matter but omitted-versus-``null``,
array order, unknown fields, ``ext`` and Unicode form all do. Numbers are
serialized per RFC 8785 (ECMAScript number formatting), so ``1.0`` and
``1`` hash the same.

Pass the raw mapping, never a parsed model or its ``model_dump()``.
Parsing applies schema defaults (``budget.accounting_mode``, and on some
schema versions ``human_review_required``) and drops or rewrites
fields, which changes the hash. Server handlers for ``sync_plans`` and
``check_governance`` receive the as-supplied request on
:attr:`adcp.server.ToolContext.raw_request`; for ``sync_plans`` the plan
is ``context.raw_request["plans"][i]``.

To check a received ``plan_hash`` against this value, base64url-decode
both to the 32-byte digest and compare with :func:`hmac.compare_digest`;
the spec forbids comparing the encoded strings.

:param plan: The as-supplied plan object (any JSON-compatible mapping).
:returns: The unpadded base64url SHA-256 digest of the RFC 8785
canonical form of the plan minus the bookkeeping fields.
:raises TypeError: if ``plan`` is a Pydantic model or not a mapping.
:raises ValueError: if the plan contains a value RFC 8785 cannot
canonicalize: a non-JSON type, a non-finite float, or an integer
outside the I-JSON safe range (``rfc8785.CanonicalizationError``).
"""
supplied: object = plan # runtime callers are not bound by the annotation
if isinstance(supplied, BaseModel):
raise TypeError(
"compute_plan_hash needs the plan exactly as supplied on sync_plans; a parsed "
"model or its model_dump() carries schema defaults and is not a valid preimage. "
"Use the raw mapping, e.g. context.raw_request['plans'][i]."
)
if not isinstance(supplied, Mapping):
raise TypeError("compute_plan_hash expects a plan mapping")
preimage = {key: value for key, value in plan.items() if key not in PLAN_HASH_EXCLUDED_FIELDS}
return b64url_encode(hashlib.sha256(rfc8785.dumps(preimage)).digest())


def compute_governance_outcome_hash(payload: Mapping[str, Any]) -> str:
"""Return the exact outcome replay identity, excluding retry metadata."""
replay_payload = {
Expand Down Expand Up @@ -1008,7 +1076,8 @@ def issue_governance_authorization(
alg: Literal["EdDSA", "ES256"],
issuer: str,
subject: str,
plan_hash: str,
plan_hash: str | None = None,
plan: Mapping[str, Any] | None = None,
audience: str,
caller: str,
check_id: str,
Expand All @@ -1023,7 +1092,17 @@ def issue_governance_authorization(
media_buy_id: str | None = None,
extra_claims: Mapping[str, Any] | None = None,
) -> str:
"""Issue a compact JWS for one exact governed downstream request."""
"""Issue a compact JWS for one exact governed downstream request.

Supply exactly one of ``plan_hash`` (a precomputed claim value) or
``plan`` (the evaluated plan exactly as supplied on ``sync_plans``,
hashed with :func:`compute_plan_hash`). ``payload`` must likewise be the
governed request as supplied, not a parsed model's dump.
"""
if (plan_hash is None) == (plan is None):
raise TypeError("pass exactly one of plan_hash or plan")
if plan is not None:
plan_hash = compute_plan_hash(plan)
for name, value in (
("key_id", key_id),
("issuer", issuer),
Expand Down Expand Up @@ -1513,6 +1592,7 @@ async def _maybe_await(value: Any) -> Any:
"NormalizedGovernanceConditions",
"NormalizedGovernanceDenied",
"NormalizedGovernanceVerdict",
"PLAN_HASH_EXCLUDED_FIELDS",
"build_governance_commitment",
"build_governance_execution_commitment",
"build_governance_execution_request",
Expand All @@ -1521,6 +1601,7 @@ async def _maybe_await(value: Any) -> Any:
"build_governance_proposed_commitment",
"compute_governed_payload_hash",
"compute_governance_outcome_hash",
"compute_plan_hash",
"enforce_governance_authorization",
"get_governance_enforcement_tasks",
"governance_request_check_type",
Expand Down
24 changes: 24 additions & 0 deletions src/adcp/server/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from __future__ import annotations

from abc import ABC
from collections.abc import Mapping
from dataclasses import dataclass, field
from typing import Any, Generic, TypeVar

Expand Down Expand Up @@ -162,13 +163,36 @@ class ToolContext:
``get_adcp_capabilities`` resolves to the highest supported release.
Handlers must answer in the latest shapes regardless of this value;
the SDK converts the response down to this version.
:param raw_request: The request exactly as the buyer supplied it on the
wire (after transport decoding), captured before skill middleware,
pre-validation hooks, version conversion, unknown-field handling and
Pydantic parsing.
Populated for ``sync_plans`` and ``check_governance``; ``None``
for other tools and for direct handler calls that bypass the
dispatcher. Each call gets its own deep copy, so a handler may keep
or change it without affecting the dispatcher. Use it for any hash
the protocol defines over the supplied request: ``compute_plan_hash`` over
``raw_request["plans"][i]`` and ``compute_governed_payload_hash``
over ``raw_request["payload"]``. The parsed request model is not a
hash preimage: parsing fills schema defaults (for example
``budget.accounting_mode``) and normalizes values, so its
``model_dump()`` hashes differently from what the buyer sent.
The dispatcher writes this field onto the context your
``context_factory`` returns, so the factory must return a fresh
``ToolContext`` for every call; a shared instance would let one
request read another buyer's plan. Keyword-only.
"""

request_id: str | None = None
caller_identity: str | None = None
tenant_id: str | None = None
metadata: dict[str, Any] = field(default_factory=dict)
resolved_adcp_version: str | None = None
# Keyword-only so positional construction of subclasses keeps its order;
# kept out of repr/eq because plans carry commercially sensitive data.
raw_request: Mapping[str, Any] | None = field(
default=None, repr=False, compare=False, kw_only=True
)


@dataclass
Expand Down
16 changes: 14 additions & 2 deletions src/adcp/server/governance.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,13 @@ async def handle_sync_plans(
request: SyncPlansRequest,
context: TContext | None = None,
) -> SyncPlansResponse:
"""Handle campaign governance plan sync."""
"""Handle campaign governance plan sync.

``request`` is the parsed model, with schema defaults filled in. Do
not hash it or its ``model_dump()``. Persist each plan as supplied,
from ``context.raw_request["plans"][i]``, and compute ``plan_hash``
with :func:`adcp.governance.compute_plan_hash` over that mapping.
"""
...

@abstractmethod
Expand All @@ -331,7 +337,13 @@ async def handle_check_governance(
request: CheckGovernanceRequest,
context: TContext | None = None,
) -> CheckGovernanceResponse:
"""Handle a governance check request."""
"""Handle a governance check request.

When issuing a ``governance_context`` token, hash the plan revision
as it was supplied on ``sync_plans`` and the governed payload as
supplied here (``context.raw_request["payload"]``), not the parsed
``request`` model.
"""
...

@abstractmethod
Expand Down
37 changes: 36 additions & 1 deletion src/adcp/server/mcp_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
import copy
import difflib
import logging
from collections.abc import Callable, Iterable, Sequence
from collections.abc import Callable, Iterable, Mapping, Sequence
from contextvars import ContextVar
from typing import Any, Literal

from adcp.server._hooks import (
Expand Down Expand Up @@ -3263,6 +3264,28 @@ def _creative_capabilities_for_handler(handler: Any) -> Any:
return getattr(handler, "_framework_adcp_capabilities", None)


# Tools whose handlers receive the as-supplied request on
# ``ToolContext.raw_request``: the spec defines hashes over these requests'
# supplied bytes (``plan_hash`` over each ``sync_plans`` plan, and the governed
# ``payload`` a ``check_governance`` token binds).
_RAW_REQUEST_TOOLS = frozenset({"sync_plans", "check_governance"})

# Set by the transports' skill-middleware composer
# (``adcp.server.serve._dispatch_with_middleware``) to the request as it
# arrived, before any middleware can rewrite the shared params dict in place.
# ``call_tool`` prefers it over its own params when the tool name matches.
_RAW_REQUEST_SNAPSHOT: ContextVar[tuple[str, dict[str, Any]] | None] = ContextVar(
"adcp_raw_request_snapshot", default=None
)


def _snapshot_raw_request(tool_name: str, params: Any) -> dict[str, Any] | None:
"""Return a private deep copy of ``params`` when ``tool_name`` gets one."""
if tool_name not in _RAW_REQUEST_TOOLS or not isinstance(params, Mapping):
return None
return copy.deepcopy(dict(params))


def create_tool_caller(
handler: ADCPHandler[Any],
method_name: str,
Expand Down Expand Up @@ -3502,6 +3525,18 @@ async def call_tool(params: dict[str, Any], context: ToolContext | None = None)
ctx = context if context is not None else ToolContext()

raw_params = params # Preserve original wire params for context echo.
# Governance hashes (plan_hash, authorized_payload_hash) are defined
# over the request as supplied. Hand the handler a private copy taken
# before skill middleware, hooks, conversion, unknown-field handling or
# model defaults touch it (#1852). Always assign so a reused context
# never carries a previous call's request.
transport_snapshot = _RAW_REQUEST_SNAPSHOT.get()
if transport_snapshot is not None and transport_snapshot[0] == method_name:
# Taken before skill middleware ran; copy again so the handler's
# copy is private even if middleware retried the call.
ctx.raw_request = copy.deepcopy(transport_snapshot[1])
else:
ctx.raw_request = _snapshot_raw_request(method_name, params)

if frozen_reporting_feed and params.get("view") == "periods":
from adcp.reporting.feed.errors import ReportingFeedError
Expand Down
38 changes: 38 additions & 0 deletions src/adcp/server/serve.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,10 @@ async def get_adcp_capabilities(self, params, context=None):
from adcp.server.mcp_sessions import ADCPStreamableHTTPSessionManager
from adcp.server.mcp_tools import (
_HANDLER_TOOLS,
_RAW_REQUEST_SNAPSHOT,
SchemaMode,
_resolve_handler_adcp_version,
_snapshot_raw_request,
create_tool_caller,
get_tools_for_handler,
)
Expand Down Expand Up @@ -883,6 +885,42 @@ async def _dispatch_with_middleware(
if not middleware:
return await call_handler()

# Middleware receives the same params dict the handler later gets, so a
# middleware that edits it in place would leak into ``raw_request``.
# Snapshot governance requests before the chain runs (#1852).
raw_snapshot = _snapshot_raw_request(skill_name, params)
if raw_snapshot is not None:
snapshot_token = _RAW_REQUEST_SNAPSHOT.set((skill_name, raw_snapshot))
try:
return await _dispatch_middleware_chain(
middleware,
skill_name,
params,
context,
call_handler,
frozen_reporting_feed=frozen_reporting_feed,
)
finally:
_RAW_REQUEST_SNAPSHOT.reset(snapshot_token)
return await _dispatch_middleware_chain(
middleware,
skill_name,
params,
context,
call_handler,
frozen_reporting_feed=frozen_reporting_feed,
)


async def _dispatch_middleware_chain(
middleware: Sequence[SkillMiddleware],
skill_name: str,
params: dict[str, Any],
context: ToolContext,
call_handler: Callable[[], Awaitable[Any]],
*,
frozen_reporting_feed: bool,
) -> Any:
receipt_request = None
if skill_name == "sync_reporting_receipts":
from adcp.exceptions import ADCPTaskError
Expand Down
Loading
Loading