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;
10use serde::{Deserialize, Serialize};
11use thiserror::Error;
12
13/// Top-level error type.
14#[derive(Debug, Error)]
15pub enum AcdpError {
16    // ── Cryptography ─────────────────────────────────────────────────────────
17    /// JCS canonicalization failed (input not serializable).
18    #[error("JCS canonicalization failed: {0}")]
19    Canonicalization(String),
20
21    /// Stored `content_hash` did not match the recomputed value
22    /// (locally detected during signature verification).
23    #[error("content_hash mismatch\n  stored:     {stored}\n  recomputed: {recomputed}")]
24    HashMismatch {
25        /// The hash claimed by the body or request.
26        stored: ContentHash,
27        /// The hash recomputed by the verifier.
28        recomputed: ContentHash,
29    },
30
31    /// Wire code: `hash_mismatch`. The remote registry rejected a
32    /// publish request because its independent hash recomputation did
33    /// not match the producer-supplied `content_hash`. Distinct from
34    /// the local [`AcdpError::HashMismatch`] variant: this one carries
35    /// the registry's message verbatim and indicates a *producer-side*
36    /// bug (most often canonicalization divergence — see RFC-ACDP-0001
37    /// §5.7 and the `can-001` conformance fixture).
38    #[error("registry rejected hash_mismatch: {0}")]
39    RemoteHashMismatch(String),
40
41    /// Wire code: `data_ref_hash_mismatch`. A DataRef's fetched or decoded
42    /// bytes do not match the producer-declared `data_ref.content_hash`.
43    /// The body itself remains cryptographically valid — only the
44    /// referenced data has diverged. Distinct from
45    /// [`AcdpError::RemoteHashMismatch`] / [`AcdpError::HashMismatch`]
46    /// (body-level ProducerContent failure — the whole body is untrusted)
47    /// and [`AcdpError::InvalidSignature`] (a key / key-binding problem).
48    /// RFC-ACDP-0002 §6.5–6.6, RFC-ACDP-0007 §5.
49    #[error("data_ref hash mismatch: {0}")]
50    DataRefHashMismatch(String),
51
52    /// Signature verification failed or signature was malformed.
53    /// Wire code: `invalid_signature`.
54    #[error("invalid signature: {0}")]
55    InvalidSignature(String),
56
57    // ── DID / key resolution ─────────────────────────────────────────────
58    /// Wire code: `key_resolution_failed` (HTTP 400).
59    #[error("key resolution failed: {0}")]
60    KeyResolution(String),
61
62    /// Wire code: `key_resolution_unreachable` (HTTP 502) — transient, may retry.
63    #[error("key resolution unreachable (transient): {0}")]
64    KeyResolutionUnreachable(String),
65
66    /// Wire code: `key_not_authorized` (HTTP 403).
67    #[error("key not authorized: {0}")]
68    KeyNotAuthorized(String),
69
70    // ── Input validation ─────────────────────────────────────────────────
71    /// Producer body could not be parsed.
72    #[error("invalid body: {0}")]
73    InvalidBody(String),
74
75    /// A required field was missing.
76    #[error("missing required field: {0}")]
77    MissingField(&'static str),
78
79    /// Schema validation failed (string length, array uniqueness, oneOf, etc).
80    /// Wire code: `schema_violation`.
81    #[error("schema violation: {0}")]
82    SchemaViolation(String),
83
84    /// Wire code: `payload_too_large` — request body exceeds the registry limit.
85    #[error("payload too large: {0}")]
86    PayloadTooLarge(String),
87
88    /// Wire code: `embedded_too_large` — a single `DataRef.embedded.content`
89    /// exceeds the 64 KB cap.
90    #[error("embedded data reference too large: {0}")]
91    EmbeddedTooLarge(String),
92
93    /// Wire code: `unsupported_algorithm` — the producer used a signature
94    /// algorithm the registry does not accept.
95    #[error("unsupported algorithm: {0}")]
96    UnsupportedAlgorithm(String),
97
98    /// Wire code: `not_implemented` — endpoint or feature not supported by
99    /// this registry.
100    #[error("not implemented: {0}")]
101    NotImplemented(String),
102
103    // ── Retrieval / authorization ────────────────────────────────────────
104    /// Wire code: `not_found`.
105    #[error("not found: {0}")]
106    NotFound(String),
107
108    /// Wire code: `not_authorized` — the caller is not permitted to access
109    /// this resource.
110    #[error("not authorized: {0}")]
111    NotAuthorized(String),
112
113    /// Wire code: `rate_limited`.
114    #[error("rate limited: {0}")]
115    RateLimited(String),
116
117    // ── Pagination ───────────────────────────────────────────────────────
118    /// Wire code: `cursor_expired`.
119    #[error("search cursor expired")]
120    CursorExpired,
121
122    /// Wire code: `invalid_cursor`.
123    #[error("invalid cursor: {0}")]
124    InvalidCursor(String),
125
126    // ── Publication ──────────────────────────────────────────────────────
127    /// Wire code: `superseded_target`. The supersession target was rejected;
128    /// the [`SupersessionReason`] disambiguates the cause.
129    #[error("superseded target rejected ({reason:?}): {message}")]
130    SupersededTarget {
131        /// Why the target was rejected.
132        reason: SupersessionReason,
133        /// Human-readable message from the registry.
134        message: String,
135    },
136
137    /// Wire code: `duplicate_publish` — an Idempotency-Key replay produced
138    /// a different request body than the original.
139    #[error("duplicate publish: {0}")]
140    DuplicatePublish(String),
141
142    // ── Cross-registry ───────────────────────────────────────────────────
143    /// Wire code: `cross_registry_resolution_failed`.
144    #[error("cross-registry resolution failed: {0}")]
145    CrossRegistryResolutionFailed(String),
146
147    // ── Registry receipts (ACDP 0.2, RFC-ACDP-0010) ─────────────────────
148    /// Wire code: `invalid_receipt`. A `registry_receipt` failed
149    /// verification: bad signature, a cross-check mismatch (`ctx_id`,
150    /// `content_hash`, `key_fingerprint`, serving authority), a
151    /// malformed shape, or a receipt required by policy but absent.
152    /// Permanent — the receipt will not verify on retry.
153    #[error("invalid registry receipt: {0}")]
154    InvalidReceipt(String),
155
156    /// Wire code: `invalid_log_proof` (RFC-ACDP-0012 §9, §11 — 0.3.0).
157    /// A transparency-log artifact failed verification: an inclusion
158    /// proof that does not fold to the checkpoint's root, a failed
159    /// consistency proof between tree sizes, or a checkpoint whose
160    /// signature does not verify. Permanent — a bad proof will not
161    /// verify on retry (HTTP 502 on the wire: the upstream log is at
162    /// fault when a federated resolver emits it).
163    #[error("invalid transparency-log proof: {0}")]
164    InvalidLogProof(String),
165
166    /// Wire code: `immutable_field` (RFC-ACDP-0013 §6, §10 — 0.3.0;
167    /// activated from the v0.1.0 reservation). A lifecycle (or future
168    /// mutation) endpoint request attempted to supply or alter
169    /// immutable body content. Bodies are immutable; lifecycle
170    /// endpoints mutate registry state only. Permanent (HTTP 400).
171    #[error("immutable field: {0}")]
172    ImmutableField(String),
173
174    /// Wire code: `invalid_lifecycle_transition` (RFC-ACDP-0013 §6
175    /// step 4, §10 — 0.3.0). The requested lifecycle transition
176    /// conflicts with the context's current retraction state (retract
177    /// of an already-retracted context; republish of a never-retracted
178    /// one). A state conflict like the 409 arm of `superseded_target`;
179    /// retryable only after the state changes (HTTP 409).
180    #[error("invalid lifecycle transition: {0}")]
181    InvalidLifecycleTransition(String),
182
183    // ── Wire / transport ─────────────────────────────────────────────────
184    /// Wire code: `internal_error`.
185    #[error("registry internal error: {0}")]
186    RegistryInternal(String),
187
188    /// Catch-all for `WireError` codes that have no typed variant in this
189    /// version of the library. Forward-compatible: registries may emit
190    /// reserved codes (`unsupported_embedding_model`)
191    /// that future ACDP versions add.
192    #[error("registry returned error: {0:?}")]
193    Registry(crate::wire_error::WireError),
194
195    /// JSON (de)serialization failed.
196    #[error("serialization failed: {0}")]
197    Serialization(String),
198
199    /// HTTP transport error.
200    #[error("HTTP error: {0}")]
201    Http(String),
202}
203
204/// Sub-reason for [`AcdpError::SupersededTarget`]. Mirrors the
205/// `details.reason` values defined by `acdp-error.schema.json`.
206#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
207#[serde(rename_all = "snake_case")]
208pub enum SupersessionReason {
209    /// The supersedes target context does not exist on this registry.
210    NotFound,
211    /// The target's lineage_id differs from the new publication's lineage.
212    LineageMismatch,
213    /// The new version is not exactly `previous.version + 1`.
214    VersionMismatch,
215    /// The target has already been superseded by a different version.
216    AlreadySuperseded,
217    /// The target lives on a different registry; v0.1.0 only allows
218    /// same-registry supersession.
219    CrossRegistrySupersessionUnsupported,
220    /// The lineage walk through `supersedes` failed because an
221    /// intermediate context could not be retrieved (RFC-ACDP-0001 §5.6.1).
222    LineageWalkFailed,
223    /// A reason this version of the library does not recognize.
224    #[serde(other)]
225    Other,
226}
227
228impl AcdpError {
229    /// Whether this error is plausibly transient and worth retrying
230    /// with the same request body (and, if applicable, the same
231    /// `Idempotency-Key`).
232    ///
233    /// Returned by [`AcdpError::is_transient`] only for variants whose
234    /// wire codes the spec marks retryable: `key_resolution_unreachable`
235    /// (RFC-ACDP-0001 §5.11), `rate_limited` (RFC-ACDP-0008 §4.3),
236    /// `cross_registry_resolution_failed` (RFC-ACDP-0006 §7), and
237    /// `internal_error` (RFC-ACDP-0007 §5). Generic `Http` transport
238    /// errors are conservatively treated as transient since they
239    /// usually mean DNS or TCP-level glitches.
240    ///
241    /// All cryptographic, schema, and authorization errors are NOT
242    /// transient: a malformed body or invalid signature will not
243    /// magically validate on retry.
244    pub fn is_transient(&self) -> bool {
245        matches!(
246            self,
247            AcdpError::KeyResolutionUnreachable(_)
248                | AcdpError::RateLimited(_)
249                | AcdpError::CrossRegistryResolutionFailed(_)
250                | AcdpError::RegistryInternal(_)
251                | AcdpError::Http(_)
252        )
253    }
254
255    /// Map a wire-protocol [`crate::wire_error::WireError`] into a typed
256    /// [`AcdpError`].
257    ///
258    /// Codes the library does not yet recognize are returned as
259    /// [`AcdpError::Registry`] for forward compatibility.
260    pub fn from_wire_error(wire: crate::wire_error::WireError) -> Self {
261        let code = wire.error.code.as_str();
262        let msg = wire.error.message.clone();
263
264        match code {
265            "invalid_signature" => AcdpError::InvalidSignature(msg),
266            "hash_mismatch" => AcdpError::RemoteHashMismatch(msg),
267            "data_ref_hash_mismatch" => AcdpError::DataRefHashMismatch(msg),
268            "schema_violation" => AcdpError::SchemaViolation(msg),
269            "not_authorized" => AcdpError::NotAuthorized(msg),
270            "not_found" => AcdpError::NotFound(msg),
271            "rate_limited" => AcdpError::RateLimited(msg),
272            "payload_too_large" => AcdpError::PayloadTooLarge(msg),
273            "embedded_too_large" => AcdpError::EmbeddedTooLarge(msg),
274            "key_resolution_failed" => AcdpError::KeyResolution(msg),
275            "key_resolution_unreachable" => AcdpError::KeyResolutionUnreachable(msg),
276            "key_not_authorized" => AcdpError::KeyNotAuthorized(msg),
277            "unsupported_algorithm" => AcdpError::UnsupportedAlgorithm(msg),
278            "not_implemented" => AcdpError::NotImplemented(msg),
279            "cursor_expired" => AcdpError::CursorExpired,
280            "invalid_cursor" => AcdpError::InvalidCursor(msg),
281            "duplicate_publish" => AcdpError::DuplicatePublish(msg),
282            "cross_registry_resolution_failed" => AcdpError::CrossRegistryResolutionFailed(msg),
283            "invalid_receipt" => AcdpError::InvalidReceipt(msg),
284            "invalid_log_proof" => AcdpError::InvalidLogProof(msg),
285            "immutable_field" => AcdpError::ImmutableField(msg),
286            "invalid_lifecycle_transition" => AcdpError::InvalidLifecycleTransition(msg),
287            "internal_error" => AcdpError::RegistryInternal(msg),
288            "superseded_target" => {
289                let reason = wire
290                    .error
291                    .details
292                    .as_ref()
293                    .and_then(|d| d.get("reason"))
294                    .and_then(|v| serde_json::from_value::<SupersessionReason>(v.clone()).ok())
295                    .unwrap_or(SupersessionReason::Other);
296                AcdpError::SupersededTarget {
297                    reason,
298                    message: msg,
299                }
300            }
301            // Unknown / future codes pass through as the catch-all variant
302            _ => AcdpError::Registry(wire),
303        }
304    }
305}
306
307impl From<serde_json::Error> for AcdpError {
308    fn from(e: serde_json::Error) -> Self {
309        AcdpError::Serialization(e.to_string())
310    }
311}
312
313impl From<std::io::Error> for AcdpError {
314    fn from(e: std::io::Error) -> Self {
315        AcdpError::Http(format!("io error: {e}"))
316    }
317}
318
319#[cfg(feature = "reqwest")]
320impl From<reqwest::Error> for AcdpError {
321    fn from(e: reqwest::Error) -> Self {
322        if e.is_connect() || e.is_timeout() {
323            AcdpError::Http(format!("connection failed: {e}"))
324        } else {
325            AcdpError::Http(e.to_string())
326        }
327    }
328}
329
330#[cfg(test)]
331mod tests {
332    use super::*;
333    use crate::wire_error::{WireError, WireErrorBody};
334    use serde_json::json;
335
336    fn wire(code: &str, message: &str, details: Option<serde_json::Value>) -> WireError {
337        WireError {
338            error: WireErrorBody {
339                code: code.into(),
340                message: message.into(),
341                details,
342            },
343        }
344    }
345
346    #[test]
347    fn all_24_wire_codes_round_trip() {
348        // Test-coverage matrix entry: "All 24 error codes parse from WireError".
349        // Every code enumerated by acdp-error.schema.json's enum MUST map to a
350        // typed AcdpError variant (or, for `superseded_target` with details,
351        // produce the right SupersessionReason).
352        type Check = fn(&AcdpError) -> bool;
353        let cases: &[(&str, Check)] = &[
354            ("invalid_signature", |e| {
355                matches!(e, AcdpError::InvalidSignature(_))
356            }),
357            ("hash_mismatch", |e| {
358                matches!(e, AcdpError::RemoteHashMismatch(_))
359            }),
360            ("data_ref_hash_mismatch", |e| {
361                matches!(e, AcdpError::DataRefHashMismatch(_))
362            }),
363            ("schema_violation", |e| {
364                matches!(e, AcdpError::SchemaViolation(_))
365            }),
366            ("not_authorized", |e| {
367                matches!(e, AcdpError::NotAuthorized(_))
368            }),
369            ("not_found", |e| matches!(e, AcdpError::NotFound(_))),
370            ("superseded_target", |e| {
371                matches!(e, AcdpError::SupersededTarget { .. })
372            }),
373            ("unsupported_algorithm", |e| {
374                matches!(e, AcdpError::UnsupportedAlgorithm(_))
375            }),
376            ("rate_limited", |e| matches!(e, AcdpError::RateLimited(_))),
377            ("payload_too_large", |e| {
378                matches!(e, AcdpError::PayloadTooLarge(_))
379            }),
380            ("embedded_too_large", |e| {
381                matches!(e, AcdpError::EmbeddedTooLarge(_))
382            }),
383            ("key_resolution_failed", |e| {
384                matches!(e, AcdpError::KeyResolution(_))
385            }),
386            ("key_resolution_unreachable", |e| {
387                matches!(e, AcdpError::KeyResolutionUnreachable(_))
388            }),
389            ("key_not_authorized", |e| {
390                matches!(e, AcdpError::KeyNotAuthorized(_))
391            }),
392            ("not_implemented", |e| {
393                matches!(e, AcdpError::NotImplemented(_))
394            }),
395            ("cursor_expired", |e| matches!(e, AcdpError::CursorExpired)),
396            ("invalid_cursor", |e| {
397                matches!(e, AcdpError::InvalidCursor(_))
398            }),
399            ("duplicate_publish", |e| {
400                matches!(e, AcdpError::DuplicatePublish(_))
401            }),
402            ("cross_registry_resolution_failed", |e| {
403                matches!(e, AcdpError::CrossRegistryResolutionFailed(_))
404            }),
405            ("invalid_receipt", |e| {
406                matches!(e, AcdpError::InvalidReceipt(_))
407            }),
408            ("invalid_log_proof", |e| {
409                matches!(e, AcdpError::InvalidLogProof(_))
410            }),
411            ("immutable_field", |e| {
412                matches!(e, AcdpError::ImmutableField(_))
413            }),
414            ("invalid_lifecycle_transition", |e| {
415                matches!(e, AcdpError::InvalidLifecycleTransition(_))
416            }),
417            ("internal_error", |e| {
418                matches!(e, AcdpError::RegistryInternal(_))
419            }),
420        ];
421        // Schema enumerates exactly 24 codes (RFC-ACDP-0007 §5 + the
422        // RFC-ACDP-0010 `invalid_receipt` addition + the 0.3.0 codes:
423        // `invalid_log_proof` (RFC-0012), `immutable_field` and
424        // `invalid_lifecycle_transition` (RFC-0013)).
425        assert_eq!(cases.len(), 24);
426        for (code, expected) in cases {
427            let err = AcdpError::from_wire_error(wire(code, "msg", None));
428            assert!(
429                expected(&err),
430                "code '{code}' did not map to its typed variant: got {err:?}"
431            );
432        }
433    }
434
435    #[test]
436    fn superseded_target_with_reason_details() {
437        let w = wire(
438            "superseded_target",
439            "lineage mismatch",
440            Some(json!({"reason": "lineage_mismatch"})),
441        );
442        match AcdpError::from_wire_error(w) {
443            AcdpError::SupersededTarget { reason, .. } => {
444                assert_eq!(reason, SupersessionReason::LineageMismatch);
445            }
446            other => panic!("expected SupersededTarget, got {other:?}"),
447        }
448    }
449
450    #[test]
451    fn superseded_target_without_details_falls_back_to_other() {
452        let w = wire("superseded_target", "?", None);
453        match AcdpError::from_wire_error(w) {
454            AcdpError::SupersededTarget { reason, .. } => {
455                assert_eq!(reason, SupersessionReason::Other);
456            }
457            other => panic!("got {other:?}"),
458        }
459    }
460
461    #[test]
462    fn unknown_code_passes_through_as_registry() {
463        let w = wire("unsupported_embedding_model", "reserved future code", None);
464        assert!(matches!(
465            AcdpError::from_wire_error(w),
466            AcdpError::Registry(_)
467        ));
468    }
469
470    /// T4 — `lineage_walk_failed` reason round-trips via WireError
471    /// (RFC-ACDP-0001 §5.6.1).
472    #[test]
473    fn lineage_walk_failed_reason_roundtrip() {
474        let w = wire(
475            "superseded_target",
476            "intermediate not retrievable",
477            Some(json!({
478                "reason": "lineage_walk_failed",
479                "unreachable_ctx_id":
480                    "acdp://r.example.com/12345678-1234-4321-8123-123456781234"
481            })),
482        );
483        match AcdpError::from_wire_error(w) {
484            AcdpError::SupersededTarget { reason, .. } => {
485                assert_eq!(reason, SupersessionReason::LineageWalkFailed);
486            }
487            other => panic!("got {other:?}"),
488        }
489    }
490
491    /// `is_transient` covers the wire codes the spec marks retryable.
492    #[test]
493    fn is_transient_for_known_retryables() {
494        assert!(AcdpError::KeyResolutionUnreachable("x".into()).is_transient());
495        assert!(AcdpError::RateLimited("x".into()).is_transient());
496        assert!(AcdpError::CrossRegistryResolutionFailed("x".into()).is_transient());
497        assert!(AcdpError::RegistryInternal("x".into()).is_transient());
498        assert!(AcdpError::Http("x".into()).is_transient());
499        assert!(!AcdpError::SchemaViolation("x".into()).is_transient());
500        assert!(!AcdpError::InvalidSignature("x".into()).is_transient());
501        assert!(!AcdpError::NotFound("x".into()).is_transient());
502        // BUG-02: data-ref hash mismatch is a data-integrity failure;
503        // retrying the SAME publish/fetch will return the same answer.
504        // The spec marks it permanent, not retryable.
505        assert!(!AcdpError::DataRefHashMismatch("x".into()).is_transient());
506        // RFC-ACDP-0010: a failed receipt will not verify on retry.
507        assert!(!AcdpError::InvalidReceipt("x".into()).is_transient());
508        assert!(!AcdpError::InvalidLogProof("x".into()).is_transient());
509        assert!(!AcdpError::ImmutableField("x".into()).is_transient());
510        assert!(!AcdpError::InvalidLifecycleTransition("x".into()).is_transient());
511    }
512}