Skip to main content

acdp_primitives/
error.rs

1//! Error types for the ACDP library.
2//!
3//! Error variants align with the wire vocabulary defined by
4//! `acdp-error.schema.json` and RFC-ACDP-0007 §5. The
5//! [`AcdpError::from_wire_error`] helper converts a
6//! [`crate::wire_error::WireError`] (HTTP response body shape) into a typed
7//! variant.
8
9use crate::primitives::ContentHash;
10#[cfg(doc)]
11use crate::revocation::RevocationEffect;
12use crate::revocation::{RevocationRefusal, UnknownReason};
13use serde::{Deserialize, Serialize};
14use thiserror::Error;
15
16/// Top-level error type.
17///
18/// `#[non_exhaustive]`: the wire vocabulary (RFC-ACDP-0007 §5) keeps growing
19/// as new RFCs land — 25 wire codes now, up from 21 not long ago, with
20/// RFC-ACDP-0009 reserved and still unimplemented. Without this attribute,
21/// every new variant is a semver-breaking change for any downstream crate
22/// that matches on `AcdpError` exhaustively. Same rationale as
23/// `SsrfReason` in `crates/acdp-safe-http/src/lib.rs` ("future spec
24/// revisions may add ranges"); match with a wildcard arm.
25/// `Clone` (added for issue #248 Phase 4): `VerifiedContext` and
26/// `VerificationReport` each need an independently-owned copy of a
27/// `ProceedWithKnown`-swallowed revocation-discovery failure — one via
28/// `VerifiedContext::revocation_discovery_failure()`, the other via
29/// `VerificationReport::revocation_discovery` — so both surfaces stay
30/// non-silent from a single call. Every variant field (`String`,
31/// `&'static str`, `ContentHash`, `WireError`, `SupersessionReason`,
32/// and the recursive `Box<AcdpError>` in `RevocationUnknown`)
33/// is already `Clone`, so this is a free addition with no wire-format
34/// or matching impact.
35///
36/// This is a standing constraint on every future variant, not just the
37/// ones that exist today: every future variant's payloads must remain
38/// `Clone`. A variant that needs a structured source should hold
39/// `Arc<dyn std::error::Error + Send + Sync>` (which is `Clone`
40/// regardless of the inner type, and still preserves `source()`
41/// chaining), never `Box<dyn Error>` or a bare `io::Error` (neither is
42/// `Clone`). This is not a new tradeoff introduced by adding `Clone`
43/// here — `From<std::io::Error>` and `From<reqwest::Error>` already
44/// stringify into `Http(String)` rather than carry the error value, so
45/// value semantics over reference/source-chain semantics was already
46/// the twice-exercised choice for this type; `Clone` just makes it a
47/// documented rule instead of an implicit pattern.
48#[derive(Debug, Clone, Error)]
49#[non_exhaustive]
50pub enum AcdpError {
51    // ── Cryptography ─────────────────────────────────────────────────────────
52    /// JCS canonicalization failed (input not serializable).
53    #[error("JCS canonicalization failed: {0}")]
54    Canonicalization(String),
55
56    /// Stored `content_hash` did not match the recomputed value
57    /// (locally detected during signature verification).
58    #[error("content_hash mismatch\n  stored:     {stored}\n  recomputed: {recomputed}")]
59    HashMismatch {
60        /// The hash claimed by the body or request.
61        stored: ContentHash,
62        /// The hash recomputed by the verifier.
63        recomputed: ContentHash,
64    },
65
66    /// Locally detected: the registry returned a body whose `ctx_id` is not
67    /// the one that was requested (context substitution). Not a wire code —
68    /// the client detects it. Permanent; fail closed.
69    ///
70    /// Implements RFC-ACDP-0006 §4.1 step 7 (NORMATIVE, "Bind the resolved
71    /// identity"): step 7 requires exactly this comparison — `body.ctx_id`
72    /// against the `ctx_id` used to construct the request — and permits a
73    /// consumer to surface "an equivalent typed error" in place of the
74    /// registry-side `cross_registry_resolution_failed` wire code; this
75    /// variant is that typed error. See RFC-ACDP-0008 §9.1 for the threat
76    /// this closes: without it, a registry can serve any other
77    /// validly-signed body by the same producer under the requested
78    /// context's URL, and both signature verification and `content_hash`
79    /// recomputation still pass. It does **not** close §9.1 in full: a
80    /// registry that genuinely republishes the same content under a new
81    /// `ctx_id` still passes; only serve-time substitution — a different
82    /// id claimed to be the one requested — is caught.
83    #[error("context substitution: requested {requested}, registry served {served}")]
84    ContextIdMismatch {
85        /// The `ctx_id` the caller requested.
86        requested: String,
87        /// The `ctx_id` actually present on the body the registry served.
88        served: String,
89    },
90
91    /// Locally detected: `GET /lineages/{id}` (RFC-ACDP-0013 §8.1) did not
92    /// serve a lineage the caller could accept — either it came back with
93    /// no members at all, or (when `ctx_id` is `Some`) its members did not
94    /// include the `ctx_id` a live search match named for that lineage.
95    /// Not a wire code — RFC-ACDP-0014 §10 ("No new wire error code"):
96    /// this is a locally-detected consumer-side binding failure, exactly
97    /// the same kind of thing as [`AcdpError::ContextIdMismatch`] (issue
98    /// #189) but for the lineage-walk path added for issue #226. Permanent;
99    /// fail closed — never added to [`AcdpError::is_transient`].
100    #[error(
101        "incomplete lineage {lineage_id}: registry-served members did not satisfy the \
102         expected membership (expected ctx_id: {ctx_id:?})"
103    )]
104    IncompleteLineage {
105        /// The lineage id that was walked (`GET /lineages/{id}`).
106        lineage_id: String,
107        /// The `ctx_id` a live search match named for this lineage, when
108        /// the walk was invoked with a specific member to check for.
109        /// `None` when the walk was invoked directly with no particular
110        /// member to verify (e.g. via `find_revocations_in_lineage`),
111        /// in which case only the empty-lineage case can produce this
112        /// variant.
113        ctx_id: Option<String>,
114    },
115
116    /// Locally detected: a revocation-discovery search helper
117    /// (`find_revocations`, `find_registry_attested_revocations` in
118    /// `acdp-client`) exhausted its pagination safety cap
119    /// (`MAX_SEARCH_PAGES`) with a search cursor still remaining, or
120    /// named more candidate revocation-lineage ids than its lineage-walk
121    /// safety cap (`MAX_LINEAGE_WALKS`) allows to fetch. Not a wire code
122    /// — RFC-ACDP-0014 §10 ("No new wire error code"): this is a
123    /// client-local safety-limit signal the registry cannot express, the
124    /// same rationale as [`AcdpError::ContextIdMismatch`] and
125    /// [`AcdpError::IncompleteLineage`]. Permanent for the same request
126    /// shape — never added to [`AcdpError::is_transient`]; retrying an
127    /// identical query reproduces the same truncation.
128    ///
129    /// Both caps exist as hostile-registry DoS protection
130    /// (`MAX_SEARCH_PAGES` bounds search round-trips; `MAX_LINEAGE_WALKS`
131    /// bounds the `GET /lineages/{id}` fetches a search result can
132    /// trigger, each capped at 1 MB). Search results are ordered
133    /// `created_at DESC`, so hitting a cap sheds the OLDEST — most
134    /// likely earliest-`compromised_since` — members first: a silently
135    /// truncated revocation set narrows a compromise window, which is
136    /// precisely the outcome RFC-ACDP-0014 §4 ("earliest T across a
137    /// revocation lineage is effective") forbids. A knowingly-partial
138    /// answer from these discovery helpers is strictly worse than a
139    /// loud refusal, so exhausting either cap with more results
140    /// remaining on the registry is a hard error, never a silently
141    /// partial `Vec`.
142    #[error("search truncated: {0}")]
143    SearchTruncated(String),
144
145    /// Locally detected (issue #258): RFC-ACDP-0014 §8 revocation
146    /// auto-discovery (`RevocationDiscovery::max_requests` /
147    /// `RevocationDiscovery::max_bytes` in `acdp-client`) exhausted its
148    /// caller-configured request-count or cumulative-byte budget before
149    /// both trust-class lookups finished. Not a wire code — RFC-ACDP-0014
150    /// §10 ("No new wire error code") forbids one, and this is
151    /// client-side only, the same rationale as
152    /// [`AcdpError::SearchTruncated`]. Permanent for the same request
153    /// shape — never added to [`AcdpError::is_transient`] — exhausting a
154    /// budget is closer to `SearchTruncated` ("we did not see
155    /// everything") than to a transport error, and carries the same
156    /// attacker-inducible-downgrade warning: a hostile registry that
157    /// learns a caller's budget can pad harmless-looking traffic to
158    /// exhaust it before a real revocation is found.
159    ///
160    /// The two budgets are combined across BOTH lookups
161    /// (`find_revocations` and, when opted in,
162    /// `find_registry_attested_revocations`), not one ceiling each —
163    /// enabling the registry-attested trust class does not double the
164    /// allowance. The request count is enforced exactly: the slot is
165    /// reserved *before* the request is issued, so a request is never
166    /// issued once the budget is reserved out, and — unlike the byte
167    /// count below — a 503, a parse failure, or a `PayloadTooLarge` on
168    /// an already-reserved request still consumes its slot. The byte
169    /// count is enforced on a check-before-issue basis using the running
170    /// total from completed requests, so up to TWO in-flight requests
171    /// (one per concurrently-running trust-class lookup) can push the
172    /// total over `max_bytes` before the NEXT request observes the
173    /// overrun. Counts registry traffic only (`acdp-client`'s
174    /// `RegistryClient::{capabilities, retrieve, lineage, search}`) —
175    /// DID-document fetches issued via `WebResolver` are not counted.
176    /// Only the byte count is scoped to successfully-parsed response
177    /// bodies: the capped error-envelope read on a non-success response
178    /// is never charged to `max_bytes`, but IS charged to `max_requests`
179    /// (the slot was already reserved before the response arrived).
180    #[error("revocation discovery budget exceeded: {0}")]
181    RevocationDiscoveryBudgetExceeded(String),
182
183    /// Locally detected (RFC-ACDP-0014 §8, 0.5.0 "Discovery outcome
184    /// classes"): a revocation candidate found during auto-discovery
185    /// could be neither verified nor proven invalid. The canonical case is
186    /// the mandatory *historical arm*: the candidate's signing key is in
187    /// the producer's `verificationMethod` but no longer in
188    /// `assertionMethod` (the producer rotated after publishing it), and
189    /// the candidate carries no `registry_receipt` — or one that does not
190    /// verify — so the RFC-ACDP-0010 §10 historical-key rule cannot place
191    /// the signature (rev-005 B).
192    ///
193    /// Not a wire code (RFC-ACDP-0014 §10). Not transient — retrying the
194    /// same discovery will see the same candidate — but **discovery-
195    /// fatal**: the spec forbids folding an unverifiable candidate into
196    /// "not revoked", so discovery surfaces it (wrapped in
197    /// [`AcdpError::RevocationUnknown`]) exactly like a transient
198    /// lookup failure, and the overall outcome is *unknown*.
199    #[error("revocation candidate unverifiable: {0}")]
200    RevocationCandidateUnverifiable(String),
201
202    /// Locally detected (RFC-ACDP-0014 §8, 0.5.0 "Discovery outcome
203    /// classes"): revocation auto-discovery (`RevocationPolicy::discover`
204    /// in `acdp-client`) could not establish whether the signing key is
205    /// revoked — the outcome is **`unknown`**, which is never folded into
206    /// not-revoked. Returned under `DiscoveryFailurePolicy::FailClosed`
207    /// (the default); under `ProceedWithKnown` the same value is reported
208    /// on the verified context instead.
209    ///
210    /// Not a wire code (RFC-ACDP-0014 §10). [`AcdpError::is_transient`] is
211    /// `true` exactly when `reason` is [`UnknownReason::Transient`] — map
212    /// that to "unavailable, retry" and every other reason to "failed
213    /// precondition".
214    ///
215    /// Replaces 0.14's `RevocationDiscoveryFailed { source }`: match
216    /// `RevocationUnknown { source, .. }` for the same shape.
217    #[error("revocation status unknown ({reason}): {detail}")]
218    RevocationUnknown {
219        /// The `unknown` reason sub-code.
220        reason: UnknownReason,
221        /// The underlying failure (a transport or lookup error,
222        /// [`AcdpError::SearchTruncated`],
223        /// [`AcdpError::RevocationDiscoveryBudgetExceeded`],
224        /// [`AcdpError::RevocationCandidateUnverifiable`], …). Boxed:
225        /// the variant recurses.
226        source: Box<AcdpError>,
227        /// Human-readable context (which lookup, which vantage).
228        detail: String,
229    },
230
231    /// Locally detected (RFC-ACDP-0014 §7, 0.5.0 "Attribution"): a
232    /// verified, in-scope revocation makes the context's signing key not
233    /// authorized — §7 step 3 ([`RevocationEffect::Revoked`], final) or
234    /// step 4 ([`RevocationEffect::Unplaceable`], curable by a receipt).
235    /// The refusal names the revocation that fixes the boundary: its
236    /// `ctx_id`, signer, trust class, controller and T.
237    ///
238    /// Wire code: `key_not_authorized` — a revocation is a verification
239    /// verdict with no wire code of its own (RFC-ACDP-0014 §10), so a
240    /// round trip through the wire yields [`AcdpError::KeyNotAuthorized`].
241    /// [`AcdpError::is_key_not_authorized`] covers both.
242    #[error("key revoked — {0}")]
243    KeyRevoked(Box<RevocationRefusal>),
244
245    /// Wire code: `hash_mismatch`. The remote registry rejected a
246    /// publish request because its independent hash recomputation did
247    /// not match the producer-supplied `content_hash`. Distinct from
248    /// the local [`AcdpError::HashMismatch`] variant: this one carries
249    /// the registry's message verbatim and indicates a *producer-side*
250    /// bug (most often canonicalization divergence — see RFC-ACDP-0001
251    /// §5.7 and the `can-001` conformance fixture).
252    #[error("registry rejected hash_mismatch: {0}")]
253    RemoteHashMismatch(String),
254
255    /// Wire code: `data_ref_hash_mismatch`. A DataRef's fetched or decoded
256    /// bytes do not match the producer-declared `data_ref.content_hash`.
257    /// The body itself remains cryptographically valid — only the
258    /// referenced data has diverged. Distinct from
259    /// [`AcdpError::RemoteHashMismatch`] / [`AcdpError::HashMismatch`]
260    /// (body-level ProducerContent failure — the whole body is untrusted)
261    /// and [`AcdpError::InvalidSignature`] (a key / key-binding problem).
262    /// RFC-ACDP-0002 §6.5–6.6, RFC-ACDP-0007 §5.
263    #[error("data_ref hash mismatch: {0}")]
264    DataRefHashMismatch(String),
265
266    /// Signature verification failed or signature was malformed.
267    /// Wire code: `invalid_signature`.
268    #[error("invalid signature: {0}")]
269    InvalidSignature(String),
270
271    // ── DID / key resolution ─────────────────────────────────────────────
272    /// Wire code: `key_resolution_failed` (HTTP 400).
273    #[error("key resolution failed: {0}")]
274    KeyResolution(String),
275
276    /// Wire code: `key_resolution_unreachable` (HTTP 502) — transient, may retry.
277    #[error("key resolution unreachable (transient): {0}")]
278    KeyResolutionUnreachable(String),
279
280    /// Wire code: `key_not_authorized` (HTTP 403).
281    #[error("key not authorized: {0}")]
282    KeyNotAuthorized(String),
283
284    // ── Input validation ─────────────────────────────────────────────────
285    /// Producer body could not be parsed.
286    #[error("invalid body: {0}")]
287    InvalidBody(String),
288
289    /// A required field was missing.
290    #[error("missing required field: {0}")]
291    MissingField(&'static str),
292
293    /// Schema validation failed (string length, array uniqueness, oneOf, etc).
294    /// Wire code: `schema_violation`.
295    #[error("schema violation: {0}")]
296    SchemaViolation(String),
297
298    /// Wire code: `payload_too_large` — request body exceeds the registry limit.
299    #[error("payload too large: {0}")]
300    PayloadTooLarge(String),
301
302    /// Wire code: `embedded_too_large` — a single `DataRef.embedded.content`
303    /// exceeds the 64 KB cap.
304    #[error("embedded data reference too large: {0}")]
305    EmbeddedTooLarge(String),
306
307    /// Wire code: `unsupported_algorithm` — the producer used a signature
308    /// algorithm the registry does not accept.
309    #[error("unsupported algorithm: {0}")]
310    UnsupportedAlgorithm(String),
311
312    /// Wire code: `unsupported_media_type` — the request carried a body whose
313    /// `Content-Type` is outside the registry's accept-set (RFC-ACDP-0007 §4.1,
314    /// §5; HTTP 415). Added on the 0.5.0 line.
315    ///
316    /// Distinct from [`AcdpError::SchemaViolation`] on purpose: the body is
317    /// rejected *unparsed*, so no structural claim about it is made. A registry
318    /// answering `schema_violation` here would be asserting a validation that
319    /// never ran — and that code is pinned to HTTP 400. Registries advertising
320    /// `acdp_version` below 0.5.0 MUST NOT emit this code.
321    #[error("unsupported media type: {0}")]
322    UnsupportedMediaType(String),
323
324    /// Wire code: `not_implemented` — endpoint or feature not supported by
325    /// this registry.
326    #[error("not implemented: {0}")]
327    NotImplemented(String),
328
329    // ── Retrieval / authorization ────────────────────────────────────────
330    /// Wire code: `not_found`.
331    #[error("not found: {0}")]
332    NotFound(String),
333
334    /// Wire code: `not_authorized` — the caller is not permitted to access
335    /// this resource.
336    #[error("not authorized: {0}")]
337    NotAuthorized(String),
338
339    /// Wire code: `rate_limited`.
340    #[error("rate limited: {0}")]
341    RateLimited(String),
342
343    // ── Pagination ───────────────────────────────────────────────────────
344    /// Wire code: `cursor_expired`.
345    #[error("search cursor expired")]
346    CursorExpired,
347
348    /// Wire code: `invalid_cursor`.
349    #[error("invalid cursor: {0}")]
350    InvalidCursor(String),
351
352    // ── Publication ──────────────────────────────────────────────────────
353    /// Wire code: `superseded_target`. The supersession target was rejected;
354    /// the [`SupersessionReason`] disambiguates the cause.
355    #[error("superseded target rejected ({reason:?}): {message}")]
356    SupersededTarget {
357        /// Why the target was rejected.
358        reason: SupersessionReason,
359        /// Human-readable message from the registry.
360        message: String,
361    },
362
363    /// Wire code: `duplicate_publish` — an Idempotency-Key replay produced
364    /// a different request body than the original.
365    #[error("duplicate publish: {0}")]
366    DuplicatePublish(String),
367
368    // ── Cross-registry ───────────────────────────────────────────────────
369    /// Wire code: `cross_registry_resolution_failed`.
370    #[error("cross-registry resolution failed: {0}")]
371    CrossRegistryResolutionFailed(String),
372
373    // ── Registry receipts (ACDP 0.2, RFC-ACDP-0010) ─────────────────────
374    /// Wire code: `invalid_receipt`. A `registry_receipt` failed
375    /// verification: bad signature, a cross-check mismatch (`ctx_id`,
376    /// `content_hash`, `key_fingerprint`, serving authority), a
377    /// malformed shape, or a receipt required by policy but absent.
378    /// Permanent — the receipt will not verify on retry.
379    #[error("invalid registry receipt: {0}")]
380    InvalidReceipt(String),
381
382    /// Wire code: `invalid_log_proof` (RFC-ACDP-0012 §9, §11 — 0.3.0).
383    /// A transparency-log artifact failed verification: an inclusion
384    /// proof that does not fold to the checkpoint's root, a failed
385    /// consistency proof between tree sizes, or a checkpoint whose
386    /// signature does not verify. Permanent — a bad proof will not
387    /// verify on retry (HTTP 502 on the wire: the upstream log is at
388    /// fault when a federated resolver emits it).
389    #[error("invalid transparency-log proof: {0}")]
390    InvalidLogProof(String),
391
392    /// Wire code: `invalid_witness_cosignature` (RFC-ACDP-0015 §8,
393    /// §10 — 0.4.0). A transparency-log **witness cosignature** failed
394    /// the §8 verification procedure: closed parse, the witness-key
395    /// signature, witness binding (`signature.key_id` DID ≠
396    /// `witness_id`), checkpoint binding (`witnessed_checkpoint` ≠ the
397    /// checkpoint being evaluated), or the `witnessed_at` skew check.
398    /// Deliberately **distinct** from [`AcdpError::InvalidLogProof`]:
399    /// that indicts the *log* (tree membership, history consistency,
400    /// the registry's checkpoint signature); this indicts a *witness's*
401    /// attestation — an independent verdict over an independent signer
402    /// (RFC-ACDP-0015 §10). Permanent — a bad cosignature will not
403    /// verify on retry (HTTP 502 on the wire: the cosignature came from
404    /// an upstream party — a registry aggregating on a caller's behalf
405    /// or a resolver validating a witness's cosignatures). A cosignature
406    /// that verifies but is merely *stale* is consumer freshness policy
407    /// (§8.1), never this code.
408    #[error("invalid witness cosignature: {0}")]
409    InvalidWitnessCosignature(String),
410
411    /// Wire code: `immutable_field` (RFC-ACDP-0013 §6, §10 — 0.3.0;
412    /// activated from the v0.1.0 reservation). A lifecycle (or future
413    /// mutation) endpoint request attempted to supply or alter
414    /// immutable body content. Bodies are immutable; lifecycle
415    /// endpoints mutate registry state only. Permanent (HTTP 400).
416    #[error("immutable field: {0}")]
417    ImmutableField(String),
418
419    /// Wire code: `invalid_lifecycle_transition` (RFC-ACDP-0013 §6
420    /// step 4, §10 — 0.3.0). The requested lifecycle transition
421    /// conflicts with the context's current retraction state (retract
422    /// of an already-retracted context; republish of a never-retracted
423    /// one). A state conflict like the 409 arm of `superseded_target`;
424    /// retryable only after the state changes (HTTP 409).
425    #[error("invalid lifecycle transition: {0}")]
426    InvalidLifecycleTransition(String),
427
428    // ── Wire / transport ─────────────────────────────────────────────────
429    /// Wire code: `internal_error`.
430    #[error("registry internal error: {0}")]
431    RegistryInternal(String),
432
433    /// Catch-all for `WireError` codes that have no typed variant in this
434    /// version of the library. Forward-compatible: registries may emit
435    /// reserved codes (`unsupported_embedding_model`)
436    /// that future ACDP versions add.
437    #[error("registry returned error: {0:?}")]
438    Registry(crate::wire_error::WireError),
439
440    /// JSON (de)serialization failed.
441    #[error("serialization failed: {0}")]
442    Serialization(String),
443
444    /// HTTP transport error.
445    #[error("HTTP error: {0}")]
446    Http(String),
447}
448
449/// Sub-reason for [`AcdpError::SupersededTarget`]. Starts from the
450/// `details.reason` values enumerated by `acdp-error.schema.json`'s
451/// `superseded_target` description (`not_found`, `lineage_mismatch`,
452/// `version_mismatch`, `already_superseded`,
453/// `cross_registry_supersession_unsupported`) and adds typed reasons this
454/// library recognizes beyond what that enum currently lists
455/// (`LineageWalkFailed`, `RevocationTypeMismatch`) — it is a superset, not
456/// a mirror. `#[non_exhaustive]` plus the `Other` catch-all below is what
457/// keeps a schema addition from being a breaking change here.
458#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
459#[non_exhaustive]
460#[serde(rename_all = "snake_case")]
461pub enum SupersessionReason {
462    /// The supersedes target context does not exist on this registry.
463    NotFound,
464    /// The target's lineage_id differs from the new publication's lineage.
465    LineageMismatch,
466    /// The new version is not exactly `previous.version + 1`.
467    VersionMismatch,
468    /// The target has already been superseded by a different version.
469    AlreadySuperseded,
470    /// The target lives on a different registry; v0.1.0 only allows
471    /// same-registry supersession.
472    CrossRegistrySupersessionUnsupported,
473    /// The lineage walk through `supersedes` failed because an
474    /// intermediate context could not be retrieved (RFC-ACDP-0001 §5.6.1).
475    LineageWalkFailed,
476    /// A non-revocation context superseded a `key-revocation` (or interim
477    /// `acdp:key-revocation`) target (RFC-ACDP-0014 §4/§10). Only emitted by
478    /// registries advertising `acdp_version >= 0.5.0`; below that version
479    /// this rejection surfaces as `AcdpError::SchemaViolation` instead.
480    /// `Provisional` per `registries/error-codes.md` (the 0.5.0 line is
481    /// still Draft).
482    RevocationTypeMismatch,
483    /// A reason this version of the library does not recognize.
484    #[serde(other)]
485    Other,
486}
487
488impl AcdpError {
489    /// Whether this error is plausibly transient and worth retrying
490    /// with the same request body (and, if applicable, the same
491    /// `Idempotency-Key`).
492    ///
493    /// Returned by [`AcdpError::is_transient`] only for variants whose
494    /// wire codes the spec marks retryable: `key_resolution_unreachable`
495    /// (RFC-ACDP-0001 §5.11), `rate_limited` (RFC-ACDP-0008 §4.3),
496    /// `cross_registry_resolution_failed` (RFC-ACDP-0006 §7), and
497    /// `internal_error` (RFC-ACDP-0007 §5). Generic `Http` transport
498    /// errors are conservatively treated as transient since they
499    /// usually mean DNS or TCP-level glitches.
500    ///
501    /// An SSRF-policy refusal is never `Http`: the DNS-time refusal raised
502    /// by `acdp_safe_http::SafeDnsResolver` (see [`SsrfDnsRefusal`]) is
503    /// classified by `From<reqwest::Error>` as the permanent
504    /// [`AcdpError::SchemaViolation`] — the same variant the URL-time
505    /// `SsrfPolicy::check_url` refusal already uses — so a retry loop such
506    /// as `RegistryClient::publish_with_retry` does not retry a policy
507    /// decision that will be identical on every attempt (issue #321).
508    /// `CrossRegistryResolver` is the one deliberate exception: RFC-ACDP-0007
509    /// §5 lists "DNS resolution refused" under
510    /// `cross_registry_resolution_failed` (fixture `fed-007`), so that
511    /// resolver re-maps the refusal to
512    /// [`AcdpError::CrossRegistryResolutionFailed`].
513    ///
514    /// All cryptographic, schema, and authorization errors are NOT
515    /// transient: a malformed body or invalid signature will not
516    /// magically validate on retry.
517    ///
518    /// [`AcdpError::RevocationUnknown`] is not a wire code; it is
519    /// transient exactly when its reason is [`UnknownReason::Transient`].
520    pub fn is_transient(&self) -> bool {
521        if let AcdpError::RevocationUnknown { reason, .. } = self {
522            return *reason == UnknownReason::Transient;
523        }
524        matches!(
525            self,
526            AcdpError::KeyResolutionUnreachable(_)
527                | AcdpError::RateLimited(_)
528                | AcdpError::CrossRegistryResolutionFailed(_)
529                | AcdpError::RegistryInternal(_)
530                | AcdpError::Http(_)
531        )
532    }
533
534    /// The RFC-ACDP-0014 §8 `unknown` reason a revocation-discovery
535    /// failure carrying this error represents (0.5.0 "Discovery outcome
536    /// classes"):
537    ///
538    /// - [`UnknownReason::Truncated`] — [`AcdpError::SearchTruncated`],
539    ///   [`AcdpError::RevocationDiscoveryBudgetExceeded`],
540    ///   [`AcdpError::IncompleteLineage`] (truncation is not completeness);
541    /// - [`UnknownReason::UnverifiableCandidate`] —
542    ///   [`AcdpError::RevocationCandidateUnverifiable`];
543    /// - [`UnknownReason::Transient`] — any [`Self::is_transient`] error;
544    /// - [`UnknownReason::Unanswerable`] — everything else, notably
545    ///   `not_authorized` (403) and `not_implemented` (501) from the
546    ///   discovery vantage.
547    ///
548    /// An existing [`AcdpError::RevocationUnknown`] keeps its own reason.
549    pub fn unknown_reason(&self) -> UnknownReason {
550        match self {
551            AcdpError::RevocationUnknown { reason, .. } => *reason,
552            AcdpError::SearchTruncated(_)
553            | AcdpError::RevocationDiscoveryBudgetExceeded(_)
554            | AcdpError::IncompleteLineage { .. } => UnknownReason::Truncated,
555            AcdpError::RevocationCandidateUnverifiable(_) => UnknownReason::UnverifiableCandidate,
556            e if e.is_transient() => UnknownReason::Transient,
557            _ => UnknownReason::Unanswerable,
558        }
559    }
560
561    /// Whether this is a `key_not_authorized` verdict:
562    /// [`AcdpError::KeyNotAuthorized`] or the attributed
563    /// [`AcdpError::KeyRevoked`].
564    pub fn is_key_not_authorized(&self) -> bool {
565        matches!(
566            self,
567            AcdpError::KeyNotAuthorized(_) | AcdpError::KeyRevoked(_)
568        )
569    }
570
571    /// The attributed revocation refusal, when this is
572    /// [`AcdpError::KeyRevoked`].
573    pub fn revocation_refusal(&self) -> Option<&RevocationRefusal> {
574        match self {
575            AcdpError::KeyRevoked(r) => Some(r),
576            _ => None,
577        }
578    }
579
580    /// Whether this error is a client-local SSRF-policy refusal: an
581    /// [`AcdpError::SchemaViolation`] whose message starts with
582    /// [`SSRF_POLICY_PREFIX`].
583    ///
584    /// Covers the URL-time `SsrfPolicy::check_url` refusal, the pin-time
585    /// `SsrfPolicy::pin_resolved_ip` refusal, and the DNS-time
586    /// `SafeDnsResolver` refusal as classified by `From<reqwest::Error>`
587    /// (issue #321). Use this rather than matching message text yourself.
588    /// `WebResolver` surfaces its refusals as [`AcdpError::KeyResolution`]
589    /// and `CrossRegistryResolver` as
590    /// [`AcdpError::CrossRegistryResolutionFailed`]; neither is reported
591    /// here.
592    pub fn is_ssrf_policy_refusal(&self) -> bool {
593        matches!(self, AcdpError::SchemaViolation(m) if m.starts_with(SSRF_POLICY_PREFIX))
594    }
595
596    /// Map a wire-protocol [`crate::wire_error::WireError`] into a typed
597    /// [`AcdpError`].
598    ///
599    /// Codes the library does not yet recognize are returned as
600    /// [`AcdpError::Registry`] for forward compatibility.
601    pub fn from_wire_error(wire: crate::wire_error::WireError) -> Self {
602        let code = wire.error.code.as_str();
603        let msg = wire.error.message.clone();
604
605        match code {
606            "invalid_signature" => AcdpError::InvalidSignature(msg),
607            "hash_mismatch" => AcdpError::RemoteHashMismatch(msg),
608            "data_ref_hash_mismatch" => AcdpError::DataRefHashMismatch(msg),
609            "schema_violation" => AcdpError::SchemaViolation(msg),
610            "not_authorized" => AcdpError::NotAuthorized(msg),
611            "not_found" => AcdpError::NotFound(msg),
612            "rate_limited" => AcdpError::RateLimited(msg),
613            "payload_too_large" => AcdpError::PayloadTooLarge(msg),
614            "embedded_too_large" => AcdpError::EmbeddedTooLarge(msg),
615            "key_resolution_failed" => AcdpError::KeyResolution(msg),
616            "key_resolution_unreachable" => AcdpError::KeyResolutionUnreachable(msg),
617            "key_not_authorized" => AcdpError::KeyNotAuthorized(msg),
618            "unsupported_algorithm" => AcdpError::UnsupportedAlgorithm(msg),
619            "unsupported_media_type" => AcdpError::UnsupportedMediaType(msg),
620            "not_implemented" => AcdpError::NotImplemented(msg),
621            "cursor_expired" => AcdpError::CursorExpired,
622            "invalid_cursor" => AcdpError::InvalidCursor(msg),
623            "duplicate_publish" => AcdpError::DuplicatePublish(msg),
624            "cross_registry_resolution_failed" => AcdpError::CrossRegistryResolutionFailed(msg),
625            "invalid_receipt" => AcdpError::InvalidReceipt(msg),
626            "invalid_log_proof" => AcdpError::InvalidLogProof(msg),
627            "invalid_witness_cosignature" => AcdpError::InvalidWitnessCosignature(msg),
628            "immutable_field" => AcdpError::ImmutableField(msg),
629            "invalid_lifecycle_transition" => AcdpError::InvalidLifecycleTransition(msg),
630            "internal_error" => AcdpError::RegistryInternal(msg),
631            "superseded_target" => {
632                let reason = wire
633                    .error
634                    .details
635                    .as_ref()
636                    .and_then(|d| d.get("reason"))
637                    .and_then(|v| serde_json::from_value::<SupersessionReason>(v.clone()).ok())
638                    .unwrap_or(SupersessionReason::Other);
639                AcdpError::SupersededTarget {
640                    reason,
641                    message: msg,
642                }
643            }
644            // Unknown / future codes pass through as the catch-all variant
645            _ => AcdpError::Registry(wire),
646        }
647    }
648}
649
650impl From<serde_json::Error> for AcdpError {
651    fn from(e: serde_json::Error) -> Self {
652        AcdpError::Serialization(e.to_string())
653    }
654}
655
656impl From<std::io::Error> for AcdpError {
657    fn from(e: std::io::Error) -> Self {
658        AcdpError::Http(format!("io error: {e}"))
659    }
660}
661
662/// Typed marker for an SSRF-policy refusal raised while resolving a
663/// hostname (RFC-ACDP-0006 §7.1 / RFC-ACDP-0008 §4.8 DNS-rebinding
664/// protection).
665///
666/// `acdp_safe_http::SafeDnsResolver` returns this as the error of a
667/// refused resolution. reqwest wraps it (as an `io::Error` /
668/// connector error) before it reaches the caller, so it surfaces only in
669/// the `source()` chain of the resulting `reqwest::Error`;
670/// [`is_ssrf_refusal`] finds it there by downcast. Its presence is what
671/// makes `From<reqwest::Error> for AcdpError` (and `WebResolver`)
672/// classify the failure as permanent instead of as a retryable
673/// transport error.
674///
675/// Not a wire code: this never appears in a registry response body.
676#[derive(Debug, Clone, PartialEq, Eq)]
677pub struct SsrfDnsRefusal {
678    message: String,
679}
680
681impl SsrfDnsRefusal {
682    /// Build a refusal carrying a human-readable explanation. The
683    /// message SHOULD start with [`SSRF_POLICY_PREFIX`] (every
684    /// `acdp-safe-http` refusal does) so it stays recognizable even after
685    /// a wrapper stringifies it.
686    pub fn new(message: impl Into<String>) -> Self {
687        Self {
688            message: message.into(),
689        }
690    }
691
692    /// The human-readable explanation.
693    pub fn message(&self) -> &str {
694        &self.message
695    }
696}
697
698impl std::fmt::Display for SsrfDnsRefusal {
699    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
700        f.write_str(&self.message)
701    }
702}
703
704impl std::error::Error for SsrfDnsRefusal {}
705
706/// Prefix every SSRF-policy refusal message produced by this workspace
707/// starts with: the `acdp-safe-http` checks (`SsrfPolicy::check_url`,
708/// `check_ip`, `pin_resolved_ip`, `SafeDnsResolver`) and the
709/// [`AcdpError::SchemaViolation`] that `From<reqwest::Error>` builds for a
710/// refused request. Matched with `starts_with`, never `contains`, so a
711/// message that merely *mentions* the policy (a URL, an echoed registry
712/// error) does not classify.
713pub const SSRF_POLICY_PREFIX: &str = "SSRF policy:";
714
715/// Whether `err` — or any error in its `source()` chain — is an
716/// SSRF-policy refusal.
717///
718/// The single classification point shared by `From<reqwest::Error> for
719/// AcdpError`, `HttpsDataRefFetcher`, and `WebResolver` (issue #321), so
720/// the paths cannot drift. Primary detection is a downcast to the typed
721/// [`SsrfDnsRefusal`] marker; as a fallback, a chain link whose `Display`
722/// **starts with** [`SSRF_POLICY_PREFIX`] also counts (a wrapper that
723/// re-boxes the marker as a string still classifies the same way).
724pub fn is_ssrf_refusal(err: &(dyn std::error::Error + 'static)) -> bool {
725    let mut cur: Option<&(dyn std::error::Error + 'static)> = Some(err);
726    while let Some(e) = cur {
727        if e.downcast_ref::<SsrfDnsRefusal>().is_some()
728            || e.to_string().starts_with(SSRF_POLICY_PREFIX)
729        {
730            return true;
731        }
732        cur = e.source();
733    }
734    false
735}
736
737/// Render `err` followed by every error in its `source()` chain, joined by
738/// `": "`.
739///
740/// reqwest's own `Display` prints only its outermost frame (e.g. "error
741/// sending request for url (...)"); the cause it wraps — notably a
742/// `SafeDnsResolver` SSRF refusal — lives in the `source()` chain and
743/// would otherwise be silently dropped.
744pub fn error_chain_message(err: &(dyn std::error::Error + 'static)) -> String {
745    let mut msg = err.to_string();
746    let mut source = err.source();
747    while let Some(s) = source {
748        msg.push_str(": ");
749        msg.push_str(&s.to_string());
750        source = s.source();
751    }
752    msg
753}
754
755#[cfg(feature = "reqwest")]
756impl From<reqwest::Error> for AcdpError {
757    /// Classify a reqwest transport failure.
758    ///
759    /// - An SSRF-policy refusal anywhere in the `source()` chain
760    ///   ([`is_ssrf_refusal`]) → [`AcdpError::SchemaViolation`]
761    ///   (permanent; same variant as the URL-time `SsrfPolicy::check_url`
762    ///   refusal).
763    /// - A connect / timeout failure → [`AcdpError::Http`] prefixed
764    ///   `connection failed:` (transient).
765    /// - Anything else → [`AcdpError::Http`] (transient).
766    ///
767    /// In every case the message carries [`error_chain_message`], so the
768    /// underlying cause is never dropped. The SSRF message is prefixed
769    /// with [`SSRF_POLICY_PREFIX`] so [`AcdpError::is_ssrf_policy_refusal`]
770    /// recognizes it.
771    fn from(e: reqwest::Error) -> Self {
772        let msg = error_chain_message(&e);
773        if is_ssrf_refusal(&e) {
774            AcdpError::SchemaViolation(format!("{SSRF_POLICY_PREFIX} request refused: {msg}"))
775        } else if e.is_connect() || e.is_timeout() {
776            AcdpError::Http(format!("connection failed: {msg}"))
777        } else {
778            AcdpError::Http(msg)
779        }
780    }
781}
782
783#[cfg(test)]
784mod tests {
785    use super::*;
786    use crate::wire_error::{WireError, WireErrorBody};
787    use serde_json::json;
788
789    fn wire(code: &str, message: &str, details: Option<serde_json::Value>) -> WireError {
790        WireError {
791            error: WireErrorBody {
792                code: code.into(),
793                message: message.into(),
794                details,
795            },
796        }
797    }
798
799    #[test]
800    fn all_26_wire_codes_round_trip() {
801        // Test-coverage matrix entry: "All 26 error codes parse from WireError".
802        // Every code enumerated by acdp-error.schema.json's enum MUST map to a
803        // typed AcdpError variant (or, for `superseded_target` with details,
804        // produce the right SupersessionReason).
805        type Check = fn(&AcdpError) -> bool;
806        let cases: &[(&str, Check)] = &[
807            ("invalid_signature", |e| {
808                matches!(e, AcdpError::InvalidSignature(_))
809            }),
810            ("hash_mismatch", |e| {
811                matches!(e, AcdpError::RemoteHashMismatch(_))
812            }),
813            ("data_ref_hash_mismatch", |e| {
814                matches!(e, AcdpError::DataRefHashMismatch(_))
815            }),
816            ("schema_violation", |e| {
817                matches!(e, AcdpError::SchemaViolation(_))
818            }),
819            ("not_authorized", |e| {
820                matches!(e, AcdpError::NotAuthorized(_))
821            }),
822            ("not_found", |e| matches!(e, AcdpError::NotFound(_))),
823            ("superseded_target", |e| {
824                matches!(e, AcdpError::SupersededTarget { .. })
825            }),
826            ("unsupported_algorithm", |e| {
827                matches!(e, AcdpError::UnsupportedAlgorithm(_))
828            }),
829            ("rate_limited", |e| matches!(e, AcdpError::RateLimited(_))),
830            ("payload_too_large", |e| {
831                matches!(e, AcdpError::PayloadTooLarge(_))
832            }),
833            ("embedded_too_large", |e| {
834                matches!(e, AcdpError::EmbeddedTooLarge(_))
835            }),
836            ("key_resolution_failed", |e| {
837                matches!(e, AcdpError::KeyResolution(_))
838            }),
839            ("key_resolution_unreachable", |e| {
840                matches!(e, AcdpError::KeyResolutionUnreachable(_))
841            }),
842            ("key_not_authorized", |e| {
843                matches!(e, AcdpError::KeyNotAuthorized(_))
844            }),
845            ("not_implemented", |e| {
846                matches!(e, AcdpError::NotImplemented(_))
847            }),
848            ("unsupported_media_type", |e| {
849                matches!(e, AcdpError::UnsupportedMediaType(_))
850            }),
851            ("cursor_expired", |e| matches!(e, AcdpError::CursorExpired)),
852            ("invalid_cursor", |e| {
853                matches!(e, AcdpError::InvalidCursor(_))
854            }),
855            ("duplicate_publish", |e| {
856                matches!(e, AcdpError::DuplicatePublish(_))
857            }),
858            ("cross_registry_resolution_failed", |e| {
859                matches!(e, AcdpError::CrossRegistryResolutionFailed(_))
860            }),
861            ("invalid_receipt", |e| {
862                matches!(e, AcdpError::InvalidReceipt(_))
863            }),
864            ("invalid_log_proof", |e| {
865                matches!(e, AcdpError::InvalidLogProof(_))
866            }),
867            ("invalid_witness_cosignature", |e| {
868                matches!(e, AcdpError::InvalidWitnessCosignature(_))
869            }),
870            ("immutable_field", |e| {
871                matches!(e, AcdpError::ImmutableField(_))
872            }),
873            ("invalid_lifecycle_transition", |e| {
874                matches!(e, AcdpError::InvalidLifecycleTransition(_))
875            }),
876            ("internal_error", |e| {
877                matches!(e, AcdpError::RegistryInternal(_))
878            }),
879        ];
880        // Schema enumerates exactly 26 codes (RFC-ACDP-0007 §5 + the
881        // RFC-ACDP-0010 `invalid_receipt` addition + the 0.3.0 codes:
882        // `invalid_log_proof` (RFC-0012), `immutable_field` and
883        // `invalid_lifecycle_transition` (RFC-0013) + the 0.4.0 code
884        // `invalid_witness_cosignature` (RFC-0015) + the 0.5.0 code
885        // `unsupported_media_type` (RFC-0007 §4.1, spec #68)).
886        //
887        // This count is hand-maintained and therefore only catches a code this
888        // repo forgot to *add*. The forcing function that catches the spec
889        // growing underneath us is `wire_error_codes_cover_the_spec_enum` in
890        // `tests/conformance.rs`, which reads the enum out of
891        // `acdp-error.schema.json` itself.
892        assert_eq!(cases.len(), 26);
893        for (code, expected) in cases {
894            let err = AcdpError::from_wire_error(wire(code, "msg", None));
895            assert!(
896                expected(&err),
897                "code '{code}' did not map to its typed variant: got {err:?}"
898            );
899        }
900    }
901
902    #[test]
903    fn superseded_target_with_reason_details() {
904        let w = wire(
905            "superseded_target",
906            "lineage mismatch",
907            Some(json!({"reason": "lineage_mismatch"})),
908        );
909        match AcdpError::from_wire_error(w) {
910            AcdpError::SupersededTarget { reason, .. } => {
911                assert_eq!(reason, SupersessionReason::LineageMismatch);
912            }
913            other => panic!("expected SupersededTarget, got {other:?}"),
914        }
915    }
916
917    #[test]
918    fn superseded_target_without_details_falls_back_to_other() {
919        let w = wire("superseded_target", "?", None);
920        match AcdpError::from_wire_error(w) {
921            AcdpError::SupersededTarget { reason, .. } => {
922                assert_eq!(reason, SupersessionReason::Other);
923            }
924            other => panic!("got {other:?}"),
925        }
926    }
927
928    #[test]
929    fn unknown_code_passes_through_as_registry() {
930        let w = wire("unsupported_embedding_model", "reserved future code", None);
931        assert!(matches!(
932            AcdpError::from_wire_error(w),
933            AcdpError::Registry(_)
934        ));
935    }
936
937    /// T4 — `lineage_walk_failed` reason round-trips via WireError
938    /// (RFC-ACDP-0001 §5.6.1).
939    #[test]
940    fn lineage_walk_failed_reason_roundtrip() {
941        let w = wire(
942            "superseded_target",
943            "intermediate not retrievable",
944            Some(json!({
945                "reason": "lineage_walk_failed",
946                "unreachable_ctx_id":
947                    "acdp://r.example.com/12345678-1234-4321-8123-123456781234"
948            })),
949        );
950        match AcdpError::from_wire_error(w) {
951            AcdpError::SupersededTarget { reason, .. } => {
952                assert_eq!(reason, SupersessionReason::LineageWalkFailed);
953            }
954            other => panic!("got {other:?}"),
955        }
956    }
957
958    /// RFC-ACDP-0014 §4 — `revocation_type_mismatch` reason round-trips via
959    /// `WireError`, same shape as `lineage_walk_failed_reason_roundtrip`
960    /// above. This is also a direct serde round-trip of the
961    /// `SupersessionReason` variant itself (`to_value`/`from_value`), not
962    /// just an assertion on the value `from_wire_error` produces.
963    #[test]
964    fn revocation_type_mismatch_reason_roundtrip() {
965        assert_eq!(
966            serde_json::to_value(SupersessionReason::RevocationTypeMismatch).unwrap(),
967            json!("revocation_type_mismatch")
968        );
969        assert_eq!(
970            serde_json::from_value::<SupersessionReason>(json!("revocation_type_mismatch"))
971                .unwrap(),
972            SupersessionReason::RevocationTypeMismatch
973        );
974
975        let w = wire(
976            "superseded_target",
977            "non-revocation context cannot supersede a key-revocation target",
978            Some(json!({"reason": "revocation_type_mismatch"})),
979        );
980        match AcdpError::from_wire_error(w) {
981            AcdpError::SupersededTarget { reason, .. } => {
982                assert_eq!(reason, SupersessionReason::RevocationTypeMismatch);
983            }
984            other => panic!("got {other:?}"),
985        }
986    }
987
988    /// `is_transient` covers the wire codes the spec marks retryable.
989    #[test]
990    fn is_transient_for_known_retryables() {
991        assert!(AcdpError::KeyResolutionUnreachable("x".into()).is_transient());
992        assert!(AcdpError::RateLimited("x".into()).is_transient());
993        assert!(AcdpError::CrossRegistryResolutionFailed("x".into()).is_transient());
994        assert!(AcdpError::RegistryInternal("x".into()).is_transient());
995        assert!(AcdpError::Http("x".into()).is_transient());
996        assert!(!AcdpError::SchemaViolation("x".into()).is_transient());
997        assert!(!AcdpError::InvalidSignature("x".into()).is_transient());
998        assert!(!AcdpError::NotFound("x".into()).is_transient());
999        // BUG-02: data-ref hash mismatch is a data-integrity failure;
1000        // retrying the SAME publish/fetch will return the same answer.
1001        // The spec marks it permanent, not retryable.
1002        assert!(!AcdpError::DataRefHashMismatch("x".into()).is_transient());
1003        // RFC-ACDP-0010: a failed receipt will not verify on retry.
1004        assert!(!AcdpError::InvalidReceipt("x".into()).is_transient());
1005        assert!(!AcdpError::InvalidLogProof("x".into()).is_transient());
1006        // RFC-ACDP-0015: a bad witness cosignature will not verify on retry.
1007        assert!(!AcdpError::InvalidWitnessCosignature("x".into()).is_transient());
1008        // RFC-ACDP-0007 §4.1: retrying with the same Content-Type gets the
1009        // same 415. The fix is a different request, not a later one.
1010        assert!(!AcdpError::UnsupportedMediaType("x".into()).is_transient());
1011        assert!(!AcdpError::ImmutableField("x".into()).is_transient());
1012        assert!(!AcdpError::InvalidLifecycleTransition("x".into()).is_transient());
1013        // Issue #189: context substitution is locally detected and permanent;
1014        // retrying against the same misbehaving registry will not fix it.
1015        assert!(!AcdpError::ContextIdMismatch {
1016            requested: "a".into(),
1017            served: "b".into(),
1018        }
1019        .is_transient());
1020        // Issue #226 Phase 3: an incomplete/mismatched lineage is a
1021        // locally-detected consumer-side binding failure, not a
1022        // transport hiccup — retrying will not change what the
1023        // registry serves for the same lineage_id.
1024        assert!(!AcdpError::IncompleteLineage {
1025            lineage_id: "lin:sha256:aa".into(),
1026            ctx_id: Some("acdp://r.example.com/x".into()),
1027        }
1028        .is_transient());
1029        // Issue #226 Phase 4: exhausting the search-page or lineage-walk
1030        // safety cap is a client-local safety-limit signal, not a
1031        // transport hiccup — retrying the identical query reproduces the
1032        // same truncation.
1033        assert!(!AcdpError::SearchTruncated("x".into()).is_transient());
1034        // Issue #258: exhausting a caller-configured discovery request/byte
1035        // budget is a client-local safety-limit signal, like
1036        // `SearchTruncated` above — never transient, and deliberately NOT
1037        // added to the `matches!` list in `is_transient`.
1038        assert!(!AcdpError::RevocationDiscoveryBudgetExceeded("x".into()).is_transient());
1039        assert!(!AcdpError::RevocationCandidateUnverifiable("x".into()).is_transient());
1040    }
1041
1042    /// A wrapper error with an optional source, standing in for the
1043    /// io/connector frames reqwest puts around a resolver error.
1044    #[derive(Debug)]
1045    struct Wrap(
1046        &'static str,
1047        Option<Box<dyn std::error::Error + Send + Sync>>,
1048    );
1049    impl std::fmt::Display for Wrap {
1050        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1051            f.write_str(self.0)
1052        }
1053    }
1054    impl std::error::Error for Wrap {
1055        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1056            self.1
1057                .as_deref()
1058                .map(|e| e as &(dyn std::error::Error + 'static))
1059        }
1060    }
1061
1062    /// Issue #321: the typed marker is found by downcast however deep it
1063    /// sits, independent of its message text.
1064    #[test]
1065    fn is_ssrf_refusal_finds_typed_marker_in_source_chain() {
1066        let marker = SsrfDnsRefusal::new("forbidden address (no marker text)");
1067        assert!(is_ssrf_refusal(&marker));
1068        let nested = Wrap(
1069            "error sending request",
1070            Some(Box::new(Wrap(
1071                "client error (Connect)",
1072                Some(Box::new(marker)),
1073            ))),
1074        );
1075        assert!(is_ssrf_refusal(&nested));
1076        assert_eq!(
1077            error_chain_message(&nested),
1078            "error sending request: client error (Connect): forbidden address (no marker text)"
1079        );
1080    }
1081
1082    /// Fallback: a wrapper that stringified the marker still classifies.
1083    #[test]
1084    fn is_ssrf_refusal_falls_back_to_message_text() {
1085        let stringified = Wrap(
1086            "outer",
1087            Some(Box::new(Wrap("SSRF policy: DNS answer is forbidden", None))),
1088        );
1089        assert!(is_ssrf_refusal(&stringified));
1090    }
1091
1092    /// The text fallback is anchored: a link that merely *mentions* the
1093    /// policy (e.g. an echoed URL or registry message) does not classify.
1094    #[test]
1095    fn is_ssrf_refusal_fallback_requires_prefix() {
1096        let mention = Wrap(
1097            "upstream said: SSRF policy: blocked",
1098            Some(Box::new(Wrap("see SSRF policy docs", None))),
1099        );
1100        assert!(!is_ssrf_refusal(&mention));
1101    }
1102
1103    /// `AcdpError::is_ssrf_policy_refusal` recognizes exactly the
1104    /// prefixed `SchemaViolation` shape every SSRF path produces.
1105    #[test]
1106    fn is_ssrf_policy_refusal_matches_prefixed_schema_violation_only() {
1107        assert!(
1108            AcdpError::SchemaViolation("SSRF policy: request refused: x".into())
1109                .is_ssrf_policy_refusal()
1110        );
1111        assert!(!AcdpError::SchemaViolation("title too long".into()).is_ssrf_policy_refusal());
1112        assert!(!AcdpError::SchemaViolation("note: SSRF policy: x".into()).is_ssrf_policy_refusal());
1113        assert!(!AcdpError::Http("SSRF policy: x".into()).is_ssrf_policy_refusal());
1114        assert!(!AcdpError::KeyResolution("SSRF policy: x".into()).is_ssrf_policy_refusal());
1115    }
1116
1117    /// An ordinary transport failure is NOT an SSRF refusal.
1118    #[test]
1119    fn is_ssrf_refusal_false_for_plain_transport_errors() {
1120        let plain = Wrap(
1121            "error sending request",
1122            Some(Box::new(Wrap(
1123                "tcp connect error: Connection refused",
1124                None,
1125            ))),
1126        );
1127        assert!(!is_ssrf_refusal(&plain));
1128        let io = std::io::Error::new(std::io::ErrorKind::TimedOut, "timed out");
1129        assert!(!is_ssrf_refusal(&io));
1130    }
1131
1132    /// The variant an SSRF refusal classifies to is permanent; the
1133    /// generic transport variant stays transient.
1134    #[test]
1135    fn ssrf_refusal_classification_is_not_transient() {
1136        assert!(!AcdpError::SchemaViolation("SSRF policy: x".into()).is_transient());
1137        assert!(AcdpError::Http("connection failed: tcp reset".into()).is_transient());
1138    }
1139}