Skip to content

Commit fc6aae7

Browse files
committed
fix(identity): bound outage continuity and preserve revocations
1 parent bdbbf83 commit fc6aae7

13 files changed

Lines changed: 1472 additions & 107 deletions

‎docs/agent-identity-3-3-migration.md‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,8 @@ A presented `Signature-Agent` or `web-bot-auth` tag selects WBA exclusively, inc
6262

6363
`DiscoveredSignerKeys` resolves `(covered origin, thumbprint)` from a signed directory. It never calls capabilities or reads brand.json or trust.json. `verify_wba_request` is the standalone async verifier; it returns verified origins without granting authority. The legacy synchronous verifier rejects WBA markers and cannot be used as a fallback.
6464

65+
When a key directory cannot be fetched or a revocation list is stale past grace, the request receives retryable `SERVICE_UNAVAILABLE`. It establishes no identity and performs no business operation; it does not silently fall back to anonymous access. A fetched directory without the requested key, or a directory returning `404` or `410`, remains a signature failure with the WBA challenge.
66+
6567
To continue accepting configured RFC 9421 buyers on the same endpoint, pass their existing `StaticSignerKeys` or `JwksUriSignerKeys` as `DiscoveredSignerKeys(legacy_resolver=...)`. Only messages selected for the legacy profile use this resolver. A failed WBA discovery never falls back to it. Concurrent directory lookups coalesce per origin and do not block unrelated signers.
6668

6769
A verified unbound caller can invoke `get_adcp_capabilities` and `get_principal` by default. Configure `unbound_for` to match the handler's other anonymous permissions, such as public `get_products` and `list_creative_formats`, and JSON-RPC methods such as `initialize` or `tools/list` when they are public. Include `sync_principal` only when the application implements an explicit open onboarding policy that checks trust, requirements and billing before approval. These operations receive an established origin with no principal or account authority. `get_principal` implementations should return the preview's `unconfigured` result when no durable principal exists. Discovering a key never creates or upserts an account. To approve a binding, evaluate the operator's record explicitly:
@@ -80,7 +82,7 @@ The framework preserves the verified origin as caller identity and exposes the b
8082

8183
A stored binding records seller approval, not permanent operator membership. Framework binding authorization re-evaluates the operator's agent entry using `trust_records` and its polling-bounded cache, including when reusing a trusted edge's verified signer. `binding_role` defaults to `adcp:buying`; configure the required role for other receiving surfaces. A delisted origin falls back to identity-established access: the application's anonymous operations and `get_principal`, with no account authority. It cannot bind again while unlisted. Keep its historical binding to prevent a legacy downgrade.
8284

83-
An unreachable trust record does not delist a bound origin. Spend-committing calls fail with retryable `SERVICE_UNAVAILABLE`; other calls continue under the cached binding and existing account permissions. A failed binding or trust-record match uses `PERMISSION_DENIED`. These authority checks run after transport verification; key discovery still reads no trust record.
85+
An unreachable trust record does not delist a bound origin. The last record read stays authoritative, including a delisting or removal. Spend-committing calls fail with retryable `SERVICE_UNAVAILABLE`; other calls can continue under existing permissions only within four polling intervals after the last listing record's freshness deadline. Without a prior listing, or after that grace window, they also receive `SERVICE_UNAVAILABLE`. A `404` or `410` after a record was read is removal rather than an outage. A failed binding or trust-record match uses `PERMISSION_DENIED`. These authority checks run after transport verification; key discovery still reads no trust record.
8486

8587
`RequestSignatureVerification.spend_classifier(operation, params)` lets a seller classify spending using its own state. The default treats new purchases, acquisitions, resumes, financial changes, and unknown operations as spend-committing; name changes, pauses, and cancellations can continue under a cached binding. Budget changes are conservative because the verifier cannot compare them with seller-owned balances. The trusted decision also governs the account grant gate.
8688

@@ -92,15 +94,17 @@ Framework WBA verification installs `OriginRevocationChecker` by default to read
9294

