identity_kit/vc/validation/error.rs
1//! Validation errors.
2
3use core::fmt;
4use std::collections::BTreeMap;
5
6use chrono::{DateTime, Utc};
7
8use crate::cause::cause;
9use crate::did::{OneOrMany, Uri};
10use crate::jose::{JwsError, VerificationError};
11use crate::resolver::{JwsKeyError, KeyReference, KeyReferenceError, KeyResolutionError};
12use crate::vc::CredentialError;
13
14impl From<JwsKeyError> for ValidationError {
15 fn from(error: JwsKeyError) -> Self {
16 match error {
17 JwsKeyError::Reference(error) => Self::KeyReference(error),
18 JwsKeyError::Resolution { key, source } => Self::KeyResolution { key, source },
19 }
20 }
21}
22
23/// Why a credential or presentation JWT did not validate.
24#[derive(Debug, thiserror::Error)]
25#[non_exhaustive]
26pub enum ValidationError {
27 /// The token is not a compact JWS this crate decodes.
28 #[error("invalid JWS: {0}")]
29 Jws(#[from] JwsError),
30 /// The JWS header names no key this crate can look for: no `kid`, a `kid` that is not a
31 /// DID URL, a DID URL with a path or DID parameters, a relative `kid` without a DID issuer.
32 #[error(transparent)]
33 KeyReference(#[from] KeyReferenceError),
34 /// The header `typ` is not the one the profile requires.
35 #[error("header `typ` is {found:?}, not `{expected}`")]
36 UnexpectedTyp {
37 /// The `typ` the profile requires.
38 expected: &'static str,
39 /// The `typ` found.
40 found: String,
41 },
42 /// The payload is not a JSON claims set; the source is the JSON error.
43 #[error("the payload is not a JWT claims set: {0}")]
44 Payload(#[source] serde_json::Error),
45 /// The claims do not map to a credential or presentation.
46 #[error(transparent)]
47 Credential(#[from] CredentialError),
48 /// The payload carries `_sd_alg`, `_sd` or an array element `{"...": "<digest>"}`: it is
49 /// the issuer-signed JWT of an SD-JWT, whose claims mean something else until its
50 /// disclosures are processed, so it is not read as a plain JWT (RFC 8725 §3.12).
51 /// `SdJwtCredentialValidator` of `sd_jwt_vc` validates it.
52 #[error("the payload carries `{claim}`, so it is an SD-JWT, not a plain JWT")]
53 SdJwtPayload {
54 /// The claim found: `_sd_alg`, `_sd` or `...`.
55 claim: &'static str,
56 },
57 /// The key the token names could not be resolved.
58 #[error("resolving key {key}: {source}")]
59 KeyResolution {
60 /// Where the token says its key is.
61 key: Box<KeyReference>,
62 /// What went wrong.
63 #[source]
64 source: KeyResolutionError,
65 },
66 /// The signature does not verify under the resolved key.
67 #[error("signature: {0}")]
68 Signature(#[from] VerificationError),
69 /// The issuer of the credential does not control the key that signed it.
70 #[error("issuer `{issuer}` does not control signing key {key}")]
71 IssuerMismatch {
72 /// The issuer of the credential.
73 issuer: Uri,
74 /// Where the token says its key is.
75 key: Box<KeyReference>,
76 },
77 /// The issuer is not a DID, so no key of it can be resolved.
78 #[error("{role} `{id}` is not a DID")]
79 NotDid {
80 /// `issuer` or `holder`.
81 role: &'static str,
82 /// The identifier.
83 id: String,
84 },
85 /// The holder of the presentation does not control the key that signed it.
86 #[error("holder `{holder}` does not control signing key {key}")]
87 HolderMismatch {
88 /// The holder of the presentation.
89 holder: Uri,
90 /// Where the token says its key is.
91 key: Box<KeyReference>,
92 },
93 /// The token or credential is not valid yet.
94 #[error("not valid before {} (now is {})", not_before.to_rfc3339(), now.to_rfc3339())]
95 NotYetValid {
96 /// When it becomes valid.
97 not_before: DateTime<Utc>,
98 /// The validation time.
99 now: DateTime<Utc>,
100 },
101 /// The token or credential has expired.
102 #[error("expired at {} (now is {})", expired_at.to_rfc3339(), now.to_rfc3339())]
103 Expired {
104 /// When it expired.
105 expired_at: DateTime<Utc>,
106 /// The validation time.
107 now: DateTime<Utc>,
108 },
109 /// The token claims to have been issued in the future.
110 #[error("issued at {}, after now ({})", issued_at.to_rfc3339(), now.to_rfc3339())]
111 IssuedInFuture {
112 /// The `iat`.
113 issued_at: DateTime<Utc>,
114 /// The validation time.
115 now: DateTime<Utc>,
116 },
117 /// The `aud` does not include the expected audience.
118 #[error("audience {found:?} does not include {expected:?}")]
119 AudienceMismatch {
120 /// The audience expected.
121 expected: String,
122 /// The `aud` found.
123 found: Option<OneOrMany<String>>,
124 },
125 /// The `nonce` is not the expected one.
126 #[error("nonce {found:?} is not {expected:?}")]
127 NonceMismatch {
128 /// The nonce expected.
129 expected: String,
130 /// The `nonce` found.
131 found: Option<String>,
132 },
133 /// The credential has a `credentialStatus` and the validator has no
134 /// [`StatusCheck`](super::StatusCheck) for it.
135 #[error("`credentialStatus` of type `{0}` cannot be checked")]
136 StatusUnchecked(String),
137 /// The status check failed or found the credential revoked or suspended.
138 #[error("credential status: {0}")]
139 Status(#[from] StatusError),
140 /// The subject of a presented credential is not the holder presenting it.
141 #[error("credential subject {subject:?} is not the holder `{holder}`")]
142 SubjectHolderMismatch {
143 /// The `id` of the subject, if any.
144 subject: Option<Uri>,
145 /// The holder of the presentation.
146 holder: Uri,
147 },
148 /// A credential secured with SD-JWT, enveloped in a presentation, failed a check of its
149 /// own: it is not a well-formed SD-JWT credential, or its key binding is missing or wrong.
150 /// (A check shared with the JWT validators is reported as that check's own variant.)
151 #[cfg(feature = "sd-jwt")]
152 #[cfg_attr(docsrs, doc(cfg(feature = "sd-jwt")))]
153 #[error(transparent)]
154 SdJwt(Box<crate::sd_jwt_vc::SdJwtValidationError>),
155}
156
157#[cfg(feature = "sd-jwt")]
158impl From<crate::sd_jwt_vc::SdJwtValidationError> for ValidationError {
159 /// Unwraps a shared check's error; boxes the SD-JWT-specific ones.
160 fn from(error: crate::sd_jwt_vc::SdJwtValidationError) -> Self {
161 match error {
162 crate::sd_jwt_vc::SdJwtValidationError::Validation(error) => error,
163 other => Self::SdJwt(Box::new(other)),
164 }
165 }
166}
167
168/// Why a [`StatusCheck`] did not pass.
169///
170/// The variants tell apart what a caller may want to handle differently: an
171/// [`Unavailable`](Self::Unavailable) list may be fetched on a later attempt, an
172/// [`Expired`](Self::Expired) one may be valid once its provider has refreshed it, and an
173/// [`UnresolvedKey`](Self::UnresolvedKey) depends on why the resolver failed, which its source
174/// says. An [`InvalidList`](Self::InvalidList) or an
175/// [`IndexOutOfRange`](Self::IndexOutOfRange) will not pass by trying again.
176///
177/// Where a variant has a `source`, [`Error::source`](std::error::Error::source) returns it,
178/// and the message ends with it.
179///
180/// [`StatusCheck`]: super::StatusCheck
181#[derive(Debug, thiserror::Error)]
182#[non_exhaustive]
183pub enum StatusError {
184 /// The check does not understand the status type.
185 #[error("status type `{0}` is not supported")]
186 Unsupported(String),
187 /// The status list could not be fetched: the request failed, the server answered with an
188 /// error status, or the check refused a redirect. The source is the client's error, when
189 /// there is one.
190 #[error("status list {uri} unavailable: {reason}{}", cause(.source.as_ref()))]
191 Unavailable {
192 /// The status list URI the credential references.
193 uri: String,
194 /// What went wrong, naming the URL of a redirect hop where it is not `uri`.
195 reason: String,
196 /// The underlying error.
197 source: Option<Box<dyn std::error::Error + Send + Sync>>,
198 },
199 /// The reference or the status list is not one the check can read or trust: a URI that is
200 /// not a URL, a body that is not a status list token, a `sub` other than the URI, a
201 /// signature that does not verify, a key that is not the issuer's. The source is the
202 /// underlying error, when there is one.
203 #[error("status list {uri} is invalid: {reason}{}", cause(.source.as_ref()))]
204 InvalidList {
205 /// The status list URI the credential references.
206 uri: String,
207 /// What is wrong.
208 reason: String,
209 /// The underlying error.
210 source: Option<Box<dyn std::error::Error + Send + Sync>>,
211 },
212 /// The key that signed the status list could not be resolved; the source is the
213 /// resolver's error.
214 #[error("status list {uri}: cannot resolve key {key}: {source}")]
215 UnresolvedKey {
216 /// The status list URI the credential references.
217 uri: String,
218 /// The key reference, as the token's header names it.
219 key: String,
220 /// The resolver's error.
221 source: KeyResolutionError,
222 },
223 /// The status list has expired.
224 #[error(
225 "status list {uri} expired at {} (now is {})",
226 expired_at.to_rfc3339(),
227 now.to_rfc3339()
228 )]
229 Expired {
230 /// The status list URI the credential references.
231 uri: String,
232 /// Its `exp`.
233 expired_at: DateTime<Utc>,
234 /// The validation time.
235 now: DateTime<Utc>,
236 },
237 /// The credential's index is beyond the end of the status list.
238 #[error("index {idx} is out of range of status list {uri} of {len} entries")]
239 IndexOutOfRange {
240 /// The status list URI the credential references.
241 uri: String,
242 /// The credential's index.
243 idx: u64,
244 /// The number of entries in the list.
245 len: usize,
246 },
247 /// The credential's status makes it unusable: `revoked`, `suspended`, …
248 #[error("credential is {0}")]
249 Invalid(String),
250}
251
252/// Why a presentation did not validate: the presentation itself, or some of its credentials.
253#[derive(Debug, thiserror::Error)]
254#[non_exhaustive]
255pub struct PresentationValidationError {
256 /// What is wrong with the presentation JWT; when set, no credential was validated.
257 pub presentation: Option<Box<ValidationError>>,
258 /// What is wrong with each failing credential, by its position in
259 /// `verifiableCredential`.
260 pub credentials: BTreeMap<usize, ValidationError>,
261}
262
263impl PresentationValidationError {
264 /// An error of the presentation itself.
265 pub fn presentation(error: ValidationError) -> Self {
266 Self {
267 presentation: Some(Box::new(error)),
268 credentials: BTreeMap::new(),
269 }
270 }
271
272 /// An error of the credentials at the given positions.
273 pub fn credentials(errors: BTreeMap<usize, ValidationError>) -> Self {
274 Self {
275 presentation: None,
276 credentials: errors,
277 }
278 }
279}
280
281impl fmt::Display for PresentationValidationError {
282 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
283 if let Some(error) = &self.presentation {
284 return write!(f, "presentation: {error}");
285 }
286 for (i, (index, error)) in self.credentials.iter().enumerate() {
287 if i > 0 {
288 f.write_str("; ")?;
289 }
290 write!(f, "credential {index}: {error}")?;
291 }
292 Ok(())
293 }
294}