1use std::fmt;
5
6macro_rules! error_classes {
7 ($($variant:ident => $text:literal,)*) => {
8 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
13 pub enum V2ErrorClass {
14 $($variant,)*
15 }
16
17 impl V2ErrorClass {
18 pub const ALL: &'static [V2ErrorClass] = &[$(V2ErrorClass::$variant,)*];
20
21 pub fn as_str(self) -> &'static str {
23 match self {
24 $(V2ErrorClass::$variant => $text,)*
25 }
26 }
27
28 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#[derive(Debug, Clone, PartialEq, Eq)]
106pub struct V2Error {
107 pub class: V2ErrorClass,
108 pub message: String,
109 explicit: bool,
110}
111
112impl V2Error {
113 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 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 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 pub(crate) fn is_classified(&self) -> bool {
144 self.explicit
145 }
146
147 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
162pub 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
183pub fn v2_error_class_of<T>(result: &V2Result<T>) -> Option<V2ErrorClass> {
185 result.as_ref().err().map(|e| e.class)
186}
187
188#[derive(Debug, Clone, PartialEq, Eq)]
192pub enum V2SignError {
193 InvalidObject(V2Error),
196 IssuerDuty(String),
198 KeyBinding(String),
201 InvalidSignerKey(String),
203 UnsupportedMode,
205 Provider(String),
207 Cancelled,
210 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 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
263pub type V2SignResult<T> = Result<T, V2SignError>;