9395
## Trust records and demand grants
9496

95-
The built-in origin revocation checker admits at most 256 origins and eight per registrable operator by default. Failed initial discovery consumes only a bounded 60-second cooldown entry; successful signed history is retained. Configure `max_origins` and `max_origins_per_operator`, or supply a durable checker with seller-owned admission policy for larger deployments. Discovery caches coalesce requests per origin/domain so one slow counterparty does not block another tenant.
97+
The built-in origin revocation checker admits at most 256 origins and eight per registrable operator by default. Initial discovery without an authenticated list consumes only a bounded 60-second cooldown entry. Authenticated signed history, including revocations in stale responses, is retained; a stale response still cannot authorize a request past grace. Configure `max_origins` and `max_origins_per_operator`, or supply a durable checker with seller-owned admission policy for larger deployments. Discovery caches coalesce requests per origin/domain so one slow counterparty does not block another tenant.
9698

97-
`TrustRecordEvaluator` derives `https://{eTLD+1}/.well-known/trust.json` using the SDK's pinned ICANN and PRIVATE PSL snapshot. It follows one `authoritative_location` pointer while preserving the original owner, follows no HTTP redirects, caps bytes at 2 MiB, rejects ambiguous JSON, and caches no longer than the configured revocation polling interval. Failed or expired records provide no authority. A 200 response permanently disables legacy fallback for that host during the evaluator's lifetime, including after a later disappearance or fetch failure.
99+
`TrustRecordEvaluator` derives `https://{eTLD+1}/.well-known/trust.json` using the SDK's pinned ICANN and PRIVATE PSL snapshot. It follows one `authoritative_location` pointer while preserving the original owner, follows no HTTP redirects, caps bytes at 2 MiB, rejects ambiguous JSON, and caches no longer than the configured revocation polling interval. Keep a custom polling interval no longer than the identity's revocation cadence; the default is 60 seconds. Fresh approval requires current records; outage grace is an explicit option for existing non-spend access and never replaces a newer negative record. A 200 response permanently disables legacy fallback for that host during the evaluator's lifetime, including after a later disappearance or fetch failure.
98100

99101
Host failure cooldowns are scoped to the original record owner, so an owner's pointer cannot suppress another owner's discovery. Content errors do not cool down a host. The default limits allow 256 pending records and four concurrent fetches per destination host; local saturation fails closed without caching a failure, so callers can retry as soon as capacity is available. Shared transport responses still receive separate ownership validation.
100102

103+
Outage continuity rechecks the latest retained policy for every owner, even when another origin or claim fetched it. Removals and invalid records supersede earlier approvals. Policy snapshots are bounded by `max_records`; eviction closes continuity until a fresh check succeeds. A final snapshot and clock check prevents a concurrent refresh or slow callback from extending older authority.
104+
101105
`validate_trust_record(document, operator_domain=...)` validates authoring output, rejects keys in agent entries, checks ownership, and enforces one agent per origin. The record's host is its owner; a hosted document cannot name another owner inside its content.
102106

103-
`TrustGrantEvaluator.check(...)` evaluates authority from the brand's record. It recognizes same-domain implicit authority and direct or one-intermediary chains that include `account.operator`. A self-operated brand can grant the signer's operator directly: the brand itself is `account.operator` on that chain. Every link must cover the requested scope, brand, countries, agent narrowing, and validity window. It intersects authority and cannot follow a third delegation link. `exclusive_grants` disables discretionary authorization for scopes named by the record. The optional `seller_authorization` hook consults seller-owned onboarding policy; `legacy_authorization` runs only when the brand has never successfully published trust.json and its initial fetch returns 404/410. Fetch failures do not invoke either fallback.
107+
`TrustGrantEvaluator.check(...)` evaluates authority from the brand's record. It recognizes same-domain implicit authority and direct or one-intermediary chains that include `account.operator`. A self-operated brand can grant the signer's operator directly: the brand itself is `account.operator` on that chain. Every link must cover the requested scope, brand, countries, agent narrowing, and validity window. It intersects authority and cannot follow a third delegation link. `exclusive_grants` disables discretionary authorization for scopes named by the record. The optional `seller_authorization` hook consults seller-owned onboarding policy; `legacy_authorization` runs only when the brand has never successfully published trust.json and its initial fetch returns 404/410. Fetch failures cannot establish new authority. Explicit outage continuity rechecks retained records and preserves every grant's hard validity deadline.
104108

