Skip to main content

ratify_protocol/v2/
errors.rs

1//! Language-neutral Protocol v2 failure classes (SPEC-v2 §2.7, Go
2//! `errors_v2.go`) and the typed signing error (SPEC-v2 §3.2).
3
4use std::fmt;
5
6macro_rules! error_classes {
7    ($($variant:ident => $text:literal,)*) => {
8        /// The closed list of SPEC-v2 §2.7 failure classes. Every v2 failure
9        /// that is not a terminal Protocol result, a release result, or a
10        /// signing error has exactly one of these classes. Messages are
11        /// diagnostic only; conformance compares classes.
12        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
13        pub enum V2ErrorClass {
14            $($variant,)*
15        }
16
17        impl V2ErrorClass {
18            /// Every class, in SPEC-v2 §2.7 table order.
19            pub const ALL: &'static [V2ErrorClass] = &[$(V2ErrorClass::$variant,)*];
20
21            /// The spelling shared by every SDK and the conformance corpus.
22            pub fn as_str(self) -> &'static str {
23                match self {
24                    $(V2ErrorClass::$variant => $text,)*
25                }
26            }
27
28            /// Parse a class spelling; `None` for anything outside §2.7.
29            pub fn parse(text: &str) -> Option<V2ErrorClass> {
30                match text {
31                    $($text => Some(V2ErrorClass::$variant),)*
32                    _ => None,
33                }
34            }
35        }
36    };
37}
38
39error_classes! {
40    Malformed => "malformed",
41    UnsupportedObjectType => "unsupported_object_type",
42    KeyIdMismatch => "key_id_mismatch",
43    DelegationDigestMismatch => "delegation_digest_mismatch",
44    ChainLinkageMismatch => "chain_linkage_mismatch",
45    DuplicateCertificateRef => "duplicate_certificate_ref",
46    InvalidSignature => "invalid_signature",
47    InvalidRequiredScope => "invalid_required_scope",
48    ConfigurationInvalid => "configuration_invalid",
49    ExpectedChallengeUnavailable => "expected_challenge_unavailable",
50    NamespaceMismatch => "namespace_mismatch",
51    StaleReplayEpoch => "stale_replay_epoch",
52    VerifierIdMismatch => "verifier_id_mismatch",
53    ChallengeMismatch => "challenge_mismatch",
54    ChallengeNotFresh => "challenge_not_fresh",
55    ExpectedAgentMismatch => "expected_agent_mismatch",
56    SessionContextMismatch => "session_context_mismatch",
57    ReceiverAudienceRequired => "receiver_audience_required",
58    ReceiverAudienceMismatch => "receiver_audience_mismatch",
59    ReceiverBindingRejected => "receiver_binding_rejected",
60    ClaimReplay => "claim_replay",
61    StreamSequenceMismatch => "stream_sequence_mismatch",
62    ClaimStoreUnavailable => "claim_store_unavailable",
63    ReceiptAbandoned => "receipt_abandoned",
64    EvaluationCancelled => "evaluation_cancelled",
65    ClockRegressed => "clock_regressed",
66    AllowHorizonPassed => "allow_horizon_passed",
67    ClaimLeaseLive => "claim_lease_live",
68    ClaimLeaseLost => "claim_lease_lost",
69    ClaimAlreadyTerminal => "claim_already_terminal",
70    ClaimNotFound => "claim_not_found",
71    StatusKeyBindingMismatch => "status_key_binding_mismatch",
72    StatusObjectRejected => "status_object_rejected",
73    ReceiptBundleMismatch => "receipt_bundle_mismatch",
74    BundleHashMismatch => "bundle_hash_mismatch",
75    TransactionPartyMismatch => "transaction_party_mismatch",
76    TransactionContextMismatch => "transaction_context_mismatch",
77    TransactionSignatureSetInvalid => "transaction_signature_set_invalid",
78    RotationStateMismatch => "rotation_state_mismatch",
79    RotationKeyReused => "rotation_key_reused",
80    RotationFutureDated => "rotation_future_dated",
81    RotationFork => "rotation_fork",
82    RotationFrozen => "rotation_frozen",
83    RotationRecoveryInvalid => "rotation_recovery_invalid",
84    LogStateMismatch => "log_state_mismatch",
85    LogGap => "log_gap",
86    LogOrphan => "log_orphan",
87    LogFork => "log_fork",
88    LogFrozen => "log_frozen",
89}
90
91impl fmt::Display for V2ErrorClass {
92    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93        f.write_str(self.as_str())
94    }
95}
96
97/// A classified Protocol v2 failure. `class` is the conformance-relevant
98/// part; `message` is diagnostic text only.
99///
100/// Internally an error may be created before its class is known (the Go
101/// reference's unclassified error, later passed through `v2Classify`). Such an
102/// error carries a provisional `malformed` class until the first
103/// [`V2Error::classify`] fixes it, so a public API never reports a class
104/// outside SPEC-v2 §2.7.
105#[derive(Debug, Clone, PartialEq, Eq)]
106pub struct V2Error {
107    pub class: V2ErrorClass,
108    pub message: String,
109    explicit: bool,
110}
111
112impl V2Error {
113    /// A classified error.
114    pub fn new(class: V2ErrorClass, message: impl Into<String>) -> Self {
115        V2Error {
116            class,
117            message: message.into(),
118            explicit: true,
119        }
120    }
121
122    /// An error whose class is assigned later by [`V2Error::classify`]
123    /// (Go: a plain `error`). Until then it reports `malformed`.
124    pub(crate) fn plain(message: impl Into<String>) -> Self {
125        V2Error {
126            class: V2ErrorClass::Malformed,
127            message: message.into(),
128            explicit: false,
129        }
130    }
131
132    /// Go `v2Classify`: assign `class` only when no class was fixed yet.
133    pub fn classify(mut self, class: V2ErrorClass) -> Self {
134        if !self.explicit {
135            self.class = class;
136            self.explicit = true;
137        }
138        self
139    }
140
141    /// Whether the class was fixed deliberately (Go: the error is a
142    /// `*V2Error`); false for a provisional (Go: unclassified) error.
143    pub(crate) fn is_classified(&self) -> bool {
144        self.explicit
145    }
146
147    /// Prefix the diagnostic message, keeping the class.
148    pub fn context(mut self, prefix: impl fmt::Display) -> Self {
149        self.message = format!("{prefix}: {}", self.message);
150        self
151    }
152}
153
154impl fmt::Display for V2Error {
155    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156        write!(f, "{} ({})", self.message, self.class)
157    }
158}
159
160impl std::error::Error for V2Error {}
161
162/// Result alias for Protocol v2 operations.
163pub type V2Result<T> = Result<T, V2Error>;
164
165pub(crate) fn err<T>(class: V2ErrorClass, message: impl Into<String>) -> V2Result<T> {
166    Err(V2Error::new(class, message))
167}
168
169pub(crate) fn plain<T>(message: impl Into<String>) -> V2Result<T> {
170    Err(V2Error::plain(message))
171}
172
173pub(crate) trait Classify<T> {
174    fn classify(self, class: V2ErrorClass) -> V2Result<T>;
175}
176
177impl<T> Classify<T> for V2Result<T> {
178    fn classify(self, class: V2ErrorClass) -> V2Result<T> {
179        self.map_err(|e| e.classify(class))
180    }
181}
182
183/// Go `V2ErrorClassOf`: `None` for success.
184pub fn v2_error_class_of<T>(result: &V2Result<T>) -> Option<V2ErrorClass> {
185    result.as_ref().err().map(|e| e.class)
186}
187
188/// A typed signing failure (SPEC-v2 §3.2). Signing failures are not
189/// verification error classes: a refusal creates no object and no signer
190/// method runs after an issuer-duty or validation refusal.
191#[derive(Debug, Clone, PartialEq, Eq)]
192pub enum V2SignError {
193    /// The object fails its schema, bounds, or encoding (the wrapped error
194    /// carries the class a decoder would report).
195    InvalidObject(V2Error),
196    /// An issuer duty (SPEC-v2 §5.1, §5.4) refuses the object.
197    IssuerDuty(String),
198    /// The signer's complete key is not the key the object or the
199    /// caller-authenticated configuration names for this role.
200    KeyBinding(String),
201    /// The signer reported an invalid public key or private key material.
202    InvalidSignerKey(String),
203    /// The signer reported a mode this SDK does not implement.
204    UnsupportedMode,
205    /// The provider failed or refused.
206    Provider(String),
207    /// The caller's context was cancelled before or during signing; any
208    /// signature that arrived afterwards was discarded.
209    Cancelled,
210    /// The provider returned a signature that does not verify under the
211    /// bound key over the SDK-computed message and context.
212    SignatureRejected(V2Error),
213}
214
215impl fmt::Display for V2SignError {
216    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217        match self {
218            V2SignError::InvalidObject(e) => write!(f, "v2 signing refused: {e}"),
219            V2SignError::IssuerDuty(m) => write!(f, "v2 issuer duty: {m}"),
220            V2SignError::KeyBinding(m) => write!(f, "v2 signer key binding: {m}"),
221            V2SignError::InvalidSignerKey(m) => write!(f, "v2 signer key: {m}"),
222            V2SignError::UnsupportedMode => f.write_str("v2 signer reports an unsupported mode"),
223            V2SignError::Provider(m) => write!(f, "v2 signer: {m}"),
224            V2SignError::Cancelled => f.write_str("v2 signing cancelled"),
225            V2SignError::SignatureRejected(e) => {
226                write!(f, "v2 signer returned a signature that does not verify: {e}")
227            }
228        }
229    }
230}
231
232impl std::error::Error for V2SignError {}
233
234impl V2SignError {
235    /// The SPEC-v2 §2.7 class of this signing failure; every public v2 error
236    /// carries exactly one. An invalid object keeps the class of its wrapped
237    /// error; an issuer-duty refusal is `malformed`; a signer whose key is not
238    /// the key the object names is `key_id_mismatch`; a missing, invalid, or
239    /// failing signer is `configuration_invalid`; cancellation is
240    /// `evaluation_cancelled`; and a returned signature that does not verify is
241    /// `invalid_signature`. Operations whose refusal has another class (for
242    /// example a status-key binding) return it as [`V2SignError::InvalidObject`].
243    pub fn class(&self) -> V2ErrorClass {
244        match self {
245            V2SignError::InvalidObject(e) => e.class,
246            V2SignError::IssuerDuty(_) => V2ErrorClass::Malformed,
247            V2SignError::KeyBinding(_) => V2ErrorClass::KeyIdMismatch,
248            V2SignError::InvalidSignerKey(_) | V2SignError::UnsupportedMode | V2SignError::Provider(_) => {
249                V2ErrorClass::ConfigurationInvalid
250            }
251            V2SignError::Cancelled => V2ErrorClass::EvaluationCancelled,
252            V2SignError::SignatureRejected(_) => V2ErrorClass::InvalidSignature,
253        }
254    }
255}
256
257impl From<V2Error> for V2SignError {
258    fn from(e: V2Error) -> Self {
259        V2SignError::InvalidObject(e)
260    }
261}
262
263/// Result alias for typed v2 signing.
264pub type V2SignResult<T> = Result<T, V2SignError>;