Skip to main content

acdp_client/
verified.rs

1//! VerifiedContext: retrieve + verify in one call.
2
3use super::data_ref::{fetch_and_verify_data_ref, DataRefFetcher};
4use super::registry::RegistryClient;
5use acdp_did::WebResolver;
6use acdp_primitives::error::AcdpError;
7use acdp_types::{body::FullContext, primitives::CtxId};
8use acdp_verify::Verifier;
9use std::time::Duration;
10
11use super::revocation_verdict::{RevocationAssessment, RevocationVerdict, SourcedRevocation};
12use super::transparency::{
13    CannotVerifyReason, LogInclusionPolicy, LogInclusionVerdict, TransparencyVerdicts,
14    WitnessQuorumPolicy,
15};
16use super::witness::WitnessQuorumReport;
17
18/// Consumer-tunable strictness for [`VerifiedContext::fetch_with_policy`],
19/// [`VerifiedContext::fetch_current_with_policy`], and the
20/// `fetch_report*` family ([`VerifiedContext::fetch_report`],
21/// [`VerifiedContext::fetch_report_with_fetcher`],
22/// [`VerifiedContext::fetch_report_diagnose`]). All three surfaces
23/// consult the same policy fields through the same `verify_retrieved`
24/// spine — but they do not always *agree*, because
25/// [`VerifiedContext::fetch_report_diagnose`] differs in more than just
26/// how a failure surfaces:
27///
28/// - [`VerifiedContext::fetch_report`] and
29///   [`VerifiedContext::fetch_report_with_fetcher`] run
30///   `verify_retrieved` directly once their own top-level probes pass,
31///   and surface a phase failure as `Err`.
32/// - [`VerifiedContext::fetch_report_diagnose`] runs its own
33///   independent, strict, assertionMethod-only signature *probe* first
34///   (recorded as `VerificationReport::signature_ok`). That probe has
35///   no historical-key fallback and runs *before* `verify_retrieved` is
36///   ever invoked. If it fails, `diagnose` withholds the
37///   [`VerifiedContext`] handle with `policy_phase_error: None` — the
38///   spine never ran, so there is no phase error to record — even in
39///   cases where `verify_retrieved` itself, as run by `fetch_report`,
40///   would have accepted the key historically under the default
41///   `historical_keys: HistoricalKeyPolicy::AcceptWithReceipt` plus a
42///   verified receipt. Concretely: for a key rotated out of
43///   `assertionMethod` with a valid receipt, `fetch_report` returns
44///   `Ok` with [`KeyAuthorization::HistoricallyAuthorized`], while
45///   `diagnose` returns no handle at all for the same input and policy.
46///   Only once `diagnose`'s own probes all pass does it fall through to
47///   `verify_retrieved` and, from that point on, withhold the handle /
48///   record [`VerificationReport::policy_phase_error`] instead of
49///   returning `Err` — that part of the behavior *is* shared with the
50///   other two.
51///
52/// The verification profile is **always strict**:
53///
54/// - Every producer identity must be `did:web` or `did:key` — enforced
55///   unconditionally by `verify_signature_envelope`
56///   (RFC-ACDP-0001 §5.4), regardless of any policy field.
57/// - Embedded `DataRef` hashes are verified by
58///   [`acdp_validation::validate_body`] whenever `validate_body_schema`
59///   is set.
60///
61/// Only the fields below have real effect in this version; there are no
62/// relaxed-mode `did:web` or embedded-hash knobs.
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct VerificationPolicy {
65    /// If true, run [`acdp_validation::validate_body`] (structural
66    /// schema checks plus embedded-`DataRef` hash verification) before
67    /// any cryptographic check. Default `true`. Set `false` only in
68    /// diagnostic paths that want to attempt signature verification
69    /// despite a body known to fail structural checks.
70    ///
71    /// The `fetch_report*` family forces this field off unconditionally
72    /// on the internal policy it derives from the caller's — they run
73    /// `validate_body_structural` (schema only) themselves and record
74    /// per-`DataRef` embedded-hash outcomes in
75    /// [`VerificationReport::data_ref_embedded`] instead of treating a
76    /// mismatch as fatal. This field's value as set by the caller is
77    /// otherwise irrelevant to the report family.
78    pub validate_body_schema: bool,
79
80    /// If true, accept `Status::Other` values (degrade to active per
81    /// RFC-ACDP-0004 §4.1). When false, reject unknown statuses.
82    /// Default `true`.
83    pub allow_unknown_status: bool,
84
85    /// Registry-receipt handling (ACDP 0.2, RFC-ACDP-0010).
86    /// Default [`ReceiptPolicy::VerifyIfPresent`].
87    pub receipts: ReceiptPolicy,
88
89    /// Historical-key handling (ACDP 0.2, WS-B). Default
90    /// [`HistoricalKeyPolicy::AcceptWithReceipt`].
91    pub historical_keys: HistoricalKeyPolicy,
92
93    /// Lineage-head receipt handling on `/current` fetches (ACDP 0.3,
94    /// RFC-ACDP-0011). Only consulted by
95    /// [`VerifiedContext::fetch_current_with_policy`]; plain retrieval
96    /// preserves any `lineage_head_receipt` verbatim without verifying
97    /// it. Default [`LineageHeadPolicy::default`]. This is the ONE
98    /// field on this struct with restricted scope — `allow_unknown_status`,
99    /// `receipts`, `historical_keys`, and `revocations` above and below
100    /// are each honored by every entry point that accepts a
101    /// [`VerificationPolicy`], including the `fetch_report*` family.
102    pub lineage_head: LineageHeadPolicy,
103
104    /// Key-revocation handling (ACDP 0.3, RFC-ACDP-0014 §7). Default:
105    /// no known revocations — the phase is inert.
106    pub revocations: RevocationPolicy,
107
108    /// RFC-ACDP-0001 §5.11 v0.1.0 strict profile, item 1 (NORMATIVE for
109    /// `acdp-consumer`): when `body.acdp_version` is absent or `"0.1.0"`,
110    /// `body.agent_id` and the DID portion of `signature.key_id` MUST be
111    /// `did:web`; any other method fails with `schema_violation`.
112    /// Default `true` (and `true` in [`Self::strict_v0_1_0`]).
113    ///
114    /// `did:key` was introduced in 0.2.0, whose producers MUST emit
115    /// `acdp_version`, so a conformant body never trips this. Setting it
116    /// `false` is a relaxed mode that is **non-conformant with v0.1.0**
117    /// and outside the `acdp-consumer` conformance profile (§5.11).
118    pub require_did_web_for_v0_1_0: bool,
119
120    /// Transparency-log inclusion handling (ACDP 0.4, RFC-ACDP-0012 §9).
121    /// Default [`LogInclusionPolicy::Ignore`]. The verdict is reported
122    /// separately, through [`VerifiedContext::log_inclusion_verdict`] and
123    /// [`VerificationReport::log_inclusion_verdict`]. A failure fails
124    /// verification only under [`LogInclusionPolicy::Require`] (§9.3).
125    pub log_inclusion: LogInclusionPolicy,
126
127    /// Witness-quorum corroboration of the log checkpoint (ACDP 0.4,
128    /// RFC-ACDP-0015 §8). Default `None`, which means not evaluated. When
129    /// set, the `log_inclusion` checkpoint is verified even under
130    /// [`LogInclusionPolicy::Ignore`], because cosignatures can only be
131    /// checked against a checkpoint the consumer verified itself.
132    pub witness_quorum: Option<WitnessQuorumPolicy>,
133}
134
135impl Default for VerificationPolicy {
136    fn default() -> Self {
137        Self {
138            validate_body_schema: true,
139            allow_unknown_status: true,
140            receipts: ReceiptPolicy::VerifyIfPresent,
141            historical_keys: HistoricalKeyPolicy::AcceptWithReceipt,
142            lineage_head: LineageHeadPolicy::default(),
143            revocations: RevocationPolicy::default(),
144            require_did_web_for_v0_1_0: true,
145            log_inclusion: LogInclusionPolicy::Ignore,
146            witness_quorum: None,
147        }
148    }
149}
150
151/// Consumer-held key revocations to enforce during verification
152/// (ACDP 0.3, RFC-ACDP-0014 §7).
153///
154/// [`Self::known`] is **pull-based**: the pipeline does not go looking
155/// for those revocations on its own — the caller supplies the
156/// **verified** revocations it holds (from
157/// [`find_revocations`](crate::revocation::find_revocations),
158/// [`find_registry_attested_revocations`](crate::revocation::find_registry_attested_revocations),
159/// an out-of-band channel, or its own indefinite cache — the statement
160/// is permanent, cache accordingly). [`Self::discover`] (RFC-ACDP-0014
161/// §8) is the opt-in complement: when set, `verify_retrieved` itself
162/// runs those same two lookups and unions their result with `known`
163/// (see [`RevocationDiscovery`]). When `known` is empty, `discover` is
164/// `None`, AND no [`crate::RevocationCache`] is attached to the client,
165/// the phase is inert and verification behaves exactly as before
166/// RFC-ACDP-0014.
167///
168/// Issue #257 gives `discover`'s own caching a first-class home:
169/// [`crate::RevocationCache`], attached to the [`crate::RegistryClient`]
170/// passed to `verify_retrieved` via
171/// [`crate::RegistryClient::with_revocation_cache`], persists exactly the
172/// "own indefinite cache" a caller would otherwise have to hand-roll
173/// around `known` — verified revocations discovered on one call are
174/// unioned into every later call against the same client, unconditionally
175/// and indefinitely, independent of [`RevocationDiscovery::freshness`], and
176/// **regardless of whether that later call itself sets `discover`** —
177/// attaching a cache is itself the opt-in (MATERIAL-3, fresh-Opus review
178/// of Phase 2): a call made with `discover: None` still seeds
179/// producer-signed facts from the cache (never registry-attested ones —
180/// see below), which is what extends this anti-rollback protection to
181/// [`VerifiedContext::fetch`]/[`VerifiedContext::fetch_current`] (LIM-2),
182/// the two entry points that can never set `discover` at all. A
183/// registry-attested fact, by contrast, is additionally scoped to the
184/// vantage that minted it (BLOCKER-1, RFC-ACDP-0014 §6): reading it back
185/// through a client talking to a different authority never applies it,
186/// even under [`RevocationDiscovery::include_registry_attested`]. See
187/// that field's doc and `crate::revocation_cache` for the full model,
188/// including the separate, opt-in, TTL-bounded marker that can additionally
189/// skip a repeat lookup.
190///
191/// When the body's signing key matches a supplied revocation, §7
192/// applies: a receipt-attested publish time strictly before the
193/// (earliest, §4) `compromised_since` boundary verifies as
194/// [`KeyAuthorization::HistoricallyAuthorizedPreCompromise`]; at/after
195/// the boundary, or with no verified receipt to place the context at
196/// all, verification **fails closed** with `key_not_authorized` —
197/// regardless of DID-document state and regardless of the receipt's
198/// own validity. Note the interaction with [`ReceiptPolicy::Ignore`]:
199/// an unverified receipt provides no publish time, so a revoked key's
200/// contexts all fail closed under it.
201///
202/// This applies uniformly to every entry point that *accepts* a
203/// [`VerificationPolicy`] — [`VerifiedContext::fetch_with_policy`],
204/// [`VerifiedContext::fetch_current_with_policy`], and the
205/// `fetch_report*` family (five entry points in total) — since they all
206/// reach this phase through the same internal pipeline. On
207/// [`VerifiedContext::fetch_report_diagnose`] specifically, "fails
208/// closed" means the returned [`VerifiedContext`] handle is withheld
209/// and the cause is recorded in `VerificationReport::policy_phase_error`,
210/// rather than the call returning `Err` — that method never
211/// short-circuits on a policy-phase failure by design.
212///
213/// "Uniformly" has one remaining carve-out, structural rather than a
214/// policy choice: [`VerifiedContext::fetch`] and
215/// [`VerifiedContext::fetch_current`] hardcode
216/// [`VerificationPolicy::default`] and so can never carry a non-empty
217/// `known` or a `discover`; callers wanting either use the
218/// `_with_policy` forms instead. This is recorded as a known limitation
219/// (issue #248 LIM-2) rather than silently true. Phase 2's cache still
220/// extends anti-rollback protection to these two entry points — see
221/// [`Self::discover`]'s doc — but they can never *configure* discovery
222/// themselves.
223///
224/// **Issue #260 closed the sibling limitation, LIM-1.**
225/// [`crate::CrossRegistryResolver::with_revocation_policy`] now injects a
226/// [`RevocationPolicy`] into every node a cross-registry walk verifies,
227/// and [`crate::CrossRegistryResolver::with_revocation_cache`] shares one
228/// [`crate::RevocationCache`] across the walk (walk-scoped by default —
229/// see that method's doc). The resolver derives `receipts` itself, per
230/// node, from that node's advertised capabilities, so it takes a
231/// [`RevocationPolicy`], never a caller-supplied [`VerificationPolicy`] —
232/// see `CrossRegistryResolver::with_revocation_policy`'s doc for why.
233///
234/// Only put revocations here that you have verified (strict body
235/// pipeline + the §5 not-self-signed rule) and, per §6, that you have
236/// decided to act on: producer-signed ones unconditionally;
237/// registry-attested ones ([`RevocationTrustClass::RegistryAttested`](acdp_types::revocation::RevocationTrustClass))
238/// by default only for contexts served by or receipted by that same
239/// registry, with corroboration before global application.
240///
241/// [`find_revocations`](crate::revocation::find_revocations) itself
242/// pre-filters its output to [`RevocationTrustClass::ProducerSigned`](acdp_types::revocation::RevocationTrustClass)
243/// entries actually published by the queried producer, so §6
244/// registry-attested attestations never arrive through it — obtain
245/// those from
246/// [`find_registry_attested_revocations`](crate::revocation::find_registry_attested_revocations)
247/// instead.
248///
249/// `#[non_exhaustive]`: this struct grew a second field
250/// ([`Self::discover`], RFC-ACDP-0014 §8 auto-discovery) after having
251/// shipped with exactly one, and a caller constructing this with a
252/// bare struct literal would otherwise break on every future field the
253/// same way. Construct with [`Self::new`] (equivalent to today's
254/// `RevocationPolicy { known }`) and, when opting into discovery,
255/// [`Self::with_discovery`].
256#[derive(Debug, Clone, PartialEq, Eq, Default)]
257#[non_exhaustive]
258pub struct RevocationPolicy {
259    /// Verified revocations to enforce, matched against the signing
260    /// key's RFC-ACDP-0010 §6 fingerprint. The §4 earliest-
261    /// `compromised_since` rule is applied across entries naming the
262    /// same fingerprint, so include *every* revocation of a lineage,
263    /// superseded (and retracted) ones too — a later member can only
264    /// widen the compromise window, never narrow it, and dropping an
265    /// earlier one is exactly how that window gets quietly (and
266    /// wrongly) shrunk. This is no longer an unassisted obligation:
267    /// [`find_revocations`](crate::revocation::find_revocations) and
268    /// [`find_registry_attested_revocations`](crate::revocation::find_registry_attested_revocations)
269    /// each walk the full lineage of every candidate they find
270    /// (search-visible or not, including all-retracted lineages) and
271    /// already return the complete set for their respective trust
272    /// class; [`find_revocations_in_lineage`](crate::revocation::find_revocations_in_lineage)
273    /// does the same directly from a known `lineage_id`, with no
274    /// producer/trust-class scope filter. Populate `known` from one of
275    /// these rather than hand-assembling a lineage.
276    pub known: Vec<acdp_types::revocation::KeyRevocation>,
277
278    /// RFC-ACDP-0014 §8 auto-discovery configuration. `None` (the
279    /// default) is exactly today's behavior: the caller supplies
280    /// everything via [`Self::known`] and this phase does no network
281    /// I/O of its own. `Some` opts into running
282    /// [`find_revocations`](crate::revocation::find_revocations) and,
283    /// depending on [`RevocationDiscovery::include_registry_attested`],
284    /// [`find_registry_attested_revocations`](crate::revocation::find_registry_attested_revocations)
285    /// as part of verification, merging their results with
286    /// [`Self::known`].
287    pub discover: Option<RevocationDiscovery>,
288
289    /// Non-strict placement mode (RFC-ACDP-0014 §7 step 1, 0.5.0).
290    /// Under the strict profile (the default, `false`), a receipt
291    /// verified under a *historical* receipt key
292    /// ([`ReceiptKeyStatus::Historical`](acdp_types::receipt::ReceiptKeyStatus))
293    /// cannot place a revoked-key context before its compromise
294    /// boundary: the context is unplaceable (§7 step 4) and fails
295    /// closed. `true` also accepts a historical receipt key as a
296    /// placement — a deployment choice that is **non-conformant with the
297    /// strict profile**, reported per RFC-ACDP-0001 §5.11 like the step 4
298    /// pragmatic mode. Set it with
299    /// [`Self::accept_historical_receipt_key_for_pre_t`]. Ordinary
300    /// rotation with no revocation is unaffected either way.
301    pub accept_historical_receipt_key_for_pre_t: bool,
302}
303
304impl RevocationPolicy {
305    /// Construct a policy from a caller-supplied revocation set with
306    /// discovery left off (`discover: None`) — the same shape as the
307    /// bare `RevocationPolicy { known }` literal this struct's
308    /// `#[non_exhaustive]` retires.
309    #[must_use]
310    pub fn new(known: Vec<acdp_types::revocation::KeyRevocation>) -> Self {
311        Self {
312            known,
313            discover: None,
314            accept_historical_receipt_key_for_pre_t: false,
315        }
316    }
317
318    /// Opt into the non-strict placement mode: a receipt verified under
319    /// a historical receipt key may place a revoked-key context before
320    /// its compromise boundary. See
321    /// [`Self::accept_historical_receipt_key_for_pre_t`](field@Self::accept_historical_receipt_key_for_pre_t).
322    #[must_use]
323    pub fn accept_historical_receipt_key_for_pre_t(mut self) -> Self {
324        self.accept_historical_receipt_key_for_pre_t = true;
325        self
326    }
327
328    /// Opt into RFC-ACDP-0014 §8 auto-discovery on top of any
329    /// caller-supplied [`Self::known`] revocations. See
330    /// [`RevocationDiscovery`] for cost and the required explicit
331    /// trust-class choice.
332    #[must_use]
333    pub fn with_discovery(mut self, discovery: RevocationDiscovery) -> Self {
334        self.discover = Some(discovery);
335        self
336    }
337}
338
339/// RFC-ACDP-0014 §8 revocation auto-discovery configuration.
340///
341/// When set on [`RevocationPolicy::discover`], this instructs
342/// verification to look up revocations itself — via
343/// [`find_revocations`](crate::revocation::find_revocations) and,
344/// when [`Self::include_registry_attested`] is `true`, additionally
345/// [`find_registry_attested_revocations`](crate::revocation::find_registry_attested_revocations)
346/// — instead of relying solely on [`RevocationPolicy::known`].
347///
348/// # Cost
349///
350/// Discovery is expensive, and every request it issues is **serial**.
351/// `MAX_SEARCH_PAGES = 10` (`crate::revocation`) bounds search
352/// round-trips *per `(type_form, status)` pair*, and there are **6**
353/// such pairs (2 type forms × 3 statuses) — so up to 60 search
354/// requests, each of which can name up to 100 per-candidate context
355/// retrieves (`GET /contexts/{id}`, capped at 1 MB apiece), for up to
356/// **6,000 + 60 + 100 = 6,160 requests / ~6.1 GB** in the worst case
357/// for *one* of the two discovery functions. The retrieve fan-out is
358/// **not** bounded by `MAX_LINEAGE_WALKS = 100` — that cap is only
359/// checked *after* the retrieves have already gone out. With
360/// [`Self::include_registry_attested`] set, both functions run:
361/// **≈12,321 requests / ~12.2 GB** worst case for the pair (the extra
362/// 1 is the unconditional `client.capabilities()` fetch
363/// `find_registry_attested_revocations` makes).
364///
365/// [`Self::total_timeout`] is an **availability bound, not a bytes or
366/// memory bound**: it stops verification from hanging forever against
367/// a slow or hostile registry, but a hostile registry on a fast link
368/// can still serve gigabytes of legitimate-looking traffic inside the
369/// window — the 1 MB cap applies per request, not in aggregate, and
370/// verified revocations accumulate in a `Vec` for the call's duration.
371/// [`Self::max_requests`] and [`Self::max_bytes`] (issue #258) close
372/// that gap: set either (or both) to bound the two lookups **combined**
373/// — enabling [`Self::include_registry_attested`] does not double the
374/// ceiling — checked **before** each request is issued, so a would-be
375/// request that would exceed the budget is never sent. Exhaustion
376/// raises `AcdpError::RevocationDiscoveryBudgetExceeded` through the
377/// same [`Self::on_failure`] path as `AcdpError::SearchTruncated` — it
378/// is permanent for the same request shape and is never transient.
379/// Both knobs bound **registry** traffic only: DID-document fetches
380/// issued via `WebResolver` are not counted. [`Self::max_bytes`] counts
381/// only **successfully-parsed response bodies** — an error-envelope
382/// read on a non-success response is not charged. [`Self::max_requests`]
383/// has no such exemption: the request slot is reserved *before* the
384/// request is issued, so a 503, a parse failure, or a `PayloadTooLarge`
385/// still consumes it. Leaving both `None` (as both
386/// [`Self::producer_signed_only`] and [`Self::all_trust_classes`] do)
387/// preserves pre-#258 behavior exactly: unbounded requests and bytes,
388/// bounded only by [`Self::total_timeout`].
389///
390/// Issue #257 adds an opt-in cache ([`crate::RevocationCache`], attached
391/// to the [`crate::RegistryClient`] passed in via
392/// [`crate::RegistryClient::with_revocation_cache`]) — but attaching one
393/// does NOT, by itself, turn "re-discovers from scratch" into "sometimes
394/// skips discovery." It is two independent things: verified revocations
395/// ("facts") are always unioned into classification, indefinitely,
396/// regardless of [`Self::freshness`] — a caller verifying many contexts
397/// against the same producer benefits from this immediately, with zero
398/// extra configuration, simply by attaching a cache and reusing the
399/// client. Whether a repeat lookup is skipped entirely (saving requests)
400/// is governed separately by [`Self::freshness`], which defaults to
401/// 300 s (RFC-ACDP-0014 §8's RECOMMENDED bound on a cached negative). See [`Self::freshness`]'s own doc and
402/// `crate::revocation_cache` for the full model. Without a cache attached
403/// at all, this crate behaves exactly as before #257: every call
404/// re-discovers from scratch, budgeted or not. A caller that does not
405/// want to manage a `RevocationCache` can still discover once itself and
406/// pass the results via [`RevocationPolicy::known`] instead of setting
407/// `discover` on every call — the same hoisting guidance
408/// `crate::revocation`'s `find_registry_attested_revocations` doc already
409/// gives callers of that function directly (see its "Cost note for
410/// callers verifying many contexts").
411///
412/// # Reentrancy
413///
414/// Discovery calls back into verification, and that reentrancy has two
415/// consequences worth stating explicitly rather than leaving implicit:
416///
417/// 1. Each candidate body [`find_revocations`](crate::revocation::find_revocations)
418///    turns up is verified via `Verifier::new(resolver).verify_body` —
419///    **not** `verify_retrieved` — so discovered revocation bodies are
420///    themselves checked *without* revocation checking of their own.
421///    That is defensible under RFC-ACDP-0014 §5 step 1's "currently
422///    authorized key," but it is an assumption this type is making on
423///    the caller's behalf, not an accident.
424/// 2. Verifying a `key-revocation` context now *also* triggers
425///    discovery against the same producer, so the revocation-fetch path
426///    itself becomes fragile under [`DiscoveryFailurePolicy::FailClosed`]:
427///    a producer whose revocation search is briefly unreachable can no
428///    longer be verified as revoked, either.
429///
430/// # No `Default`
431///
432/// This type deliberately has **no [`Default`] impl** — construct it
433/// via [`Self::producer_signed_only`] or [`Self::all_trust_classes`].
434/// RFC-ACDP-0014 §6's "lost-everything" fallback means a producer that
435/// has lost every key it could sign a revocation with can *only* be
436/// revoked registry-attested — so the catastrophic case is exactly the
437/// one a silently-defaulted-off trust class would skip. A quiet
438/// `Default::default()` that leaves `include_registry_attested: false`
439/// would make that skip invisible at every call site; forcing a named
440/// constructor puts the choice at the type level instead, where a
441/// reviewer (and `git grep`) can see it. Callers protecting against
442/// key loss, or otherwise unwilling to assume a producer always
443/// retains signing capacity, MUST use [`Self::all_trust_classes`].
444#[derive(Debug, Clone, Copy, PartialEq, Eq)]
445#[non_exhaustive]
446pub struct RevocationDiscovery {
447    /// Whether to also run
448    /// [`find_registry_attested_revocations`](crate::revocation::find_registry_attested_revocations)
449    /// (the §6 registry-attested trust class), in addition to the
450    /// producer-signed search every discovery configuration runs.
451    /// Requires the registry to serve `/.well-known/acdp.json`; under
452    /// [`DiscoveryFailurePolicy::FailClosed`] a registry that serves no
453    /// capabilities document fails verification when this is `true`.
454    pub include_registry_attested: bool,
455    /// What to do when discovery itself fails (a transient transport
456    /// error from either search, or the search-safety-cap error
457    /// `AcdpError::SearchTruncated`). Default [`DiscoveryFailurePolicy::FailClosed`].
458    ///
459    /// **`SearchTruncated` and a transport error (e.g. a 503) are NOT
460    /// equivalent, even though both take this same `on_failure` path.**
461    /// `SearchTruncated` means "this producer has more revocations than
462    /// we will page through" (`MAX_SEARCH_PAGES`) — an
463    /// **attacker-inducible security downgrade**, since a hostile
464    /// producer or registry can pad the result set specifically to
465    /// exhaust the page cap and hide a real revocation from discovery.
466    /// A 503 is an ordinary availability blip. **A third case is
467    /// attacker-inducible the same way `SearchTruncated` is (issue
468    /// #258):** `AcdpError::RevocationDiscoveryBudgetExceeded`, raised
469    /// when [`Self::max_requests`] or [`Self::max_bytes`] is exhausted —
470    /// a hostile registry that learns a caller's budget can pad
471    /// harmless-looking traffic specifically to exhaust it before a
472    /// real revocation is found, just as padding the result set exhausts
473    /// `MAX_SEARCH_PAGES`. Under [`DiscoveryFailurePolicy::ProceedWithKnown`]
474    /// all three are treated the same way (proceed on
475    /// [`RevocationPolicy::known`] alone, record the failure) — choose
476    /// `ProceedWithKnown` knowing it also waives truncation and budget
477    /// exhaustion, not just transient unavailability.
478    pub on_failure: DiscoveryFailurePolicy,
479    /// Wall-clock budget for the whole discovery step (both searches,
480    /// if [`Self::include_registry_attested`] is set). An **availability**
481    /// bound only — see the type-level cost section above. Matches this
482    /// crate's existing `ResolverOptions::total_timeout` precedent
483    /// (`crate::cross_registry`), defaulting to the same 30 s rather
484    /// than exceeding it on the core verify path.
485    ///
486    /// Enforced via [`tokio::time::timeout`], which requires the
487    /// executing Tokio runtime to have its **time driver enabled**
488    /// (`#[tokio::main]` and `#[tokio::test]` enable it by default;
489    /// a hand-built `Builder::new_current_thread()` runtime does
490    /// **not** unless `.enable_time()` or `.enable_all()` is called).
491    /// Calling `verify_retrieved` with `discover: Some(..)` from a
492    /// runtime without the time driver **panics** — it does not
493    /// return `Err` — the same requirement `ResolverOptions::total_timeout`
494    /// (`crate::cross_registry`) already carries on its opt-in walk,
495    /// but here it sits on the core verify path whenever discovery is
496    /// configured, not just on an explicit cross-registry walk.
497    pub total_timeout: Duration,
498    /// Issue #258: cap on the total number of registry requests the
499    /// discovery step may issue, **combined across both lookups** (the
500    /// producer-signed search always, plus the registry-attested search
501    /// when [`Self::include_registry_attested`] is set) — not a ceiling
502    /// per lookup, so turning on the second trust class does not double
503    /// the allowance. `None` (the default from both named constructors)
504    /// is unbounded, matching every version before #258. Checked
505    /// **before** each request is issued (`RegistryClient::capabilities`,
506    /// `::retrieve`, `::lineage`, `::search`); exceeding it raises
507    /// `AcdpError::RevocationDiscoveryBudgetExceeded` through
508    /// [`Self::on_failure`], the same path `AcdpError::SearchTruncated`
509    /// already takes. Counts registry requests only — DID-document
510    /// fetches via `WebResolver` are not counted.
511    pub max_requests: Option<std::num::NonZeroUsize>,
512    /// Issue #258: cap on the cumulative bytes of *successfully-parsed*
513    /// response bodies the discovery step may read, **combined across
514    /// both lookups**, same combination rule as [`Self::max_requests`].
515    /// `None` (the default from both named constructors) is unbounded,
516    /// matching every version before #258. Checked **before** each
517    /// request is issued, using the running total from requests that
518    /// already completed — the size of an in-flight request cannot be
519    /// known (and therefore reserved) in advance, so **up to two**
520    /// requests can push the total past `max_bytes` before the next
521    /// check observes the overrun: the two trust-class lookups run
522    /// concurrently under `tokio::try_join!`, and both can pass a
523    /// not-yet-updated check before either's response is recorded — see
524    /// [`Self::max_requests`]'s doc for the same race on the request
525    /// count, where it is closed by an atomic reservation; there is no
526    /// equivalent reservation for bytes, since a response's size is not
527    /// known until after it is read. Counts a non-success response's
528    /// error-envelope read *not at all* — only bytes read on the
529    /// success path are charged.
530    ///
531    /// `Some(0)` is representable (unlike [`Self::max_requests`], which
532    /// is guarded by `NonZeroUsize`) and is not special-cased: it trips
533    /// the `>=` check on the very first request of either lookup,
534    /// before that request is ever issued, so discovery fails
535    /// immediately with zero registry traffic. This is a deliberate
536    /// consequence of keeping this field a plain `u64` (matching the
537    /// wave plan's chosen types) rather than a reason to reach for
538    /// `NonZeroU64`.
539    pub max_bytes: Option<u64>,
540    /// Issue #257: how long a discovery-freshness marker stays valid on
541    /// a [`crate::RevocationCache`] attached to the [`crate::RegistryClient`]
542    /// passed to `verify_retrieved` (via
543    /// [`crate::RegistryClient::with_revocation_cache`]). A marker records
544    /// "vantage V completed a full, untruncated discovery for this
545    /// producer/trust-class at time T"; while one is within `freshness` of
546    /// T, that lookup is skipped entirely (zero registry requests) rather
547    /// than merely supplemented.
548    ///
549    /// Default [`RECOMMENDED_NEGATIVE_FRESHNESS`](crate::RECOMMENDED_NEGATIVE_FRESHNESS)
550    /// (300 s) from both named constructors — RFC-ACDP-0014 §8 "Caching"
551    /// (0.5.0) RECOMMENDS bounding a cached negative this way (it was
552    /// `Duration::ZERO` before 0.15.0). A cached absence is per vantage,
553    /// per trust class, and minted only by a complete, untruncated lookup;
554    /// an `unknown` outcome is never cached. A verdict answered from one
555    /// reports when the absence was observed
556    /// ([`RevocationVerdict::NotRevoked`]'s `observed_at`). Set
557    /// `Duration::ZERO` to never suppress a lookup. No cache attached makes
558    /// this field inert regardless of its value.
559    ///
560    /// Distinct from — and orthogonal to — caching verified revocations
561    /// themselves ("facts"), which a [`crate::RevocationCache`] does
562    /// **unconditionally** and **indefinitely** whenever one is attached,
563    /// independent of this field: facts are always unioned into
564    /// classification (never gated behind `freshness`), because a
565    /// revocation is monotone (more revocations ⇒ an earlier effective
566    /// boundary ⇒ strictly more fail-closed verdicts), so seeding from
567    /// them can only tighten a verdict, never loosen one. `freshness`
568    /// governs only whether a lookup that would otherwise re-confirm "no
569    /// NEW revocation" is skipped. See `crate::revocation_cache` for the
570    /// full two-object model.
571    ///
572    /// That "unconditionally" is exact for a producer-signed fact (§8:
573    /// self-contained, applies at any vantage) but is scoped for a
574    /// registry-attested one (§6): the cache additionally filters those to
575    /// the vantage that minted them, so attaching one cache to clients for
576    /// two different registries does not let registry A's attestation
577    /// apply to a context served by registry B.
578    ///
579    /// A recommended ceiling, not enforced: RFC-ACDP-0006 §4.2 caps
580    /// `WebResolver`'s own DID-document cache TTL at 3600 s, and that is a
581    /// reasonable order-of-magnitude anchor for this field too — this
582    /// crate already accepts bounded key-material staleness at that
583    /// order. Left unenforced deliberately: a hard cap on a knob whose
584    /// safe default is `ZERO` would add a failure mode without adding
585    /// safety.
586    pub freshness: Duration,
587}
588
589impl RevocationDiscovery {
590    /// Discover producer-signed revocations only
591    /// (`include_registry_attested: false`). Cheapest of the two
592    /// constructors, and the default choice for callers that are not
593    /// specifically defending against a producer that has lost every
594    /// signing key — see the "No `Default`" section above for who must
595    /// NOT stop here.
596    #[must_use]
597    pub fn producer_signed_only() -> Self {
598        Self {
599            include_registry_attested: false,
600            on_failure: DiscoveryFailurePolicy::FailClosed,
601            total_timeout: Duration::from_secs(30),
602            max_requests: None,
603            max_bytes: None,
604            freshness: super::revocation_verdict::RECOMMENDED_NEGATIVE_FRESHNESS,
605        }
606    }
607
608    /// Discover both trust classes: producer-signed AND registry-attested
609    /// (`include_registry_attested: true`). Required to catch RFC-ACDP-0014
610    /// §6's "lost-everything" fallback, where a producer with no signing
611    /// key left can only be revoked registry-attested. Requires the
612    /// registry to serve a capabilities document.
613    #[must_use]
614    pub fn all_trust_classes() -> Self {
615        Self {
616            include_registry_attested: true,
617            on_failure: DiscoveryFailurePolicy::FailClosed,
618            total_timeout: Duration::from_secs(30),
619            max_requests: None,
620            max_bytes: None,
621            freshness: super::revocation_verdict::RECOMMENDED_NEGATIVE_FRESHNESS,
622        }
623    }
624}
625
626/// What to do when RFC-ACDP-0014 §8 auto-discovery itself fails (a
627/// transient search/lookup error, or the discovery search functions'
628/// own safety-cap error).
629#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
630#[non_exhaustive]
631pub enum DiscoveryFailurePolicy {
632    /// Treat an `unknown` discovery outcome as a verification failure
633    /// (`AcdpError::RevocationUnknown`). Default — matches this
634    /// crate's existing bias (§7's own lineage-walk and
635    /// verification-failure paths already fail closed; see
636    /// `crate::revocation`'s doc for the parallel reasoning) that an
637    /// authorization phase which could not run is not the same thing
638    /// as one that ran and found nothing.
639    #[default]
640    FailClosed,
641    /// Proceed using only [`RevocationPolicy::known`] and cached facts when
642    /// discovery is `unknown`; the verified context then carries
643    /// [`RevocationVerdict::Unknown`] (never not-revoked) and the
644    /// `AcdpError::RevocationUnknown` in
645    /// [`VerifiedContext::revocation_discovery_failure`].
646    /// Use only when availability matters more than catching a
647    /// revocation that discovery would otherwise have found.
648    ProceedWithKnown,
649}
650
651/// What RFC-ACDP-0014 §8 auto-discovery actually did, distinguishing
652/// "this trust class was not queried" from "it was queried and found
653/// nothing" — the same distinction
654/// [`RevocationDiscovery`]'s no-`Default` design protects at the
655/// config level, carried through to the outcome.
656#[derive(Debug, Clone, Copy, PartialEq, Eq)]
657#[non_exhaustive]
658pub struct DiscoveryOutcome {
659    /// Count of producer-signed revocations discovery found.
660    pub producer_signed: usize,
661    /// Count of registry-attested revocations discovery found, or
662    /// `None` if [`RevocationDiscovery::include_registry_attested`]
663    /// was `false` and that trust class was never queried.
664    pub registry_attested: Option<usize>,
665}
666
667/// How to treat the optional `registry_receipt` on retrieval
668/// (RFC-ACDP-0010).
669///
670/// `#[non_exhaustive]` since 0.15.0 ([`Self::VerifyAndReport`] was added).
671#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
672#[non_exhaustive]
673pub enum ReceiptPolicy {
674    /// Skip receipt verification entirely (0.1.0 behavior). The
675    /// receipt value is still preserved verbatim on the context.
676    Ignore,
677    /// Verify the receipt when one is present; absence is not an
678    /// error (the registry may simply be a 0.1.0 registry). Default.
679    #[default]
680    VerifyIfPresent,
681    /// Fail closed unless a receipt is present AND verifies. Use when
682    /// the deployment requires audit-grade provenance — registry
683    /// claims (`ctx_id`, `created_at`, `origin_registry`) are
684    /// assertions, not proofs, without a receipt.
685    ///
686    /// Honored identically by every entry point that accepts a
687    /// [`VerificationPolicy`] — `fetch_with_policy`,
688    /// `fetch_current_with_policy` (via [`LineageHeadPolicy::receipts`]),
689    /// and the `fetch_report*` family. On
690    /// [`VerifiedContext::fetch_report_diagnose`] the failure surfaces as
691    /// a withheld handle plus `VerificationReport::policy_phase_error`,
692    /// not an `Err` — see that method's doc.
693    Require,
694    /// Verify the receipt when one is present and report its verdict
695    /// separately from the body verdict (RFC-ACDP-0010 §8, 0.5.0 — the
696    /// `acdp-consumer` "receipt verdict reported separately" rule). A
697    /// failing receipt does not fail retrieval: it is recorded in
698    /// [`VerifiedContext::receipt_verdict`] /
699    /// [`VerificationReport::receipt_verdict`] and then treated exactly
700    /// as an absent one by every rule that consumes receipt-attested
701    /// facts — the RFC-ACDP-0010 §10 historical-key rule does not apply,
702    /// an RFC-ACDP-0014 §7 revoked-key context is unplaceable (fails
703    /// closed), and `lineage_id` is reported
704    /// [`LineageBinding::Unbound`](acdp_verify::LineageBinding). The
705    /// body is never presented as receipt-attested
706    /// ([`VerifiedContext::verified_receipt`] is `None`).
707    ///
708    /// On `/current` the same applies to the lineage-head receipt under
709    /// [`LineageHeadPolicy::receipts`]
710    /// ([`VerifiedContext::head_receipt_verdict`]).
711    VerifyAndReport,
712}
713
714/// How to treat the optional `lineage_head_receipt` on
715/// `GET /lineages/{id}/current` responses (ACDP 0.3, RFC-ACDP-0011).
716///
717/// The presence handling reuses the [`ReceiptPolicy`] vocabulary; the
718/// two numeric knobs are the RFC's consumer-side parameters:
719///
720/// - `max_clock_skew_seconds` — §7 step 6's forward-skew allowance. A
721///   receipt whose `as_of` is further in the future **fails
722///   verification** (`invalid_receipt`, fixture `lhr-004`). RFC
723///   RECOMMENDED: 120.
724/// - `max_age_seconds` — §6's freshness policy. A receipt older than
725///   this is still *verified* (it may be perfectly genuine — merely
726///   old); it is reported distinctly via
727///   [`VerifiedContext::head_receipt_stale`], never as a verification
728///   failure. RFC RECOMMENDED default: 300. `None` disables the
729///   staleness verdict.
730#[derive(Debug, Clone, Copy, PartialEq, Eq)]
731pub struct LineageHeadPolicy {
732    /// Presence handling: `Ignore` (skip verification, preserve
733    /// verbatim), `VerifyIfPresent` (default), or `Require` (fail
734    /// closed unless present AND verified — appropriate when the
735    /// registry advertises `acdp-registry-head-receipts`, under which
736    /// a head receipt on `/current` is REQUIRED, RFC-ACDP-0011 §6).
737    pub receipts: ReceiptPolicy,
738    /// RFC-ACDP-0011 §7 step 6 clock-skew allowance (default 120 s).
739    pub max_clock_skew_seconds: u32,
740    /// RFC-ACDP-0011 §6 maximum acceptable receipt age for the
741    /// staleness verdict (default `Some(300)`).
742    pub max_age_seconds: Option<u32>,
743}
744
745impl Default for LineageHeadPolicy {
746    fn default() -> Self {
747        Self {
748            receipts: ReceiptPolicy::VerifyIfPresent,
749            max_clock_skew_seconds: 120,
750            max_age_seconds: Some(300),
751        }
752    }
753}
754
755/// How to treat a producer key that is present in the DID document's
756/// `verificationMethod` but no longer in `assertionMethod` — i.e. a
757/// key the producer rotated out but retained per the RFC-ACDP-0010
758/// key-retention rule.
759#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
760pub enum HistoricalKeyPolicy {
761    /// Strict 0.1.0 behavior: only `assertionMethod` keys verify.
762    /// Every context signed by a rotated-out key fails.
763    Reject,
764    /// Accept a retained key **only** when a verified registry receipt
765    /// attests (via `key_fingerprint`) that this exact key was the
766    /// authorized one at publish time. Without a verified receipt the
767    /// historical path never activates — fail closed. Default.
768    #[default]
769    AcceptWithReceipt,
770}
771
772/// How the producer key that verified the body relates to the
773/// producer's *current* DID document.
774#[derive(Debug, Clone, Copy, PartialEq, Eq)]
775pub enum KeyAuthorization {
776    /// The signing key is currently listed in `assertionMethod`.
777    CurrentlyAuthorized,
778    /// The signing key was rotated out of `assertionMethod` but is
779    /// retained in `verificationMethod`, and a verified registry
780    /// receipt attests it was the authorized key at publish time
781    /// (RFC-ACDP-0010). Weigh accordingly: valid history, not a
782    /// current endorsement.
783    HistoricallyAuthorized,
784    /// The signing key is **revoked** (a verified RFC-ACDP-0014
785    /// revocation names its fingerprint), but a verified registry
786    /// receipt attests the context was published strictly *before* the
787    /// compromise boundary `compromised_since` — it was signed while
788    /// the key was still the producer's, and verified under the
789    /// RFC-ACDP-0010 §10 historical rule (RFC-ACDP-0014 §7 step 2).
790    ///
791    /// Deliberately distinguishable from BOTH
792    /// [`Self::CurrentlyAuthorized`] and the no-revocation
793    /// [`Self::HistoricallyAuthorized`]: the revocation and its
794    /// boundary MUST be visible in the verdict — even a key still
795    /// listed in `assertionMethod` MUST NOT be reported as fully
796    /// current once revoked. This holds for every entry point that
797    /// accepts a [`VerificationPolicy`], including the `fetch_report*`
798    /// family: they derive `key_status` from the same `verify_retrieved`
799    /// phase `fetch_with_policy` uses, so a revoked key cannot silently
800    /// surface as [`Self::CurrentlyAuthorized`] on any of them. Contexts
801    /// by the same key at/after the boundary — or with no verifiable
802    /// publish time — never reach a status at all: they fail closed
803    /// with `key_not_authorized` (§7 steps 3–4).
804    HistoricallyAuthorizedPreCompromise,
805}
806
807/// RFC-ACDP-0001 §5.11 v0.1.0 strict profile item 1: a body with
808/// `acdp_version` absent or `"0.1.0"` MUST be signed by a `did:web`
809/// producer (`agent_id` and the DID portion of `signature.key_id`).
810fn require_did_web_for_v0_1_0(body: &acdp_types::body::Body) -> Result<(), AcdpError> {
811    if !matches!(body.acdp_version.as_deref(), None | Some("0.1.0")) {
812        return Ok(());
813    }
814    let key_did = body
815        .signature
816        .key_id
817        .split_once('#')
818        .map_or(body.signature.key_id.as_str(), |(d, _)| d);
819    for (field, did) in [
820        ("agent_id", body.agent_id.as_str()),
821        ("signature.key_id", key_did),
822    ] {
823        if !did.starts_with("did:web:") {
824            return Err(AcdpError::SchemaViolation(format!(
825                "v0.1.0 context (acdp_version {}) requires a did:web {field}; got '{did}' \
826                 (RFC-ACDP-0001 §5.11 strict profile)",
827                body.acdp_version.as_deref().unwrap_or("absent"),
828            )));
829        }
830    }
831    Ok(())
832}
833
834impl VerificationPolicy {
835    /// The v0.1.0 strict verification profile (RFC-ACDP-0001 §5.11, §9.2).
836    ///
837    /// Runs the full §5.11 pipeline: body schema validation, `content_hash`
838    /// recomputation, `did:web` key resolution, signature verification, and
839    /// embedded `data_ref.content_hash` checks. Returns on the first failure.
840    ///
841    /// This is the **only** mode covered by the `acdp-consumer` conformance
842    /// profile. Relaxed modes (`Diagnostic`, `UnsafeForTests`) are NOT
843    /// available in this crate in v0.1.0 — they would be separately-named
844    /// opt-ins per §9.2, and are not currently implemented.
845    ///
846    /// NOT identical to [`Default::default()`] as of 0.2: the default
847    /// policy is receipt-aware (`VerifyIfPresent` + `AcceptWithReceipt`),
848    /// while this named profile preserves the exact v0.1.0 semantics —
849    /// receipts inert ([`ReceiptPolicy::Ignore`]) and only
850    /// `assertionMethod` keys accepted
851    /// ([`HistoricalKeyPolicy::Reject`]). Callers pinned to this
852    /// constructor keep v0.1.0 behavior across the 0.2 upgrade.
853    pub fn strict_v0_1_0() -> Self {
854        Self {
855            validate_body_schema: true,
856            allow_unknown_status: true,
857            receipts: ReceiptPolicy::Ignore,
858            historical_keys: HistoricalKeyPolicy::Reject,
859            lineage_head: LineageHeadPolicy {
860                receipts: ReceiptPolicy::Ignore,
861                ..LineageHeadPolicy::default()
862            },
863            // A 0.1.0-pinned consumer predates RFC-ACDP-0014 and is
864            // unaffected by it (§10): no revocations enforced.
865            revocations: RevocationPolicy::default(),
866            require_did_web_for_v0_1_0: true,
867            // Likewise RFC-ACDP-0012/0015 (0.4.0): transparency inert.
868            log_inclusion: LogInclusionPolicy::Ignore,
869            witness_quorum: None,
870        }
871    }
872
873    /// The policy the report family (`fetch_report`,
874    /// `fetch_report_with_fetcher`, `fetch_report_diagnose`) passes to
875    /// [`VerifiedContext::verify_retrieved`].
876    ///
877    /// `validate_body_schema` is forced `false` unconditionally,
878    /// independent of the caller: P1 (schema) is always handled by the
879    /// report path itself — `validate_body_structural` plus per-`DataRef`
880    /// non-fatal recording of embedded-hash outcomes into
881    /// `VerificationReport::data_ref_embedded` — so the spine must always
882    /// skip its own full `validate_body` (structural + fatal embedded-hash
883    /// check) here. Every other field passes through verbatim. Do **not**
884    /// pass the caller's policy directly to `verify_retrieved` from a
885    /// report entry point; doing so reinstates the fatal embedded-hash
886    /// check the report path deliberately downgrades to non-fatal (see
887    /// `tests/tls_conformance.rs`'s
888    /// `fetch_report_records_embedded_hash_failure`).
889    fn derived_for_report(&self) -> Self {
890        Self {
891            validate_body_schema: false,
892            ..self.clone()
893        }
894    }
895}
896
897/// A retrieved context that has been cryptographically verified.
898///
899/// Every value of this type is the output of one of the
900/// `VerifiedContext::fetch*` pipelines, each of which independently
901/// recomputes `content_hash` (RFC-ACDP-0001 §5.11) and verifies the
902/// producer signature before the value is constructed. The fields are
903/// **private** precisely so this "cryptographically verified" invariant
904/// cannot be forged: there is no way to construct a `VerifiedContext`
905/// around an unverified [`FullContext`]. Downstream code can therefore
906/// trust the accessors below without re-deriving anything.
907#[derive(Debug)]
908pub struct VerifiedContext {
909    inner: FullContext,
910    /// Whether the body verified against a currently authorized key or
911    /// a receipt-attested historical one (ACDP 0.2, WS-B).
912    key_status: KeyAuthorization,
913    /// The verified registry receipt, when one was present and the
914    /// policy verified it (RFC-ACDP-0010). `None` under
915    /// [`ReceiptPolicy::Ignore`] or when the registry minted none.
916    verified_receipt: Option<acdp_types::receipt::RegistryReceipt>,
917    /// RFC-ACDP-0010 §8 step 1 status of the key that signed
918    /// `verified_receipt` (0.5.0). `None` exactly when `verified_receipt`
919    /// is `None`.
920    receipt_key_status: Option<acdp_types::receipt::ReceiptKeyStatus>,
921    /// The receipt verdict, reported separately from the body verdict
922    /// (RFC-ACDP-0010 §8, 0.5.0). `None` when no receipt was evaluated.
923    receipt_verdict: Option<Result<(), AcdpError>>,
924    /// How `body.lineage_id` is bound (RFC-ACDP-0004 §2.1, 0.5.0).
925    lineage_binding: acdp_verify::LineageBinding,
926    /// The verified lineage-head receipt (ACDP 0.3, RFC-ACDP-0011),
927    /// when one was present and the policy verified it. Only populated
928    /// by [`Self::fetch_current`] / [`Self::fetch_current_with_policy`]
929    /// — plain retrieval preserves the raw value verbatim without
930    /// verification. Per §7 this verdict is independent of the body
931    /// verdict and the RFC-ACDP-0010 receipt verdict.
932    verified_head_receipt: Option<acdp_types::receipt::LineageHeadReceipt>,
933    /// RFC-ACDP-0011 §6 freshness verdict for the verified head
934    /// receipt, reported distinctly from verification: `Some(true)`
935    /// when the (genuine, verified) receipt's `as_of` is older than
936    /// [`LineageHeadPolicy::max_age_seconds`]; `Some(false)` when
937    /// within policy; `None` when there is no verified head receipt or
938    /// the max-age knob is disabled.
939    head_receipt_stale: Option<bool>,
940    /// The lineage-head receipt verdict (RFC-ACDP-0011 §7), reported
941    /// separately: `None` when none was evaluated.
942    head_receipt_verdict: Option<Result<(), AcdpError>>,
943    /// RFC-ACDP-0014 §8 auto-discovery failure, when
944    /// `policy.revocations.discover` was `Some`, discovery failed, and
945    /// [`DiscoveryFailurePolicy::ProceedWithKnown`] let verification
946    /// proceed on [`RevocationPolicy::known`] alone anyway. `None` when
947    /// discovery was off, succeeded, or was never attempted because
948    /// [`DiscoveryFailurePolicy::FailClosed`] turned the failure into
949    /// this call's `Err` instead (so no `VerifiedContext` was ever
950    /// constructed to carry it). Exposed so `ProceedWithKnown` is never
951    /// silent on the plain `fetch*` paths — see
952    /// [`Self::revocation_discovery_failure`].
953    revocation_discovery_failure: Option<AcdpError>,
954    /// The typed revocation verdict (RFC-ACDP-0014 §7/§8, 0.5.0).
955    revocation_verdict: RevocationVerdict,
956    /// Verified revocations outside the producer's scope — hints only.
957    revocation_hints: Vec<SourcedRevocation>,
958    /// RFC-ACDP-0012 §9 / RFC-ACDP-0015 §8 verdicts.
959    transparency: TransparencyVerdicts,
960}
961
962/// `verify_retrieved`'s verdicts — private and free to shape.
963struct Retrieved {
964    key_status: KeyAuthorization,
965    verified_receipt: Option<acdp_types::receipt::RegistryReceipt>,
966    receipt_key_status: Option<acdp_types::receipt::ReceiptKeyStatus>,
967    receipt_verdict: Option<Result<(), AcdpError>>,
968    lineage_binding: acdp_verify::LineageBinding,
969    revocation: RevocationAssessment,
970    transparency: TransparencyVerdicts,
971}
972
973type VerifyRetrievedResult = Result<Retrieved, AcdpError>;
974
975impl Retrieved {
976    /// Copy the verdicts onto a report.
977    fn record(&self, report: &mut VerificationReport) {
978        report.key_status = Some(self.key_status);
979        report.receipt_key_status = self.receipt_key_status;
980        report.receipt_verdict = self.receipt_verdict.clone();
981        report.lineage_binding = Some(self.lineage_binding);
982        report.revocation_discovery = self.revocation.discovery.clone();
983        report.revocation_verdict = Some(self.revocation.verdict.clone());
984        report.revocation_hints = self.revocation.hints.clone();
985        report.log_inclusion_verdict = self.transparency.log.clone();
986        report.witness_quorum = self.transparency.witness.clone();
987    }
988
989    fn into_context(self, inner: FullContext) -> VerifiedContext {
990        let RevocationAssessment {
991            verdict,
992            hints,
993            discovery,
994            ..
995        } = self.revocation;
996        let revocation_discovery_failure = match discovery {
997            Some(Err(e)) => Some(e),
998            _ => None,
999        };
1000        VerifiedContext {
1001            inner,
1002            key_status: self.key_status,
1003            verified_receipt: self.verified_receipt,
1004            receipt_key_status: self.receipt_key_status,
1005            receipt_verdict: self.receipt_verdict,
1006            lineage_binding: self.lineage_binding,
1007            verified_head_receipt: None,
1008            head_receipt_stale: None,
1009            head_receipt_verdict: None,
1010            revocation_discovery_failure,
1011            revocation_verdict: verdict,
1012            revocation_hints: hints,
1013            transparency: self.transparency,
1014        }
1015    }
1016}
1017
1018impl VerifiedContext {
1019    /// Retrieve a context and verify its signature using the strict
1020    /// default [`VerificationPolicy`].
1021    pub async fn fetch(
1022        client: &RegistryClient,
1023        resolver: &WebResolver,
1024        ctx_id: &CtxId,
1025    ) -> Result<Self, AcdpError> {
1026        Self::fetch_with_policy(client, resolver, ctx_id, &VerificationPolicy::default()).await
1027    }
1028
1029    /// Retrieve a context and verify its signature with caller-controlled
1030    /// strictness.
1031    ///
1032    /// 1. Fetches `body + registry_state` from the registry.
1033    /// 2. Refuses a served body whose `ctx_id` differs from the one
1034    ///    requested (`AcdpError::ContextIdMismatch`) — this implements
1035    ///    RFC-ACDP-0006 §4.1 step 7 (NORMATIVE, "Bind the resolved
1036    ///    identity"): neither the signature check (step 5) nor the
1037    ///    `content_hash` recomputation (step 6) can supply this binding,
1038    ///    because `ctx_id` sits in the RFC-ACDP-0001 §5.7 registry-assigned
1039    ///    exclusion set and is therefore stripped from ProducerContent
1040    ///    before hashing. See RFC-ACDP-0008 §9.1 for the threat this
1041    ///    closes: without it, a registry can serve any other
1042    ///    validly-signed body by the same producer under the requested
1043    ///    context's URL, and both preceding checks still pass. Step 7
1044    ///    permits a consumer to surface "an equivalent typed error" in
1045    ///    place of the registry-side `cross_registry_resolution_failed`
1046    ///    wire code — `ContextIdMismatch` is that typed error. This
1047    ///    generalizes the receipt-path analogue at RFC-ACDP-0010 §8 step 3
1048    ///    to the receipt-less core-profile path, where it is the only
1049    ///    binding available. It does **not** close §9.1 in full: a
1050    ///    registry that genuinely republishes the same content under a
1051    ///    new `ctx_id` still passes; only serve-time substitution — a
1052    ///    different id claimed to be the one requested — is caught.
1053    /// 3. Optionally runs `validate_body` — structural schema checks
1054    ///    plus embedded-`DataRef` hash verification (policy-controlled).
1055    /// 4. Recomputes `content_hash` over ProducerContent.
1056    /// 5. Resolves the producer's DID document. `did:web` is required
1057    ///    unconditionally for v0.1.0 (RFC-ACDP-0001 §5.4).
1058    /// 6. Verifies the Ed25519 signature (or other supported algorithm).
1059    /// 7. Optionally verifies the `registry_receipt` placeholder.
1060    /// 8. Optionally rejects unknown statuses.
1061    pub async fn fetch_with_policy(
1062        client: &RegistryClient,
1063        resolver: &WebResolver,
1064        ctx_id: &CtxId,
1065        policy: &VerificationPolicy,
1066    ) -> Result<Self, AcdpError> {
1067        let ctx = client.retrieve(ctx_id).await?;
1068        let retrieved = Self::verify_retrieved(client, resolver, &ctx, ctx_id, policy).await?;
1069        Ok(retrieved.into_context(ctx))
1070    }
1071
1072    /// Retrieve the current head of a lineage
1073    /// (`GET /lineages/{lineage_id}/current`) and verify it with the
1074    /// strict default [`VerificationPolicy`] — including the
1075    /// lineage-head receipt when the registry minted one (ACDP 0.3,
1076    /// RFC-ACDP-0011).
1077    pub async fn fetch_current(
1078        client: &RegistryClient,
1079        resolver: &WebResolver,
1080        lineage_id: &acdp_types::primitives::LineageId,
1081    ) -> Result<Self, AcdpError> {
1082        Self::fetch_current_with_policy(
1083            client,
1084            resolver,
1085            lineage_id,
1086            &VerificationPolicy::default(),
1087        )
1088        .await
1089    }
1090
1091    /// Retrieve + verify the current head of a lineage with
1092    /// caller-controlled strictness.
1093    ///
1094    /// Runs the same pipeline as [`Self::fetch_with_policy`] against
1095    /// the `/current` response (the expected `ctx_id` is the served
1096    /// body's own — there is no requested identifier on this endpoint;
1097    /// the head receipt's §7 step 5 byte-match is what binds it), then
1098    /// applies `policy.lineage_head` to the response's
1099    /// `lineage_head_receipt` per RFC-ACDP-0011 §7:
1100    ///
1101    /// - [`ReceiptPolicy::Ignore`] — the raw value is preserved
1102    ///   verbatim, unverified.
1103    /// - [`ReceiptPolicy::VerifyIfPresent`] — verified when present
1104    ///   (absence is fine: the registry may not advertise
1105    ///   `acdp-registry-head-receipts`).
1106    /// - [`ReceiptPolicy::Require`] — fail closed with
1107    ///   `invalid_receipt` unless present AND verified.
1108    ///
1109    /// Verification fetches the registry's capabilities document for
1110    /// the §7 step 3 `capabilities.registry_did` binding. Staleness
1111    /// beyond `policy.lineage_head.max_age_seconds` is a *freshness*
1112    /// verdict reported via [`Self::head_receipt_stale`], never a
1113    /// verification failure (§6).
1114    ///
1115    /// [`Self::fetch_with_policy`] now additionally refuses a served body
1116    /// whose `ctx_id` is not the one requested (RFC-ACDP-0008 §9.1). This
1117    /// endpoint has no requested identifier to compare against — the
1118    /// served head's `ctx_id` is trivially "the one requested" — so on a
1119    /// receipt-less registry the served head's identity rests entirely on
1120    /// registry honesty (RFC-ACDP-0008 §9.1). Use [`ReceiptPolicy::Require`]
1121    /// where that matters.
1122    pub async fn fetch_current_with_policy(
1123        client: &RegistryClient,
1124        resolver: &WebResolver,
1125        lineage_id: &acdp_types::primitives::LineageId,
1126        policy: &VerificationPolicy,
1127    ) -> Result<Self, AcdpError> {
1128        let ctx = client.current(lineage_id).await?;
1129        let served_ctx_id = ctx.body.ctx_id.clone();
1130        let retrieved =
1131            Self::verify_retrieved(client, resolver, &ctx, &served_ctx_id, policy).await?;
1132
1133        // ── Lineage-head receipt phase (RFC-ACDP-0011) ──────────────
1134        let head_policy = policy.lineage_head.receipts;
1135        let head = match (head_policy, &ctx.lineage_head_receipt) {
1136            (ReceiptPolicy::Ignore, _)
1137            | (ReceiptPolicy::VerifyIfPresent | ReceiptPolicy::VerifyAndReport, None) => None,
1138            (ReceiptPolicy::Require, None) => {
1139                return Err(AcdpError::InvalidReceipt(
1140                    "policy requires a lineage-head receipt but the /current response \
1141                         carries none (registry without the acdp-registry-head-receipts \
1142                         profile?)"
1143                        .into(),
1144                ));
1145            }
1146            (_, Some(value)) => {
1147                let serving_authority = client
1148                    .authority()
1149                    .unwrap_or_else(|| served_ctx_id.authority().to_string());
1150                // §7 step 3 needs capabilities.registry_did — fetched
1151                // from the same authority the context came from.
1152                let caps = client.capabilities().await?;
1153                let verdict = super::receipt::verify_lineage_head_receipt_value(
1154                    value,
1155                    lineage_id,
1156                    &served_ctx_id,
1157                    ctx.body.version,
1158                    &ctx.registry_state.status,
1159                    true, // /current always serves the attested head
1160                    &serving_authority,
1161                    &caps.registry_did,
1162                    chrono::Duration::seconds(policy.lineage_head.max_clock_skew_seconds as i64),
1163                    resolver,
1164                )
1165                .await;
1166                match verdict {
1167                    Ok(receipt) => Some(Ok(receipt)),
1168                    Err(e) if head_policy == ReceiptPolicy::VerifyAndReport => Some(Err(e)),
1169                    Err(e) => return Err(e),
1170                }
1171            }
1172        };
1173        let (verified_head_receipt, head_receipt_verdict) = match head {
1174            None => (None, None),
1175            Some(Ok(receipt)) => (Some(receipt), Some(Ok(()))),
1176            Some(Err(e)) => (None, Some(Err(e))),
1177        };
1178        let head_receipt_stale = verified_head_receipt.as_ref().and_then(
1179            |receipt: &acdp_types::receipt::LineageHeadReceipt| {
1180                policy.lineage_head.max_age_seconds.map(|max| {
1181                    receipt.age_at(chrono::Utc::now()) > chrono::Duration::seconds(max as i64)
1182                })
1183            },
1184        );
1185
1186        let mut verified = retrieved.into_context(ctx);
1187        verified.verified_head_receipt = verified_head_receipt;
1188        verified.head_receipt_stale = head_receipt_stale;
1189        verified.head_receipt_verdict = head_receipt_verdict;
1190        Ok(verified)
1191    }
1192
1193    /// The shared retrieve-side verification pipeline: body schema,
1194    /// hash recomputation, RFC-ACDP-0010 receipt phase, signature
1195    /// phase (with the receipt-gated historical-key fallback), and the
1196    /// unknown-status policy check.
1197    #[cfg_attr(
1198        feature = "tracing",
1199        tracing::instrument(
1200            name = "acdp.verify_retrieved",
1201            skip_all,
1202            fields(ctx_id = %expected_ctx_id),
1203            err(Display)
1204        )
1205    )]
1206    async fn verify_retrieved(
1207        client: &RegistryClient,
1208        resolver: &WebResolver,
1209        ctx: &FullContext,
1210        expected_ctx_id: &CtxId,
1211        policy: &VerificationPolicy,
1212    ) -> VerifyRetrievedResult {
1213        // Identifier binding — RFC-ACDP-0006 §4.1 step 7 (NORMATIVE, "Bind
1214        // the resolved identity"): refuse a served body whose `ctx_id`
1215        // differs from the one requested, before any crypto or network
1216        // work. `ctx_id` is registry-assigned and outside both the
1217        // `content_hash` and signature coverage (RFC-ACDP-0001 §5.7's
1218        // exclusion set), so this equality check is the only binding
1219        // available when no receipt is served. See RFC-ACDP-0008 §9.1 for
1220        // the threat this closes; it does not close §9.1 in full (a
1221        // genuine republish under a new `ctx_id` still passes — only
1222        // serve-time substitution is caught). Step 7 permits a
1223        // consumer-side "equivalent typed error" in place of the
1224        // registry-side `cross_registry_resolution_failed` wire code —
1225        // `ContextIdMismatch` is that typed error.
1226        if ctx.body.ctx_id != *expected_ctx_id {
1227            return Err(AcdpError::ContextIdMismatch {
1228                requested: expected_ctx_id.as_str().to_string(),
1229                served: ctx.body.ctx_id.as_str().to_string(),
1230            });
1231        }
1232
1233        // Registry-assigned lineage/origin binding — RFC-ACDP-0004 §2.1
1234        // (0.5.0): `lineage_id` and `origin_registry` are outside
1235        // `content_hash`/signature coverage like `ctx_id`, so a first
1236        // version's derivation and the origin authority are checked here,
1237        // offline, before any crypto or network work.
1238        acdp_verify::verify_registry_assigned_bindings(&ctx.body)?;
1239
1240        if policy.validate_body_schema {
1241            acdp_validation::validate_body(&ctx.body)?;
1242        }
1243        if policy.require_did_web_for_v0_1_0 {
1244            require_did_web_for_v0_1_0(&ctx.body)?;
1245        }
1246
1247        // Hash recomputation first: from here on `ctx.body.content_hash`
1248        // IS the independently recomputed value, which the receipt
1249        // cross-check below relies on.
1250        // One DID-freshness scope for every lookup this verification makes
1251        // (RFC-ACDP-0001 §5.11 "Caching"): a document fetched at or after
1252        // `since` is fresh, so a forced re-fetch done for the receipt key
1253        // also serves the signature phase.
1254        let since = std::time::Instant::now();
1255        let verifier = Verifier::new(resolver).fresh_since(since);
1256        verifier.verify_context_hash(ctx)?;
1257
1258        // ── Receipt phase (RFC-ACDP-0010) ───────────────────────────
1259        // Verified BEFORE the signature phase because the historical-
1260        // key path is gated on a verified receipt.
1261        let serving_authority = client
1262            .authority()
1263            .unwrap_or_else(|| expected_ctx_id.authority().to_string());
1264        let receipt_outcome = match (policy.receipts, &ctx.registry_receipt) {
1265            (ReceiptPolicy::Ignore, _)
1266            | (ReceiptPolicy::VerifyIfPresent | ReceiptPolicy::VerifyAndReport, None) => None,
1267            (ReceiptPolicy::Require, None) => {
1268                return Err(AcdpError::InvalidReceipt(
1269                    "policy requires a registry receipt but the response carries none \
1270                     (registry without the acdp-registry-receipts profile, or a \
1271                     pre-receipts context)"
1272                        .into(),
1273                ));
1274            }
1275            (_, Some(value)) => {
1276                let fingerprint = acdp_crypto::fingerprint::fingerprint_for_key_id_since(
1277                    &ctx.body.signature.key_id,
1278                    &ctx.body.signature.algorithm,
1279                    resolver,
1280                    since,
1281                )
1282                .await?;
1283                let verdict = super::receipt::verify_receipt_value_with_status_since(
1284                    value,
1285                    expected_ctx_id,
1286                    &ctx.body,
1287                    &ctx.body.content_hash,
1288                    &fingerprint,
1289                    &serving_authority,
1290                    resolver,
1291                    since,
1292                )
1293                .await;
1294                match verdict {
1295                    Ok(placed) => Some(Ok(placed)),
1296                    // RFC-ACDP-0010 §8 (0.5.0): reported separately, then
1297                    // treated exactly as an absent receipt below.
1298                    Err(e) if policy.receipts == ReceiptPolicy::VerifyAndReport => Some(Err(e)),
1299                    Err(e) => return Err(e),
1300                }
1301            }
1302        };
1303        let (verified_receipt, receipt_key_status, receipt_verdict) = match receipt_outcome {
1304            None => (None, None, None),
1305            Some(Ok((receipt, status))) => (Some(receipt), Some(status), Some(Ok(()))),
1306            Some(Err(e)) => (None, None, Some(Err(e))),
1307        };
1308
1309        // ── Revocation phase (RFC-ACDP-0014 §7/§8) ──────────────────
1310        // `crate::revocation_verdict` gathers `known` + cached facts +
1311        // (when configured) §8 discovery, scopes them to this producer
1312        // (0.5.0 "Producer scope"), and decides the verdict. Cached facts
1313        // are read before discovery runs, so they survive any failure an
1314        // attacker can induce on this call (anti-rollback). Runs after the
1315        // receipt phase because §7 step 1 accepts ONLY a receipt-attested
1316        // publish time — and under the strict profile only one from a
1317        // *current* receipt key. Discovered revocation bodies are verified
1318        // with `Verifier::verify_body`, never `verify_retrieved`, so this
1319        // does not recurse.
1320        //
1321        // Discovery puts a Tokio time-driver requirement on this path
1322        // (`total_timeout`), gated behind `discover: Some`.
1323        let gathered = super::revocation_verdict::gather(
1324            client,
1325            resolver,
1326            &ctx.body.agent_id,
1327            &policy.revocations,
1328        )
1329        .await;
1330        let fingerprint = if gathered.has_in_scope() {
1331            Some(
1332                acdp_crypto::fingerprint::fingerprint_for_key_id_since(
1333                    &ctx.body.signature.key_id,
1334                    &ctx.body.signature.algorithm,
1335                    resolver,
1336                    since,
1337                )
1338                .await?,
1339            )
1340        } else {
1341            None
1342        };
1343        let revocation = super::revocation_verdict::decide(
1344            gathered,
1345            fingerprint.as_deref(),
1346            verified_receipt
1347                .as_ref()
1348                .zip(receipt_key_status)
1349                .map(|(r, status)| (r.created_at, status)),
1350            policy.revocations.accept_historical_receipt_key_for_pre_t,
1351        )
1352        .enforce()?;
1353
1354        // ── Signature phase ──────────────────────────────────────────
1355        // Standard path enforces assertionMethod membership. A
1356        // KeyNotAuthorized failure falls back to the historical path
1357        // only under AcceptWithReceipt AND a verified receipt — the
1358        // receipt's key_fingerprint (already cross-checked against this
1359        // exact key above) is what attests publish-time authorization.
1360        let key_status = match revocation.pre_compromise() {
1361            // Pre-compromise (§7 step 2): the signature is verified
1362            // under the RFC-ACDP-0010 §10 historical rule — the key may
1363            // legitimately have left assertionMethod (and SHOULD, §9),
1364            // and even a key still in assertionMethod MUST NOT be
1365            // reported as fully current once revoked. did:key material
1366            // cannot rotate, so it takes the plain envelope path.
1367            true => {
1368                if ctx.body.agent_id.as_str().starts_with("did:key:") {
1369                    verifier.verify_body_signature(&ctx.body).await?;
1370                } else {
1371                    verifier.verify_body_signature_historical(&ctx.body).await?;
1372                }
1373                KeyAuthorization::HistoricallyAuthorizedPreCompromise
1374            }
1375            false => match verifier.verify_body_signature(&ctx.body).await {
1376                Ok(()) => KeyAuthorization::CurrentlyAuthorized,
1377                Err(AcdpError::KeyNotAuthorized(_))
1378                    if policy.historical_keys == HistoricalKeyPolicy::AcceptWithReceipt
1379                        && verified_receipt.is_some() =>
1380                {
1381                    verifier.verify_body_signature_historical(&ctx.body).await?;
1382                    KeyAuthorization::HistoricallyAuthorized
1383                }
1384                Err(e) => return Err(e),
1385            },
1386        };
1387
1388        if !policy.allow_unknown_status {
1389            if let Some(other) = ctx.registry_state.status.as_other() {
1390                return Err(AcdpError::SchemaViolation(format!(
1391                    "policy.allow_unknown_status=false; registry returned '{other}'"
1392                )));
1393            }
1394        }
1395
1396        // ── Transparency phase (RFC-ACDP-0012 §9, RFC-ACDP-0015 §8) ──
1397        // Runs last: the leaf is rebuilt only from material verified
1398        // above (recomputed content_hash, verified receipt). Its verdicts
1399        // are independent of the ones above (§9.3), and under the default
1400        // policies they never fail verification.
1401        // Without a verified receipt the inclusion is cannot-verify (spec
1402        // #78 L1), attributed to the receipt state.
1403        let material = match (&verified_receipt, &ctx.registry_receipt, &receipt_verdict) {
1404            (Some(receipt), Some(receipt_value), _) => Ok(super::transparency::LeafMaterial {
1405                receipt,
1406                receipt_value,
1407            }),
1408            (_, None, _) => Err(CannotVerifyReason::ReceiptAbsent),
1409            (_, Some(_), Some(Err(_))) => Err(CannotVerifyReason::ReceiptInvalid),
1410            (_, Some(_), _) => Err(CannotVerifyReason::ReceiptNotVerified),
1411        };
1412        let transparency = super::transparency::evaluate(
1413            client,
1414            ctx,
1415            material,
1416            &serving_authority,
1417            policy.log_inclusion,
1418            policy.witness_quorum.as_ref(),
1419            resolver,
1420        )
1421        .await?;
1422
1423        let lineage_binding = acdp_verify::lineage_binding(&ctx.body, verified_receipt.is_some());
1424        Ok(Retrieved {
1425            key_status,
1426            verified_receipt,
1427            receipt_key_status,
1428            receipt_verdict,
1429            lineage_binding,
1430            revocation,
1431            transparency,
1432        })
1433    }
1434
1435    /// Retrieve + verify, returning a structured [`VerificationReport`]
1436    /// alongside the verified context. Does NOT attempt external
1437    /// `DataRef` fetches — use [`Self::fetch_report_with_fetcher`] for
1438    /// that. Each `data_ref_external` slot in the returned report is
1439    /// `None`.
1440    ///
1441    /// Unlike [`Self::fetch_with_policy`], per-`DataRef` embedded-hash
1442    /// failures are recorded in the report instead of aborting the
1443    /// verification. The top-level checks (schema, body hash,
1444    /// signature) remain hard-fail: if any of them fails, the method
1445    /// returns an `AcdpError` and produces no report.
1446    ///
1447    /// For diagnostic callers that want a populated report even when
1448    /// a top-level check fails (e.g. an audit walker that needs to
1449    /// distinguish "wrong hash" from "wrong signature"), use
1450    /// [`Self::fetch_report_diagnose`] instead.
1451    pub async fn fetch_report(
1452        client: &RegistryClient,
1453        resolver: &WebResolver,
1454        ctx_id: &CtxId,
1455        policy: &VerificationPolicy,
1456    ) -> Result<(Self, VerificationReport), AcdpError> {
1457        Self::fetch_report_inner::<NoFetcher>(client, resolver, ctx_id, policy, None).await
1458    }
1459
1460    /// Diagnostic variant of [`Self::fetch_report`] that never
1461    /// short-circuits on a top-level failure — schema, body-hash, and
1462    /// signature outcomes are each recorded individually in the
1463    /// returned [`VerificationReport`]. Returns `Ok((None, report))`
1464    /// when any top-level probe failed (the report shows which one);
1465    /// `Ok((Some(verified), report))` only when every check passed
1466    /// (FEAT-05) — and "every check" now genuinely means every
1467    /// authorization phase (receipt, revocation, signature/
1468    /// historical-key, unknown-status), not just the top-level probes:
1469    /// once the probes pass, this method additionally runs the same
1470    /// `verify_retrieved` phase `fetch_with_policy` does, and withholds
1471    /// the handle — recording the cause in
1472    /// [`VerificationReport::policy_phase_error`] — if that phase fails
1473    /// too. Either way the method still returns `Ok`; it never converts
1474    /// a policy-phase failure into an `Err`.
1475    ///
1476    /// Use cases:
1477    /// - Audit walkers that need to classify failures by stage.
1478    /// - Admin tooling that wants to distinguish "hash mismatch"
1479    ///   (probable tampering / encoding drift) from "signature
1480    ///   verification failed" (key compromise / DID resolution
1481    ///   problem).
1482    ///
1483    /// Network errors from the initial retrieval still propagate as
1484    /// `Err` — there's no body to inspect when the registry is
1485    /// unreachable. But network/DID-resolution errors that occur
1486    /// *inside* the `verify_retrieved` phase (e.g. resolving the
1487    /// fingerprint for a receipt cross-check, or the historical-key
1488    /// fallback) are caught there and land in
1489    /// [`VerificationReport::policy_phase_error`] instead of `Err`,
1490    /// same as any other phase failure — this method never
1491    /// short-circuits once retrieval has succeeded. That means a
1492    /// transient network flake at that stage can read as a policy
1493    /// rejection (`Ok((None, report))`) rather than an `Err`. A caller
1494    /// that needs to tell a flake from a genuine rejection should
1495    /// inspect `policy_phase_error`'s [`AcdpError::is_transient`].
1496    ///
1497    /// Stage-classification caveat: `verify_retrieved` (and therefore the
1498    /// receipt/revocation/signature/historical-key phases it runs) is only
1499    /// attempted once ALL top-level probes pass, `ctx_id_ok` included — see
1500    /// `all_top_level_pass` below. So when `ctx_id_ok` is `false`,
1501    /// `policy_phase_error` stays `None` even if the served body also
1502    /// carries a receipt that would independently fail its own cross-check
1503    /// (e.g. a receipt genuinely bound to the *served*, substituted body —
1504    /// RFC-ACDP-0010 §8 step 3 — rather than the requested one). A caller
1505    /// classifying a `ctx_id_ok: false` report should not read a `None`
1506    /// `policy_phase_error` as "the receipt/signature phases passed" — they
1507    /// were never attempted.
1508    pub async fn fetch_report_diagnose(
1509        client: &RegistryClient,
1510        resolver: &WebResolver,
1511        ctx_id: &CtxId,
1512        policy: &VerificationPolicy,
1513    ) -> Result<(Option<Self>, VerificationReport), AcdpError> {
1514        let ctx = client.retrieve(ctx_id).await?;
1515        let mut report = VerificationReport {
1516            body_hash_ok: false,
1517            signature_ok: false,
1518            schema_ok: false,
1519            data_ref_embedded: Vec::with_capacity(ctx.body.data_refs.len()),
1520            data_ref_external: Vec::with_capacity(ctx.body.data_refs.len()),
1521            ctx_id_ok: ctx.body.ctx_id == *ctx_id,
1522            key_status: None,
1523            policy_phase_error: None,
1524            revocation_discovery: None,
1525            receipt_key_status: None,
1526            receipt_verdict: None,
1527            lineage_binding: None,
1528            revocation_verdict: None,
1529            revocation_hints: Vec::new(),
1530            log_inclusion_verdict: None,
1531            witness_quorum: None,
1532        };
1533
1534        // Schema (structural) — record pass/fail.
1535        if policy.validate_body_schema {
1536            match acdp_validation::validate_body_structural(&ctx.body) {
1537                Ok(()) => report.schema_ok = true,
1538                Err(_) => { /* keep schema_ok=false; continue collecting */ }
1539            }
1540        } else {
1541            report.schema_ok = true;
1542        }
1543
1544        // Per-DataRef embedded hashes — same as fetch_report_inner.
1545        for dr in &ctx.body.data_refs {
1546            if let Some(emb) = &dr.embedded {
1547                if dr.content_hash.is_some() || emb.content_hash.is_some() {
1548                    let outcome = acdp_validation::verify_embedded_hash(dr).and_then(|()| {
1549                        acdp_validation::embedded_decoded_bytes(emb).map(|b| b.len())
1550                    });
1551                    report.data_ref_embedded.push(outcome);
1552                } else {
1553                    report.data_ref_embedded.push(Ok(0));
1554                }
1555            } else {
1556                report.data_ref_embedded.push(Ok(0));
1557            }
1558        }
1559
1560        // Hash + signature recorded independently (FEAT-05).
1561        let verifier = Verifier::new(resolver);
1562        report.body_hash_ok = verifier.verify_context_hash(&ctx).is_ok();
1563        report.signature_ok = verifier.verify_body_signature(&ctx.body).await.is_ok();
1564
1565        // External fetches were not attempted (this method has no
1566        // fetcher param — diagnostic callers can wire their own).
1567        for _ in &ctx.body.data_refs {
1568            report.data_ref_external.push(None);
1569        }
1570
1571        // Decide whether to surface the verified handle. The probes above
1572        // are diagnostic — their whole value is continuing past failure —
1573        // but the handle is a trust assertion (`VerifiedContext`'s
1574        // invariant: "the accessors below can be trusted without
1575        // re-deriving anything"), so it is only ever issued once the real
1576        // authorization phases (receipt, revocation, signature/historical,
1577        // unknown-status) have actually run and passed through
1578        // `verify_retrieved` — never on the probes alone.
1579        let all_top_level_pass =
1580            report.schema_ok && report.body_hash_ok && report.signature_ok && report.ctx_id_ok;
1581        let verified = if all_top_level_pass {
1582            // The call MUST be hoisted out of the `match` scrutinee: in a
1583            // match, scrutinee temporaries live to the end of the match,
1584            // so the awaited future would still be holding `&ctx` inside
1585            // the arms and `Self { inner: ctx, .. }` below would fail
1586            // borrowck (E0505).
1587            let outcome = Self::verify_retrieved(
1588                client,
1589                resolver,
1590                &ctx,
1591                ctx_id,
1592                &policy.derived_for_report(),
1593            )
1594            .await; // borrow of `ctx` ends here
1595            match outcome {
1596                Ok(retrieved) => {
1597                    retrieved.record(&mut report);
1598                    Some(retrieved.into_context(ctx))
1599                }
1600                Err(e) => {
1601                    // Reports; never short-circuits — `fetch_report_diagnose`
1602                    // still returns `Ok` in every case it does today.
1603                    report.policy_phase_error = Some(e);
1604                    None
1605                }
1606            }
1607        } else {
1608            None
1609        };
1610        Ok((verified, report))
1611    }
1612
1613    /// Retrieve + verify like [`Self::fetch_report`], and additionally
1614    /// fetch every `DataRef` whose `location` resolves through `fetcher`.
1615    /// Each external fetch outcome is recorded in `report.data_ref_external`.
1616    pub async fn fetch_report_with_fetcher<F: DataRefFetcher>(
1617        client: &RegistryClient,
1618        resolver: &WebResolver,
1619        ctx_id: &CtxId,
1620        policy: &VerificationPolicy,
1621        fetcher: &F,
1622    ) -> Result<(Self, VerificationReport), AcdpError> {
1623        Self::fetch_report_inner(client, resolver, ctx_id, policy, Some(fetcher)).await
1624    }
1625
1626    async fn fetch_report_inner<F: DataRefFetcher>(
1627        client: &RegistryClient,
1628        resolver: &WebResolver,
1629        ctx_id: &CtxId,
1630        policy: &VerificationPolicy,
1631        fetcher: Option<&F>,
1632    ) -> Result<(Self, VerificationReport), AcdpError> {
1633        let ctx = client.retrieve(ctx_id).await?;
1634
1635        // Identifier binding — RFC-ACDP-0006 §4.1 step 7 (NORMATIVE, "Bind
1636        // the resolved identity"). Same check as `verify_retrieved`,
1637        // applied here (in addition to `verify_retrieved`'s own re-check
1638        // below) so this fails before schema validation too — the early
1639        // copy preserves fail-before-schema ordering that
1640        // `tests/receipts.rs` depends on.
1641        if ctx.body.ctx_id != *ctx_id {
1642            return Err(AcdpError::ContextIdMismatch {
1643                requested: ctx_id.as_str().to_string(),
1644                served: ctx.body.ctx_id.as_str().to_string(),
1645            });
1646        }
1647
1648        let mut report = VerificationReport {
1649            body_hash_ok: false,
1650            signature_ok: false,
1651            schema_ok: false,
1652            data_ref_embedded: Vec::with_capacity(ctx.body.data_refs.len()),
1653            data_ref_external: Vec::with_capacity(ctx.body.data_refs.len()),
1654            ctx_id_ok: true,
1655            key_status: None,
1656            policy_phase_error: None,
1657            revocation_discovery: None,
1658            receipt_key_status: None,
1659            receipt_verdict: None,
1660            lineage_binding: None,
1661            revocation_verdict: None,
1662            revocation_hints: Vec::new(),
1663            log_inclusion_verdict: None,
1664            witness_quorum: None,
1665        };
1666
1667        // Structural-only schema validation — embedded-hash checks are
1668        // intentionally skipped here so per-DataRef hash failures land
1669        // in the report (below) instead of short-circuiting the whole
1670        // verification. That's the diagnostic shape `fetch_report`
1671        // promises in its docstring.
1672        if policy.validate_body_schema {
1673            acdp_validation::validate_body_structural(&ctx.body)?;
1674        }
1675        report.schema_ok = true;
1676
1677        // Per-DataRef embedded-hash outcomes — recorded individually.
1678        for dr in &ctx.body.data_refs {
1679            if let Some(emb) = &dr.embedded {
1680                if dr.content_hash.is_some() || emb.content_hash.is_some() {
1681                    let outcome = acdp_validation::verify_embedded_hash(dr).and_then(|()| {
1682                        acdp_validation::embedded_decoded_bytes(emb).map(|b| b.len())
1683                    });
1684                    report.data_ref_embedded.push(outcome);
1685                } else {
1686                    report.data_ref_embedded.push(Ok(0));
1687                }
1688            } else {
1689                report.data_ref_embedded.push(Ok(0));
1690            }
1691        }
1692
1693        // Delegate the remaining phases — content_hash recomputation,
1694        // RFC-ACDP-0010 receipt, RFC-ACDP-0014 revocation, signature (with
1695        // the historical-key fallback), and the unknown-status check — to
1696        // `verify_retrieved`, the sole reader of those policy fields. The
1697        // derived policy forces `validate_body_schema` off (P1 was already
1698        // handled, structurally-only, above) and passes everything else
1699        // through verbatim — see `VerificationPolicy::derived_for_report`.
1700        let retrieved =
1701            Self::verify_retrieved(client, resolver, &ctx, ctx_id, &policy.derived_for_report())
1702                .await?;
1703        report.body_hash_ok = true;
1704        report.signature_ok = true;
1705        retrieved.record(&mut report);
1706
1707        // External fetches — record per-ref outcomes when a fetcher is
1708        // supplied; otherwise leave each slot as `None` so callers can
1709        // distinguish "skipped" from "failed".
1710        for dr in &ctx.body.data_refs {
1711            let slot: Option<Result<usize, AcdpError>> = match (fetcher, &dr.location) {
1712                (Some(f), Some(_)) => Some(fetch_and_verify_data_ref(dr, f).await.map(|b| b.len())),
1713                _ => None,
1714            };
1715            report.data_ref_external.push(slot);
1716        }
1717
1718        Ok((retrieved.into_context(ctx), report))
1719    }
1720
1721    pub fn body(&self) -> &acdp_types::body::Body {
1722        &self.inner.body
1723    }
1724
1725    pub fn registry_state(&self) -> &acdp_types::body::RegistryState {
1726        &self.inner.registry_state
1727    }
1728
1729    /// The verified [`FullContext`] (body + registry state + any
1730    /// receipts) in its retrieval shape. Every field was reached only
1731    /// after this context's hash + signature were verified.
1732    pub fn full_context(&self) -> &FullContext {
1733        &self.inner
1734    }
1735
1736    /// Whether the body verified against a currently authorized key, a
1737    /// receipt-attested historical one, or a receipt-attested
1738    /// pre-compromise one (ACDP 0.2 WS-B / RFC-ACDP-0014 §7). This is
1739    /// the real verdict regardless of which `fetch*`/`fetch_report*`
1740    /// entry point produced this `VerifiedContext` — every construction
1741    /// path runs the same `verify_retrieved` phase to derive it.
1742    pub fn key_status(&self) -> KeyAuthorization {
1743        self.key_status
1744    }
1745
1746    /// The verified registry receipt (RFC-ACDP-0010), when one was
1747    /// present and the policy verified it. `None` under
1748    /// [`ReceiptPolicy::Ignore`] or when the registry minted none — this
1749    /// is exhaustive; there is no additional "or you used a report path"
1750    /// carve-out, since `fetch_report`/`fetch_report_with_fetcher`/
1751    /// `fetch_report_diagnose` verify the receipt exactly like
1752    /// `fetch_with_policy` does. For the raw on-wire value see
1753    /// [`Self::receipt`].
1754    pub fn verified_receipt(&self) -> Option<&acdp_types::receipt::RegistryReceipt> {
1755        self.verified_receipt.as_ref()
1756    }
1757
1758    /// RFC-ACDP-0010 §8 step 1 status of the key that signed the
1759    /// verified receipt (0.5.0): [`ReceiptKeyStatus::Current`] when it is
1760    /// in the registry DID document's `assertionMethod`,
1761    /// [`ReceiptKeyStatus::Historical`] when it is in `verificationMethod`
1762    /// only. A historical receipt is not a currently-authorized registry
1763    /// attestation and, under the strict profile, cannot place a
1764    /// revoked-key context before its boundary. `None` exactly when
1765    /// [`Self::verified_receipt`] is `None`.
1766    ///
1767    /// [`ReceiptKeyStatus::Current`]: acdp_types::receipt::ReceiptKeyStatus::Current
1768    /// [`ReceiptKeyStatus::Historical`]: acdp_types::receipt::ReceiptKeyStatus::Historical
1769    pub fn receipt_key_status(&self) -> Option<acdp_types::receipt::ReceiptKeyStatus> {
1770        self.receipt_key_status
1771    }
1772
1773    /// The registry-receipt verdict, reported separately from the body
1774    /// verdict (RFC-ACDP-0010 §8, 0.5.0). `None` when no receipt was
1775    /// evaluated (none served, or [`ReceiptPolicy::Ignore`]);
1776    /// `Some(Ok(()))` when it verified; `Some(Err(_))` only under
1777    /// [`ReceiptPolicy::VerifyAndReport`] — the other policies turn a
1778    /// failing receipt into the call's `Err`.
1779    pub fn receipt_verdict(&self) -> Option<&Result<(), AcdpError>> {
1780        self.receipt_verdict.as_ref()
1781    }
1782
1783    /// How `body.lineage_id` is bound (RFC-ACDP-0004 §2.1, 0.5.0):
1784    /// derived offline for a first version, attested by the verified
1785    /// receipt for a later one, or registry-asserted only (`Unbound`).
1786    pub fn lineage_binding(&self) -> acdp_verify::LineageBinding {
1787        self.lineage_binding
1788    }
1789
1790    /// The lineage-head receipt verdict (RFC-ACDP-0011 §7), reported
1791    /// separately; `Some(Err(_))` only under
1792    /// [`ReceiptPolicy::VerifyAndReport`] on [`LineageHeadPolicy::receipts`].
1793    pub fn head_receipt_verdict(&self) -> Option<&Result<(), AcdpError>> {
1794        self.head_receipt_verdict.as_ref()
1795    }
1796
1797    /// The verified lineage-head receipt (ACDP 0.3, RFC-ACDP-0011),
1798    /// populated only by [`Self::fetch_current`] /
1799    /// [`Self::fetch_current_with_policy`] when one was present and the
1800    /// policy verified it. For the raw on-wire value see
1801    /// [`Self::lineage_head_receipt`].
1802    pub fn verified_head_receipt(&self) -> Option<&acdp_types::receipt::LineageHeadReceipt> {
1803        self.verified_head_receipt.as_ref()
1804    }
1805
1806    /// RFC-ACDP-0011 §6 freshness verdict for the verified head
1807    /// receipt: `Some(true)` when the (genuine, verified) receipt's
1808    /// `as_of` is older than [`LineageHeadPolicy::max_age_seconds`];
1809    /// `Some(false)` when within policy; `None` when there is no
1810    /// verified head receipt or the max-age knob is disabled.
1811    pub fn head_receipt_stale(&self) -> Option<bool> {
1812        self.head_receipt_stale
1813    }
1814
1815    /// RFC-ACDP-0014 §8 auto-discovery failure that
1816    /// [`DiscoveryFailurePolicy::ProceedWithKnown`] swallowed to let
1817    /// this `VerifiedContext` exist at all. `None` when discovery was
1818    /// off ([`RevocationPolicy::discover`] is `None`), succeeded, or
1819    /// was never attempted — a [`DiscoveryFailurePolicy::FailClosed`]
1820    /// failure turns into this call's `Err` instead, so there is no
1821    /// `VerifiedContext` to carry it in that case. See
1822    /// [`VerificationReport::revocation_discovery`] for the twin
1823    /// surface on the report family, populated from the same event on
1824    /// the `fetch_report*` paths.
1825    pub fn revocation_discovery_failure(&self) -> Option<&AcdpError> {
1826        self.revocation_discovery_failure.as_ref()
1827    }
1828
1829    /// The typed revocation verdict for this context's signing key
1830    /// (RFC-ACDP-0014 §7/§8, 0.5.0): [`RevocationVerdict::Revoked`] with
1831    /// [`RevocationEffect::PreCompromise`](crate::RevocationEffect::PreCompromise)
1832    /// (a refusal never yields a `VerifiedContext` — it is
1833    /// [`AcdpError::KeyRevoked`]), [`RevocationVerdict::NotRevoked`], or —
1834    /// only under [`DiscoveryFailurePolicy::ProceedWithKnown`] —
1835    /// [`RevocationVerdict::Unknown`].
1836    pub fn revocation_verdict(&self) -> &RevocationVerdict {
1837        &self.revocation_verdict
1838    }
1839
1840    /// Verified revocations that do not speak for this context's producer
1841    /// (RFC-ACDP-0014 §7 "Producer scope", 0.5.0) — reported as hints,
1842    /// never applied to the verdict.
1843    pub fn revocation_hints(&self) -> &[SourcedRevocation] {
1844        &self.revocation_hints
1845    }
1846
1847    /// The RFC-ACDP-0012 §9 transparency-log inclusion verdict, reported
1848    /// separately from the body, receipt and revocation verdicts (§9.3:
1849    /// log-proof failure "invalidates nothing else").
1850    ///
1851    /// - `None`: not evaluated. Either the policy is
1852    ///   [`LogInclusionPolicy::Ignore`] with no witness policy, or the
1853    ///   response carried no `log_inclusion`.
1854    /// - [`LogInclusionVerdict::Included`]: the proof verified. The
1855    ///   context is included in the log the registry committed to; see
1856    ///   [`Self::verified_log_inclusion`].
1857    /// - [`LogInclusionVerdict::CannotVerify`]: no verified receipt to
1858    ///   rebuild the leaf from. Not logged, and not a log failure.
1859    /// - [`LogInclusionVerdict::Invalid`]: the proof was checked and
1860    ///   failed (`invalid_log_proof`).
1861    ///
1862    /// Under the default policy, no verdict fails verification.
1863    #[must_use]
1864    pub fn log_inclusion_verdict(&self) -> Option<&LogInclusionVerdict> {
1865        self.transparency.log.as_ref()
1866    }
1867
1868    /// The verified inclusion proof, including the signed checkpoint, when
1869    /// [`Self::log_inclusion_verdict`] is
1870    /// [`LogInclusionVerdict::Included`]. Keep the checkpoint to check
1871    /// consistency with later ones (RFC-ACDP-0012 §9.2).
1872    #[must_use]
1873    pub fn verified_log_inclusion(&self) -> Option<&acdp_types::log::LogInclusion> {
1874        self.transparency
1875            .log
1876            .as_ref()
1877            .and_then(LogInclusionVerdict::inclusion)
1878    }
1879
1880    /// The RFC-ACDP-0015 §8 witness-quorum verdict over the verified
1881    /// checkpoint.
1882    /// - `None`: [`VerificationPolicy::witness_quorum`] was unset.
1883    /// - `Some(Err(_))`: there was no verified checkpoint to corroborate
1884    ///   (`invalid_log_proof`). The checkpoint is verified on its own, so
1885    ///   a cannot-verify inclusion still has a quorum when its checkpoint
1886    ///   verifies.
1887    /// - `Some(Ok(report))`: the quorum was evaluated.
1888    ///
1889    /// Read the quorum from the report:
1890    /// - [`WitnessQuorumReport::meets_quorum`] is the split-view and
1891    ///   anti-rewrite quorum;
1892    /// - [`WitnessQuorumReport::meets_fresh_quorum`] is the quorum for
1893    ///   decisions that need a current checkpoint.
1894    #[must_use]
1895    pub fn witness_quorum(&self) -> Option<&Result<WitnessQuorumReport, AcdpError>> {
1896        self.transparency.witness.as_ref()
1897    }
1898
1899    /// Raw registry receipt value as served on the wire
1900    /// (RFC-ACDP-0010), preserved verbatim. For the verified, typed
1901    /// form see [`Self::verified_receipt`].
1902    pub fn receipt(&self) -> Option<&serde_json::Value> {
1903        self.inner.registry_receipt.as_ref()
1904    }
1905
1906    /// Raw lineage-head receipt value as served on the wire
1907    /// (RFC-ACDP-0011), preserved verbatim. For the verified, typed
1908    /// form see [`Self::verified_head_receipt`].
1909    pub fn lineage_head_receipt(&self) -> Option<&serde_json::Value> {
1910        self.inner.lineage_head_receipt.as_ref()
1911    }
1912
1913    /// Verify the registry receipt, when one is present
1914    /// (RFC-ACDP-0010).
1915    ///
1916    /// Standalone variant for contexts obtained via the report paths;
1917    /// `fetch_with_policy` already does this under
1918    /// [`ReceiptPolicy::VerifyIfPresent`]/`Require`. The serving
1919    /// authority is taken from the context's own `ctx_id` — this method
1920    /// performs no requested-id binding of its own (it has no requested
1921    /// id to compare against; it only ever sees `self.inner.body.ctx_id`),
1922    /// so deriving the serving authority this way is sound only for a
1923    /// `VerifiedContext` obtained through a pipeline that already bound
1924    /// the served `ctx_id` to the one requested. Every construction path
1925    /// does: `fetch_with_policy` and `CrossRegistryResolver::resolve`
1926    /// check it directly; `fetch_current_with_policy` does too,
1927    /// tautologically, since `/current` has no requested id to diverge
1928    /// from; `fetch_report`/`fetch_report_with_fetcher` check it and
1929    /// return `ContextIdMismatch` on failure; and `fetch_report_diagnose`
1930    /// folds it into its `all_top_level_pass` gate, so it only ever
1931    /// hands back `Some(VerifiedContext)` when `ctx_id_ok` held. All of
1932    /// these implement RFC-ACDP-0006 §4.1 step 7, so the type invariant
1933    /// — every `VerifiedContext` was bound to its requested `ctx_id` —
1934    /// holds unconditionally.
1935    ///
1936    /// Returns `Ok(None)` when no receipt is present, `Ok(Some(_))`
1937    /// with the verified receipt otherwise.
1938    ///
1939    /// The receipt cross-check (RFC-ACDP-0010 §8 step 4) relies on
1940    /// `body.content_hash` being the independently recomputed value.
1941    /// That is guaranteed by the type invariant — every
1942    /// `VerifiedContext` is built only after its constructing pipeline
1943    /// verified the body hash (`Verifier::verify_body_hash` /
1944    /// `verify_body_signed`), and the fields are private so no caller
1945    /// can substitute an unverified body — so no re-derivation is
1946    /// needed here.
1947    pub async fn verify_receipt(
1948        &self,
1949        resolver: &WebResolver,
1950    ) -> Result<Option<acdp_types::receipt::RegistryReceipt>, AcdpError> {
1951        let Some(value) = &self.inner.registry_receipt else {
1952            return Ok(None);
1953        };
1954        let fingerprint = acdp_crypto::fingerprint::fingerprint_for_key_id(
1955            &self.inner.body.signature.key_id,
1956            &self.inner.body.signature.algorithm,
1957            resolver,
1958        )
1959        .await?;
1960        let receipt = super::receipt::verify_receipt_value(
1961            value,
1962            &self.inner.body.ctx_id,
1963            &self.inner.body,
1964            &self.inner.body.content_hash,
1965            &fingerprint,
1966            self.inner.body.ctx_id.authority(),
1967            resolver,
1968        )
1969        .await?;
1970        Ok(Some(receipt))
1971    }
1972
1973    /// Re-assess this context's revocation status under `policy` without
1974    /// refetching the context (RFC-ACDP-0014 §7/§8) — for a long-lived
1975    /// holder of a `VerifiedContext` that must notice a revocation
1976    /// published after it verified.
1977    ///
1978    /// Derives the two inputs of
1979    /// [`find_revocations_verdict`](crate::find_revocations_verdict) from
1980    /// this context: the signing key's RFC-ACDP-0010 §6 fingerprint
1981    /// (resolved through `resolver`, normally a DID-cache hit) and the
1982    /// placement fixed at verification time
1983    /// ([`Self::verified_receipt`]'s `created_at` with
1984    /// [`Self::receipt_key_status`]). Never fails on a verdict; call
1985    /// [`RevocationAssessment::enforce`](crate::RevocationAssessment::enforce)
1986    /// to turn a refusal or a fail-closed `unknown` into an error. `Err`
1987    /// only when the signing key can no longer be resolved.
1988    pub async fn recheck_revocation(
1989        &self,
1990        client: &RegistryClient,
1991        resolver: &WebResolver,
1992        policy: &RevocationPolicy,
1993    ) -> Result<crate::RevocationAssessment, AcdpError> {
1994        let fingerprint = acdp_crypto::fingerprint::fingerprint_for_key_id(
1995            &self.inner.body.signature.key_id,
1996            &self.inner.body.signature.algorithm,
1997            resolver,
1998        )
1999        .await?;
2000        let placement = self
2001            .verified_receipt
2002            .as_ref()
2003            .zip(self.receipt_key_status)
2004            .map(|(r, status)| (r.created_at, status));
2005        crate::find_revocations_verdict(
2006            client,
2007            resolver,
2008            &self.inner.body.agent_id,
2009            &fingerprint,
2010            placement,
2011            policy,
2012        )
2013        .await
2014    }
2015}
2016
2017/// Structured diagnostic outcome from [`VerifiedContext::fetch_report`].
2018///
2019/// Top-level booleans report the per-stage outcome of the verification
2020/// pipeline. Per-`DataRef` slots track outcomes for each entry in
2021/// `body.data_refs`, in declaration order:
2022///
2023/// - `data_ref_embedded[i]` — `Ok(decoded_size_bytes)` when the embedded
2024///   payload's `content_hash` matched; `Err` when it didn't (or the
2025///   embedded was malformed). Refs without an embedded payload or
2026///   without a declared `content_hash` produce `Ok(0)`.
2027/// - `data_ref_external[i]` — `None` when no external fetch was
2028///   attempted (either no `location` or no `fetcher` was provided);
2029///   `Some(Ok(bytes_len))` when the fetch + hash succeeded;
2030///   `Some(Err(_))` on any failure (SSRF rejection, hash mismatch,
2031///   timeout, …).
2032///
2033/// `AcdpError` implements `Clone` (see its doc), which is what lets
2034/// [`Self::revocation_discovery`]'s failure also be independently owned
2035/// by [`VerifiedContext::revocation_discovery_failure`] from the same
2036/// `fetch_report*` call; `AcdpError` still has no `PartialEq`, so
2037/// asserting on any `AcdpError`-carrying field here wants `matches!`.
2038///
2039/// `#[non_exhaustive]`: this struct has already gained a field once as a
2040/// non-optional consequence of a security fix (the RFC-ACDP-0006 §4.1
2041/// context-identity binding), and it is output-only — constructed solely
2042/// inside this crate (`verified.rs`) — so downstream loses nothing by
2043/// being unable to construct it directly. Same rationale as `SsrfReason`
2044/// in `crates/acdp-safe-http/src/lib.rs` ("future spec revisions may add
2045/// ranges"): future fields stop being breaking changes for callers that
2046/// only read this report.
2047#[derive(Debug)]
2048#[non_exhaustive]
2049pub struct VerificationReport {
2050    /// `content_hash` recomputed from the body matches the declared one.
2051    pub body_hash_ok: bool,
2052    /// The producer signature verified against the resolved DID key.
2053    pub signature_ok: bool,
2054    /// `validate_body` passed (or was disabled by policy).
2055    pub schema_ok: bool,
2056    /// Per-`DataRef` embedded-hash outcome, in `body.data_refs` order.
2057    pub data_ref_embedded: Vec<Result<usize, AcdpError>>,
2058    /// Per-`DataRef` external-fetch outcome, in `body.data_refs` order.
2059    /// `None` indicates "not attempted" (no fetcher provided or no
2060    /// `location` to fetch from).
2061    pub data_ref_external: Vec<Option<Result<usize, AcdpError>>>,
2062    /// The served body's `ctx_id` equals the one requested
2063    /// (RFC-ACDP-0006 §4.1 step 7, NORMATIVE — "Bind the resolved
2064    /// identity"). `false` means the registry served a different,
2065    /// validly-signed body under the requested id (context
2066    /// substitution); see `VerifiedContext::verify_retrieved`'s doc for
2067    /// the full rationale. This flag gates whether
2068    /// [`VerifiedContext::fetch_report_diagnose`] hands back a
2069    /// `Some(VerifiedContext)` — appended last so any positional
2070    /// construction fails loudly rather than silently binding the wrong
2071    /// field.
2072    pub ctx_id_ok: bool,
2073    /// The real P3-P6 verdict from `verify_retrieved`'s authorization
2074    /// phases (receipt, revocation, signature/historical, unknown-status),
2075    /// when they ran and all passed. `None` means either "not reached"
2076    /// (a top-level probe — schema, body hash, signature, ctx_id — failed
2077    /// first, so `verify_retrieved` was never invoked) or "the phase ran
2078    /// and failed" (see [`Self::policy_phase_error`] for which one).
2079    pub key_status: Option<KeyAuthorization>,
2080    /// Which of `verify_retrieved`'s policy-governed phases (receipt,
2081    /// revocation, signature/historical-key, unknown-status) failed, when
2082    /// one did. `None` when every phase passed, or when `verify_retrieved`
2083    /// was never invoked because a top-level probe failed first.
2084    /// `AcdpError` derives `Clone` (see its doc — added for this field's
2085    /// and [`VerifiedContext::revocation_discovery_failure`]'s sake), but
2086    /// asserting on it still wants `matches!` over `==`/`assert_eq!`:
2087    /// `AcdpError` has no `PartialEq`.
2088    pub policy_phase_error: Option<AcdpError>,
2089    /// What RFC-ACDP-0014 §8 auto-discovery did, when
2090    /// `policy.revocations.discover` was `Some` and `verify_retrieved`
2091    /// was reached (a top-level probe failure or a
2092    /// [`DiscoveryFailurePolicy::FailClosed`] discovery failure both
2093    /// leave this `None` — the latter surfaces via
2094    /// [`Self::policy_phase_error`] instead, since `verify_retrieved`
2095    /// returned `Err` before there was any outcome to record). `Some(Ok(_))`
2096    /// on success; `Some(Err(_))` when
2097    /// [`DiscoveryFailurePolicy::ProceedWithKnown`] swallowed a
2098    /// discovery failure and verification proceeded on
2099    /// [`RevocationPolicy::known`] alone — see
2100    /// [`VerifiedContext::revocation_discovery_failure`] for the twin
2101    /// surface on the verified handle itself, populated from the same
2102    /// event. The counts inside [`DiscoveryOutcome`] are discovery
2103    /// output only, never `known` — appended last, after
2104    /// `policy_phase_error`, for the same "fail loudly on stale
2105    /// positional construction" reason that field was.
2106    pub revocation_discovery: Option<Result<DiscoveryOutcome, AcdpError>>,
2107    /// RFC-ACDP-0010 §8 step 1 receipt-key status (0.5.0); see
2108    /// [`VerifiedContext::receipt_key_status`]. `None` when no receipt
2109    /// verified or the authorization phases were not reached.
2110    pub receipt_key_status: Option<acdp_types::receipt::ReceiptKeyStatus>,
2111    /// The receipt verdict, reported separately from the body verdict
2112    /// (RFC-ACDP-0010 §8, 0.5.0); see [`VerifiedContext::receipt_verdict`].
2113    pub receipt_verdict: Option<Result<(), AcdpError>>,
2114    /// How `body.lineage_id` is bound (RFC-ACDP-0004 §2.1, 0.5.0);
2115    /// `None` when the authorization phases were not reached.
2116    pub lineage_binding: Option<acdp_verify::LineageBinding>,
2117    /// The typed revocation verdict (RFC-ACDP-0014 §7/§8, 0.5.0); see
2118    /// [`VerifiedContext::revocation_verdict`]. `None` when the
2119    /// authorization phases were not reached.
2120    pub revocation_verdict: Option<RevocationVerdict>,
2121    /// Verified revocations outside the producer's scope (RFC-ACDP-0014 §7
2122    /// "Producer scope", 0.5.0) — reported, never applied.
2123    pub revocation_hints: Vec<SourcedRevocation>,
2124    /// The RFC-ACDP-0012 §9 log-inclusion verdict (0.4.0), reported
2125    /// separately from every verdict above; see
2126    /// [`VerifiedContext::log_inclusion_verdict`]. `None` when not
2127    /// evaluated or when the authorization phases were not reached.
2128    pub log_inclusion_verdict: Option<LogInclusionVerdict>,
2129    /// The RFC-ACDP-0015 §8 witness-quorum verdict (0.4.0); see
2130    /// [`VerifiedContext::witness_quorum`]. `None` when
2131    /// [`VerificationPolicy::witness_quorum`] is unset or when the
2132    /// authorization phases were not reached.
2133    pub witness_quorum: Option<Result<WitnessQuorumReport, AcdpError>>,
2134}
2135
2136/// Sentinel `DataRefFetcher` used as the type parameter for
2137/// `fetch_report_inner` when no fetcher is supplied. `fetch` is never
2138/// actually called — the option is matched out before that — but
2139/// providing a real impl lets the generic monomorphize cleanly without
2140/// requiring `fetch_report`'s callers to name a type.
2141struct NoFetcher;
2142
2143impl DataRefFetcher for NoFetcher {
2144    async fn fetch(
2145        &self,
2146        _location: &acdp_types::data_ref::Location,
2147    ) -> Result<Vec<u8>, AcdpError> {
2148        Err(AcdpError::NotImplemented(
2149            "NoFetcher should never be called — this is a fetch_report sentinel".into(),
2150        ))
2151    }
2152}
2153
2154#[cfg(test)]
2155mod tests {
2156    use super::{
2157        DiscoveryFailurePolicy, HistoricalKeyPolicy, ReceiptPolicy, RevocationDiscovery,
2158        RevocationPolicy, VerificationPolicy,
2159    };
2160    use acdp_primitives::error::AcdpError;
2161    use std::time::Duration;
2162
2163    /// The RFC-ACDP-0001 §9.2 named constructor preserves exact v0.1.0
2164    /// semantics: receipts inert, assertionMethod-only keys. It is
2165    /// deliberately NOT the 0.2 default (which is receipt-aware).
2166    /// RFC-ACDP-0001 §5.11 strict profile item 1 (acdp-rs#385 item 8).
2167    #[test]
2168    fn v0_1_0_bodies_require_did_web() {
2169        use acdp_types::Body;
2170
2171        const DK: &str = "did:key:z6MkiTBz1ymuepAQ4HEHYSF1H8quG5GLVVQR3djdX3mDooWp";
2172        const WEB: &str = "did:web:agents.example.com:p";
2173        let body_for = |agent: &str, version: Option<&str>| -> Body {
2174            let mut v = serde_json::json!({
2175                "ctx_id": "acdp://registry.example.com/9f1e2d3c-5a6b-4c7d-8e9f-0a1b2c3d4e5f",
2176                "lineage_id": "lin:sha256:6af6229c1c6a4a119695c77e47f6554941aebce3d25ba8567e2ae6ffbb6059cb",
2177                "origin_registry": "registry.example.com",
2178                "created_at": "2026-05-02T08:00:00.000Z",
2179                "version": 1,
2180                "supersedes": null,
2181                "agent_id": agent,
2182                "contributors": [],
2183                "content_hash": "sha256:0000000000000000000000000000000000000000000000000000000000000000",
2184                "signature": {"algorithm": "ed25519", "key_id": format!("{agent}#key-1"), "value": "AA=="},
2185                "title": "strict v0.1.0",
2186                "type": "data_snapshot",
2187                "data_refs": [],
2188                "derived_from": [],
2189                "visibility": "public",
2190            });
2191            if let Some(ver) = version {
2192                v["acdp_version"] = serde_json::json!(ver);
2193            }
2194            serde_json::from_value(v).unwrap()
2195        };
2196
2197        for v in [None, Some("0.1.0")] {
2198            let err = crate::verified::require_did_web_for_v0_1_0(&body_for(DK, v)).unwrap_err();
2199            assert!(
2200                matches!(err, AcdpError::SchemaViolation(_)),
2201                "{v:?}: {err:?}"
2202            );
2203            crate::verified::require_did_web_for_v0_1_0(&body_for(WEB, v)).unwrap();
2204        }
2205        for v in ["0.2.0", "0.4.0"] {
2206            crate::verified::require_did_web_for_v0_1_0(&body_for(DK, Some(v))).unwrap();
2207        }
2208
2209        // A did:web agent_id with a did:key signing key on a v0.1.0 body
2210        // is rejected too (the key_id DID portion is checked separately).
2211        let mut mixed = body_for(WEB, None);
2212        mixed.signature.key_id = format!("{DK}#k");
2213        assert!(matches!(
2214            crate::verified::require_did_web_for_v0_1_0(&mixed),
2215            Err(AcdpError::SchemaViolation(_))
2216        ));
2217    }
2218
2219    #[test]
2220    fn strict_v0_1_0_preserves_v0_1_0_semantics() {
2221        let strict = VerificationPolicy::strict_v0_1_0();
2222        assert!(strict.validate_body_schema);
2223        assert!(strict.allow_unknown_status);
2224        assert_eq!(strict.receipts, ReceiptPolicy::Ignore);
2225        assert_eq!(strict.historical_keys, HistoricalKeyPolicy::Reject);
2226        assert!(strict.require_did_web_for_v0_1_0);
2227        assert!(
2228            VerificationPolicy::default().require_did_web_for_v0_1_0,
2229            "RFC-ACDP-0001 §5.11: a relaxed mode MUST NOT be the default"
2230        );
2231        assert!(
2232            strict.revocations.known.is_empty(),
2233            "a 0.1.0-pinned consumer is unaffected by RFC-ACDP-0014"
2234        );
2235        assert_ne!(
2236            strict,
2237            VerificationPolicy::default(),
2238            "the 0.2 default is receipt-aware; the v0.1.0 profile is not"
2239        );
2240    }
2241
2242    /// Phase 2 acceptance criterion 6 — the spine lock.
2243    ///
2244    /// `verify_retrieved` must be the SOLE reader of the
2245    /// authorization-policy fields (`receipts`, `revocations`,
2246    /// `historical_keys`, `allow_unknown_status`,
2247    /// `require_did_web_for_v0_1_0`) anywhere in this file.
2248    /// Every public entry point (the four `fetch*` forms plus the three
2249    /// report forms) reaches every authorization phase through that one
2250    /// function, so a future RFC phase added anywhere else — instead of
2251    /// inside `verify_retrieved` — trips this test instead of silently
2252    /// reintroducing the exact divergence this phase fixed.
2253    ///
2254    /// Implemented as a plain `str` scan (no `regex` — it is not a
2255    /// dependency of `acdp-client`) over this file's own source, read via
2256    /// `include_str!`. `verify_retrieved`'s body span is located by
2257    /// brace-counting from its own opening brace (its signature has no
2258    /// braces of its own — only angle brackets in the return type — so
2259    /// the first `{` after the `fn` keyword IS the body's opening brace),
2260    /// not by hard-coded line numbers, so the check survives any diff.
2261    /// Lines whose trimmed start is `//` (covers `///` too), and matches
2262    /// that fall inside a string literal (detected by an odd count of
2263    /// unescaped `"` before the match on its line — this file's one
2264    /// in-string occurrence, the `allow_unknown_status=false` error
2265    /// message, already lives inside `verify_retrieved` regardless), are
2266    /// excluded.
2267    ///
2268    /// The four search patterns are built by runtime concatenation
2269    /// (`policy.` + each field name) rather than written as contiguous
2270    /// `"policy.receipts"`-style literals, so this test's own source —
2271    /// included verbatim via `include_str!` — does not self-match its
2272    /// own patterns.
2273    #[test]
2274    fn verify_retrieved_is_sole_reader_of_authorization_policy_fields() {
2275        const SRC: &str = include_str!("verified.rs");
2276
2277        let policy_prefix = "policy.";
2278        let fields = [
2279            "receipts",
2280            "revocations",
2281            "historical_keys",
2282            "allow_unknown_status",
2283            "require_did_web_for_v0_1_0",
2284            "log_inclusion",
2285            "witness_quorum",
2286        ];
2287        let patterns: Vec<String> = fields
2288            .iter()
2289            .map(|f| format!("{policy_prefix}{f}"))
2290            .collect();
2291
2292        // Locate `verify_retrieved`'s body span.
2293        let fn_start = SRC
2294            .find("async fn verify_retrieved(")
2295            .expect("verify_retrieved must exist in verified.rs");
2296        let body_open = fn_start
2297            + SRC[fn_start..]
2298                .find('{')
2299                .expect("verify_retrieved must have a body");
2300        let mut depth = 0i32;
2301        let mut body_close = None;
2302        for (i, ch) in SRC[body_open..].char_indices() {
2303            match ch {
2304                '{' => depth += 1,
2305                '}' => {
2306                    depth -= 1;
2307                    if depth == 0 {
2308                        body_close = Some(body_open + i);
2309                        break;
2310                    }
2311                }
2312                _ => {}
2313            }
2314        }
2315        let body_close =
2316            body_close.expect("verify_retrieved's matching closing brace must be found");
2317        assert!(
2318            body_close > body_open,
2319            "sanity: verify_retrieved's body must be non-empty"
2320        );
2321
2322        // Scan the whole file, tracking byte offsets so each match's
2323        // position can be tested against the body span.
2324        let mut offset = 0usize;
2325        let mut checked_any = false;
2326        for line in SRC.split_inclusive('\n') {
2327            let trimmed = line.trim_start();
2328            let is_comment_line = trimmed.starts_with("//");
2329            if !is_comment_line {
2330                for pattern in &patterns {
2331                    let mut search_from = 0usize;
2332                    while let Some(rel) = line[search_from..].find(pattern.as_str()) {
2333                        let match_col = search_from + rel;
2334                        let match_start = offset + match_col;
2335                        let before = &line[..match_col];
2336                        let in_string_literal = before.matches('"').count() % 2 == 1;
2337                        if !in_string_literal {
2338                            checked_any = true;
2339                            assert!(
2340                                match_start >= body_open && match_start < body_close,
2341                                "found `{pattern}` outside verify_retrieved's body \
2342                                 (byte offset {match_start}, line: {line:?}) — every \
2343                                 authorization-policy-field read must live inside \
2344                                 verify_retrieved, the sole reader"
2345                            );
2346                        }
2347                        search_from = match_col + pattern.len();
2348                    }
2349                }
2350            }
2351            offset += line.len();
2352        }
2353
2354        // Second pass — whitespace-normalized, to catch a read rustfmt
2355        // has wrapped across lines (e.g. a `policy` / `.revocations` /
2356        // `.known` chain on three separate lines), which the
2357        // line-by-line pass above cannot see since the pattern never
2358        // sits contiguously on any single line. Build a copy of `SRC`
2359        // with whitespace immediately touching a `.` removed — folding
2360        // any such wrapped chain back to its unwrapped spelling — while
2361        // recording, for every byte kept, the byte offset it came from
2362        // in the original `SRC`. Every match here is re-validated
2363        // against its ORIGINAL line for the same comment / string
2364        // exclusions the first pass applies, so this pass only adds
2365        // coverage; it does not relax anything the first pass enforces.
2366        let mut normalized = String::with_capacity(SRC.len());
2367        let mut orig_offsets: Vec<usize> = Vec::with_capacity(SRC.len());
2368        let mut after_dot = false;
2369        for (i, ch) in SRC.char_indices() {
2370            if ch == '.' {
2371                while let Some(last) = normalized.chars().last() {
2372                    if !last.is_whitespace() {
2373                        break;
2374                    }
2375                    normalized.pop();
2376                    let new_len = orig_offsets.len() - last.len_utf8();
2377                    orig_offsets.truncate(new_len);
2378                }
2379                normalized.push(ch);
2380                orig_offsets.push(i);
2381                after_dot = true;
2382                continue;
2383            }
2384            if after_dot && ch.is_whitespace() {
2385                continue; // swallow whitespace immediately after a dot
2386            }
2387            after_dot = false;
2388            normalized.push(ch);
2389            for _ in 0..ch.len_utf8() {
2390                orig_offsets.push(i);
2391            }
2392        }
2393        debug_assert_eq!(normalized.len(), orig_offsets.len());
2394
2395        let is_comment_line_at = |pos: usize| -> bool {
2396            let line_start = SRC[..pos].rfind('\n').map_or(0, |i| i + 1);
2397            let line_end = SRC[pos..].find('\n').map_or(SRC.len(), |i| pos + i);
2398            SRC[line_start..line_end].trim_start().starts_with("//")
2399        };
2400        let in_string_literal_at = |pos: usize| -> bool {
2401            let line_start = SRC[..pos].rfind('\n').map_or(0, |i| i + 1);
2402            SRC[line_start..pos].matches('"').count() % 2 == 1
2403        };
2404
2405        for pattern in &patterns {
2406            let mut search_from = 0usize;
2407            while let Some(rel) = normalized[search_from..].find(pattern.as_str()) {
2408                let match_col = search_from + rel;
2409                let orig_start = orig_offsets[match_col];
2410                if !is_comment_line_at(orig_start) && !in_string_literal_at(orig_start) {
2411                    checked_any = true;
2412                    assert!(
2413                        orig_start >= body_open && orig_start < body_close,
2414                        "found `{pattern}` (whitespace-normalized) outside \
2415                         verify_retrieved's body (original byte offset {orig_start}) \
2416                         — every authorization-policy-field read must live inside \
2417                         verify_retrieved, the sole reader, even when rustfmt has \
2418                         wrapped the field-access chain across multiple lines"
2419                    );
2420                }
2421                search_from = match_col + pattern.len();
2422            }
2423        }
2424
2425        assert!(
2426            checked_any,
2427            "sanity: the scan must find at least one non-comment, non-string-literal \
2428             match for at least one pattern (verify_retrieved itself reads these \
2429             fields) — zero hits would mean the patterns are miscomputed, not that \
2430             the invariant holds"
2431        );
2432    }
2433
2434    /// issue #248 Phase 2, acceptance criterion 1 — `RevocationPolicy::default()`
2435    /// stays behaviorally identical to the pre-Phase-2 shape: no known
2436    /// revocations, discovery off.
2437    #[test]
2438    fn revocation_policy_default_is_unchanged() {
2439        let policy = RevocationPolicy::default();
2440        assert!(policy.known.is_empty());
2441        assert!(policy.discover.is_none());
2442    }
2443
2444    /// issue #248 Phase 2, acceptance criterion 1 (continued) — `::new`
2445    /// produces the same shape as the old bare-literal `RevocationPolicy { known }`
2446    /// this struct's `#[non_exhaustive]` retires.
2447    #[test]
2448    fn revocation_policy_new_leaves_discovery_off() {
2449        let policy = RevocationPolicy::new(vec![]);
2450        assert!(policy.known.is_empty());
2451        assert!(policy.discover.is_none());
2452    }
2453
2454    /// issue #248 Phase 2, acceptance criterion 3.
2455    #[test]
2456    fn discovery_failure_policy_defaults_to_fail_closed() {
2457        assert_eq!(
2458            DiscoveryFailurePolicy::default(),
2459            DiscoveryFailurePolicy::FailClosed
2460        );
2461    }
2462
2463    /// issue #248 Phase 2, acceptance criterion 3.
2464    #[test]
2465    fn revocation_discovery_constructors_set_the_right_trust_classes() {
2466        let producer_only = RevocationDiscovery::producer_signed_only();
2467        assert!(!producer_only.include_registry_attested);
2468        assert_eq!(producer_only.on_failure, DiscoveryFailurePolicy::FailClosed);
2469        assert_eq!(producer_only.total_timeout, Duration::from_secs(30));
2470        assert_eq!(
2471            producer_only.freshness,
2472            Duration::from_secs(300),
2473            "RFC-ACDP-0014 §8 (0.5.0): negative freshness defaults to the RECOMMENDED 300 s"
2474        );
2475
2476        let all = RevocationDiscovery::all_trust_classes();
2477        assert!(all.include_registry_attested);
2478        assert_eq!(all.on_failure, DiscoveryFailurePolicy::FailClosed);
2479        assert_eq!(all.total_timeout, Duration::from_secs(30));
2480        assert_eq!(all.freshness, Duration::from_secs(300));
2481    }
2482
2483    /// issue #248 Phase 2, acceptance criterion 3 (continued) — D6:
2484    /// `RevocationDiscovery` has no `Default` impl. This is a
2485    /// compile-time property, not something a runtime assertion can
2486    /// check; the doc comment on `RevocationDiscovery` records why.
2487    /// This test exists to make that guarantee discoverable from the
2488    /// test suite: if a future change adds `Default`, this comment is
2489    /// the tripwire a reviewer reads, since nothing here would fail.
2490    /// (An attempted `RevocationDiscovery::default()` call would be a
2491    /// compile error today — that IS the enforcement.)
2492    #[test]
2493    fn revocation_discovery_has_no_default_by_design() {
2494        // Deliberately empty: the guarantee is enforced by the type
2495        // system (no `Default` impl exists), not by this test body.
2496    }
2497
2498    /// RFC-ACDP-0014 §8 (0.5.0): `RevocationUnknown` is transient exactly
2499    /// when its reason is `transient`.
2500    #[test]
2501    fn revocation_unknown_is_transient_only_for_transient_reason() {
2502        let unknown = |source: AcdpError| {
2503            let reason = source.unknown_reason();
2504            AcdpError::RevocationUnknown {
2505                reason,
2506                source: Box::new(source),
2507                detail: String::new(),
2508            }
2509        };
2510        let transient = unknown(AcdpError::KeyResolutionUnreachable("x".into()));
2511        assert!(transient.is_transient());
2512        for permanent in [
2513            AcdpError::InvalidSignature("x".into()),
2514            AcdpError::SearchTruncated("x".into()),
2515            AcdpError::NotAuthorized("x".into()),
2516            AcdpError::RevocationCandidateUnverifiable("x".into()),
2517        ] {
2518            assert!(!unknown(permanent).is_transient());
2519        }
2520    }
2521}