105109
For `DecisioningPlatform`, wire a gate and an active buyer-agent registry:
106110

@@ -122,10 +126,12 @@ gate = TrustGrantGate(
122126
# request_signature_verification=verification)
123127
```
124128

125-
The gate checks every natural-key `sync_accounts` declaration before any upsert. Existing account IDs and account-scoped calls use the seller's extractor, including a fresh check before spending. An uncovered grant raises `PERMISSION_DENIED` with `{"scope": "agent", "reason": "grant_absent"}` after commercial identity is established. A failed trust-record match uses `PERMISSION_DENIED` without grant details; an outage requiring fresh authority uses retryable `SERVICE_UNAVAILABLE`. Existing bound accounts can continue non-spend calls during an outage, but provisioning still requires a current grant. A known grant denial persists until a fresh successful check; an outage cannot restore withdrawn authority. `max_denials` bounds this process-local history (default 4,096); once full, outage fallback stays disabled for that gate rather than forgetting a denial. Persist withdrawals in seller-owned state when continuity across restarts is required. The gate changes no account status. Supply equivalent checks in custom `ADCPHandler` implementations before account side effects.
129+
The gate checks every natural-key `sync_accounts` declaration before any upsert. Existing account IDs and account-scoped calls use the seller's extractor, including a fresh check before spending. An uncovered grant raises `PERMISSION_DENIED` with `{"scope": "agent", "reason": "grant_absent"}` after commercial identity is established. A failed trust-record match uses `PERMISSION_DENIED` without grant details; an outage requiring fresh authority uses retryable `SERVICE_UNAVAILABLE`. Existing bound accounts can continue non-spend calls only under previously read authority within its grace window; provisioning still requires a current grant. A grantor's record removed after a read means `grant_absent`, and cannot restore legacy authorization. A known grant denial persists until a fresh successful check; an outage cannot restore withdrawn authority. `max_denials` bounds this process-local history (default 4,096); once full, outage fallback stays disabled for that gate rather than forgetting a denial. Persist withdrawals in seller-owned state when continuity across restarts is required. The gate changes no account status. Supply equivalent checks in custom `ADCPHandler` implementations before account side effects.
126130

127131
Typed client results preserve `adcp_error`, including its code, recovery guidance, and details. A `SERVICE_UNAVAILABLE` result has transient recovery and can be retried after backoff; `PERMISSION_DENIED` requires an authorization change.
128132

133+
The gate also retains at most `max_denials` successful claim proofs. Only a previously approved claim can use outage grace, and evicting its positive proof removes that continuity. An outage read never refreshes the proof or extends an explicit grant's validity window.
134+
129135
When configured, this gate replaces the older `brand_authorization_gate` for account-scoped dispatch. Put any permitted brand.json fallback in `TrustGrantEvaluator(legacy_authorization=...)`; applying both gates independently would wrongly consult `authorized_operators` after a successful trust.json fetch.
130136

131137
The framework passes the trusted transport profile into this gate. Legacy RFC 9421 and bearer buyers can use the configured legacy authorization hook without an operator trust record while the brand has never published trust.json. Once the brand returns 200, both profiles use fresh operator membership and trust grants; a missing record or fetch failure cannot restore the old path.

‎src/adcp/decisioning/trust_grants.py‎

Lines changed: 55 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import inspect
66
import threading
77
from _thread import LockType
8+
from collections import OrderedDict
89
from collections.abc import Awaitable, Callable, Mapping
910
from dataclasses import dataclass, field
1011
from typing import Any, Literal
@@ -38,6 +39,7 @@ class TrustGrantClaim:
3839
@dataclass
3940
class _DenialHistory:
4041
denials: dict[_ClaimKey, tuple[int, GrantAuthorization]] = field(default_factory=dict)
42+
positives: OrderedDict[_ClaimKey, GrantAuthorization] = field(default_factory=OrderedDict)
4143
revision: int = 0
4244
saturated_revision: int | None = None
4345
lock: LockType = field(default_factory=threading.Lock)
@@ -145,6 +147,32 @@ async def require_claim(
145147
scope=claim.scope,
146148
signing_profile=signing_profile,
147149
)
150+
continuity_deadline: float | None = None
151+
if result.error_code == "SERVICE_UNAVAILABLE" and allow_cached_binding_on_outage:
152+
with self._history.lock:
153+
positive = self._history.positives.get(key)
154+
if (
155+
key not in self._history.denials
156+
and self._history.saturated_revision is None
157+
and positive is not None
158+
and positive.outage_expires_at is not None
159+
and positive.outage_expires_at > self.evaluator.current_time()
160+
):
161+
continuity_deadline = positive.outage_expires_at
162+
if continuity_deadline is not None:
163+
# A positive claim alone is insufficient: another request may
164+
# have read a newer owner withdrawal or delisting. Revalidate
165+
# every link against the latest retained record snapshots.
166+
result = await self.evaluator.check(
167+
agent_origin=agent.agent_url,
168+
brand_domain=claim.brand_domain,
169+
account_operator=claim.account_operator,
170+
brand_id=claim.brand_id,
171+
countries=claim.countries,
172+
scope=claim.scope,
173+
signing_profile=signing_profile,
174+
allow_stale_on_outage=True,
175+
)
148176
with self._history.lock:
149177
denied = self._history.denials.get(key)
150178
if result.authorized:
@@ -158,9 +186,36 @@ async def require_claim(
158186
result = GrantAuthorization(
159187
False, error_code="SERVICE_UNAVAILABLE", include_grant_absent_details=False
160188
)
189+
elif continuity_deadline is not None:
190+
if (
191+
result.outage_expires_at is None
192+
or min(continuity_deadline, result.outage_expires_at)
193+
<= self.evaluator.current_time()
194+
):
195+
result = GrantAuthorization(
196+
False,
197+
error_code="SERVICE_UNAVAILABLE",
198+
include_grant_absent_details=False,
199+
)
200+
# An outage read must never refresh the retained proof.
201+
elif (
202+
result.expires_at is not None
203+
and result.expires_at <= self.evaluator.current_time()
204+
):
205+
result = GrantAuthorization(
206+
False, error_code="SERVICE_UNAVAILABLE", include_grant_absent_details=False
207+
)
161208
else:
162209
self._history.denials.pop(key, None)
210+
if result.outage_expires_at is not None:
211+
self._history.positives[key] = result
212+
self._history.positives.move_to_end(key)
213+
while len(self._history.positives) > self.max_denials:
214+
# Forgetting a positive closes outage access; unlike
215+
# withdrawals, it is safe to bound these snapshots.
216+
self._history.positives.popitem(last=False)
163217
elif result.error_code == "PERMISSION_DENIED":
218+
self._history.positives.pop(key, None)
164219
self._history.revision += 1
165220
if denied is not None or len(self._history.denials) < self.max_denials:
166221
self._history.denials[key] = (self._history.revision, result)
@@ -172,8 +227,6 @@ async def require_claim(
172227
elif result.error_code == "SERVICE_UNAVAILABLE":
173228
if denied is not None:
174229
result = denied[1]
175-
elif allow_cached_binding_on_outage and self._history.saturated_revision is None:
176-
return
177230
result.require()
178231

179232
async def require_account(

0 commit comments

Comments
 (0)