jose_rs/error.rs
1//! Error and result types for JOSE operations.
2
3/// Errors produced by JOSE operations.
4#[derive(Debug, thiserror::Error)]
5pub enum JoseError {
6 /// A cryptographic backend operation failed.
7 #[error("cryptographic error: {0}")]
8 Crypto(#[from] kryptering::Error),
9
10 /// A serialized JOSE token is malformed or fails structural validation.
11 #[error("invalid token format: {0}")]
12 InvalidToken(String),
13
14 /// A JOSE protected header is malformed or violates configured policy.
15 #[error("invalid header: {0}")]
16 InvalidHeader(String),
17
18 /// JWT claims are malformed or violate configured validation policy.
19 #[error("invalid claims: {0}")]
20 InvalidClaims(String),
21
22 /// The requested or encoded JOSE algorithm is unsupported.
23 #[error("unsupported algorithm: {0}")]
24 UnsupportedAlgorithm(String),
25
26 /// Key material is malformed, incomplete, or incompatible with an operation.
27 #[error("key error: {0}")]
28 Key(String),
29
30 /// JWT validation found that the token has expired.
31 #[error("token expired")]
32 Expired,
33
34 /// JWT validation found that the token is not valid yet.
35 #[error("token not yet valid")]
36 NotYetValid,
37
38 /// The JWT issuer does not match the configured issuer.
39 #[error("invalid issuer")]
40 InvalidIssuer,
41
42 /// The JWT audience does not contain the configured audience.
43 #[error("invalid audience")]
44 InvalidAudience,
45
46 /// JSON serialization or deserialization failed.
47 #[error("JSON error: {0}")]
48 Json(#[from] serde_json::Error),
49
50 /// Base64url decoding failed.
51 #[error("base64 decode error: {0}")]
52 Base64(String),
53}
54
55/// The coarse kind of an error, for callers who need to branch without matching on
56/// every variant.
57///
58/// Why this exists rather than more variants: [`JoseError`] is an exhaustive enum,
59/// so adding a variant is a breaking change for every downstream `match`, while a
60/// category is additive and can be extended without one. Match on this when the
61/// question is "what sort of thing went wrong"; match on [`JoseError`] when the
62/// answer must distinguish, say, expiry from audience.
63///
64/// # What this deliberately does not separate
65///
66/// [`ErrorCategory::Cryptographic`] covers *both* "the MAC/tag did not match" and
67/// "the backend refused the key", and no accessor splits them. That is not laziness:
68/// a caller-visible distinction between an integrity failure and a key failure is an
69/// oracle — it tells a prober whether a structure was well-formed enough to reach the
70/// tag check, which is precisely how padding and oracle attacks get their signal. The
71/// distinction exists internally; it is not exported.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
73#[non_exhaustive]
74pub enum ErrorCategory {
75 /// This build cannot perform the requested capability: an algorithm, curve, key
76 /// type, or serialization it does not implement. Retrying with different input
77 /// will not help; enabling a feature or changing the request will.
78 UnsupportedCapability,
79
80 /// The document could not be parsed, or it parsed and violated its own
81 /// structure rules: malformed base64url, a duplicated member, a `crit` naming
82 /// an absent parameter, claims that are not an object.
83 InvalidStructure,
84
85 /// The document was well-formed and cryptographically fine, but the caller's
86 /// policy refused it: expiry, not-yet-valid, issuer, audience.
87 PolicyRejection,
88
89 /// A signature or MAC was checked and returned "does not verify".
90 ///
91 /// Only produced where this crate can say so precisely: its own verdict from a
92 /// completed check. A backend that *refuses* a signature as malformed (an ECDSA
93 /// scalar outside the curve order, for instance) arrives as
94 /// [`ErrorCategory::Cryptographic`] instead, and the two are deliberately not
95 /// reconciled into one bucket by inspecting messages. Both mean "this did not
96 /// authenticate"; a caller that branches differently on which of the two it was
97 /// has built the oracle this design refuses to expose. Use
98 /// [`JoseError::is_authentication_failure`] for the merged question.
99 AuthenticationFailure,
100
101 /// A key is malformed, incomplete, or not permitted for the operation
102 /// (`use`/`key_ops`, a pinned `alg` mismatch, a size below the algorithm's
103 /// minimum).
104 KeyMaterial,
105
106 /// A cryptographic backend reported a failure. Covers integrity failures of
107 /// encrypted content, which are intentionally not labelled as such.
108 Cryptographic,
109
110 /// Encoding or serialization failure at the JSON/base64url boundary.
111 Encoding,
112}
113
114impl JoseError {
115 /// Classify this error.
116 ///
117 /// Coarse by design. Note that [`JoseError::InvalidHeader`] and
118 /// [`JoseError::InvalidClaims`] land in
119 /// [`ErrorCategory::InvalidStructure`] even when the message describes a policy
120 /// refusal (e.g. a required `kid`): the variants carry structure *and* policy
121 /// cases, and claiming a finer split than the variants express would make the
122 /// category a second, contradicting source of truth. Use the specific variants
123 /// when the distinction matters.
124 pub fn category(&self) -> ErrorCategory {
125 match self {
126 JoseError::UnsupportedAlgorithm(_) => ErrorCategory::UnsupportedCapability,
127 JoseError::InvalidToken(_)
128 | JoseError::InvalidHeader(_)
129 | JoseError::InvalidClaims(_) => {
130 // A signature that simply did not verify is reported as
131 // `InvalidToken` with this crate's own fixed message. Comparing
132 // against the constant this crate emits — rather than substring
133 // sniffing arbitrary text — keeps the classification exact.
134 if self.is_own_authentication_failure() {
135 ErrorCategory::AuthenticationFailure
136 } else {
137 ErrorCategory::InvalidStructure
138 }
139 }
140 JoseError::Expired
141 | JoseError::NotYetValid
142 | JoseError::InvalidIssuer
143 | JoseError::InvalidAudience => ErrorCategory::PolicyRejection,
144 JoseError::Key(_) => ErrorCategory::KeyMaterial,
145 JoseError::Crypto(_) => ErrorCategory::Cryptographic,
146 JoseError::Json(_) | JoseError::Base64(_) => ErrorCategory::Encoding,
147 }
148 }
149
150 /// The merged question: "did a verification fail?".
151 ///
152 /// True for this crate's own "signature did not verify" verdict *and* for backend
153 /// cryptographic failures. On a path that was verifying or decrypting, that union is
154 /// exactly "the credential did not authenticate", and it is exposed as one answer
155 /// because splitting it (was the tag wrong, or was the structure refused on the way to
156 /// the tag?) is a signal an attacker can request.
157 ///
158 /// Call it only on errors from a verify/decrypt path: on a key-import or encryption
159 /// path a [`JoseError::Crypto`] means something else entirely, and this function
160 /// cannot tell which path produced the error.
161 pub fn is_authentication_failure(&self) -> bool {
162 match self {
163 JoseError::Crypto(_) => true,
164 JoseError::InvalidToken(message) => message == crate::SIGNATURE_VERIFICATION_FAILED,
165 _ => false,
166 }
167 }
168
169 /// `true` when this is this crate's own "the signature did not verify" verdict.
170 ///
171 /// Implemented against the constants this crate raises, not by searching
172 /// messages: a heuristic over error text would classify a *description* of a
173 /// failure as the failure itself.
174 fn is_own_authentication_failure(&self) -> bool {
175 match self {
176 JoseError::InvalidToken(message) => message == crate::SIGNATURE_VERIFICATION_FAILED,
177 _ => false,
178 }
179 }
180}
181
182/// Result type returned by `jose-rs` operations.
183pub type Result<T> = std::result::Result<T, JoseError>;