Skip to main content

identity_kit/vc/validation/
credential.rs

1//! `JwtCredentialValidator`.
2
3use std::collections::BTreeSet;
4
5use crate::did::Uri;
6use crate::jose::{CompactJws, DefaultVerifier, Jwk, JwsHeader, JwsVerifier};
7use crate::vc::{Credential, CredentialV2, Jwt, JwtClaims, Party};
8
9use serde_json::Value;
10
11use super::{
12    CredentialStatus, CredentialValidationOptions, KeyReference, KeyResolver, KeyRole, StatusCheck,
13    StatusPolicy, TimeOptions, ValidationError, check_statuses, status_claim, status_claim_entry,
14};
15
16/// A validated or decoded VCDM 1.1 credential JWT: its header, its claims (custom ones
17/// included) and the credential they map to.
18#[derive(Debug, Clone)]
19#[non_exhaustive]
20pub struct DecodedCredential {
21    /// The JWS header.
22    pub header: JwsHeader,
23    /// The claims set, `vc` included.
24    pub claims: JwtClaims,
25    /// The credential, with the registered claims mapped back into it.
26    pub credential: Credential,
27}
28
29/// A validated or decoded VCDM 2.0 credential JWT: its header, its claims and the credential.
30#[derive(Debug, Clone)]
31#[non_exhaustive]
32pub struct DecodedCredentialV2 {
33    /// The JWS header.
34    pub header: JwsHeader,
35    /// The claims set, which is the credential plus any registered claims.
36    pub claims: JwtClaims,
37    /// The credential.
38    pub credential: CredentialV2,
39}
40
41/// Validates credential JWTs, see the [module documentation](super) for the checks.
42///
43/// # Examples
44///
45/// A `did:key` issuer signs a credential about a subject, and the verifier validates it with a
46/// resolver that knows `did:key`.
47///
48/// ```
49/// # #[cfg(feature = "did-key")]
50/// # {
51/// use chrono::{TimeZone as _, Utc};
52/// use identity_kit::did::Uri;
53/// use identity_kit::jose::{DefaultVerifier, Jwk, JwsAlgorithm, JwsHeader, SignError, Signer};
54/// use identity_kit::methods::DidKey;
55/// use identity_kit::resolver::Resolver;
56/// use identity_kit::vc::validation::{CredentialValidationOptions, JwtCredentialValidator, TimeOptions};
57/// use identity_kit::vc::{Credential, Jwt, Subject};
58///
59/// // The Ed25519 key of RFC 8037 Appendix A.1 behind a `Signer`.
60/// struct Issuer(ed25519_dalek::SigningKey);
61///
62/// #[async_trait::async_trait]
63/// impl Signer for Issuer {
64///     fn alg(&self) -> JwsAlgorithm { JwsAlgorithm::EdDSA }
65///     fn kid(&self) -> Option<&str> { None }
66///     async fn sign(&self, input: &[u8]) -> Result<Vec<u8>, SignError> {
67///         use ed25519_dalek::Signer as _;
68///         Ok(self.0.sign(input).to_bytes().to_vec())
69///     }
70/// }
71///
72/// # tokio::runtime::Builder::new_current_thread().build()?.block_on(async {
73/// let secret: [u8; 32] = identity_kit::jose::Jwk::from_ed25519_public(&[0; 32]).map(|_| [
74///     0x9d, 0x61, 0xb1, 0x9d, 0xef, 0xfd, 0x5a, 0x60, 0xba, 0x84, 0x4a, 0xf4, 0x92, 0xec, 0x2c, 0xc4,
75///     0x44, 0x49, 0xc5, 0x69, 0x7b, 0x32, 0x69, 0x19, 0x70, 0x3b, 0xac, 0x03, 0x1c, 0xae, 0x7f, 0x60,
76/// ])?;
77/// let signing_key = ed25519_dalek::SigningKey::from_bytes(&secret);
78/// let jwk = Jwk::from_ed25519_public(signing_key.verifying_key().as_bytes())?;
79/// let issuer = DidKey::did(&jwk)?;
80/// let kid = issuer.join(&format!("#{}", issuer.method_specific_id()))?;
81///
82/// let credential = Credential::new(
83///     &issuer,
84///     Utc.with_ymd_and_hms(2010, 1, 1, 0, 0, 0).unwrap(),
85///     Subject::new(Uri::parse("did:example:ebfeb1f712ebc6f1c276e12ec21")?),
86/// );
87/// let header = JwsHeader::new(JwsAlgorithm::EdDSA).with_typ("JWT").with_kid(kid.as_str());
88/// let jwt = Jwt::sign(&header, &credential.to_jwt_claims()?, &Issuer(signing_key)).await?;
89///
90/// let resolver = Resolver::builder().with(DidKey::default()).build();
91/// let validator = JwtCredentialValidator::new(resolver, DefaultVerifier);
92/// let options = CredentialValidationOptions::new()
93///     .with_time(TimeOptions::at(Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap()));
94/// let decoded = validator.validate(&jwt, &options).await?;
95/// assert_eq!(decoded.credential, credential);
96/// # Ok::<(), Box<dyn std::error::Error>>(())
97/// # })?;
98/// # }
99/// # Ok::<(), Box<dyn std::error::Error>>(())
100/// ```
101pub struct JwtCredentialValidator<R, V = DefaultVerifier> {
102    resolver: R,
103    verifier: V,
104    status: Option<Box<dyn StatusCheck>>,
105}
106
107impl<R: KeyResolver, V: JwsVerifier> JwtCredentialValidator<R, V> {
108    /// A validator resolving keys with `resolver` and verifying signatures with `verifier`,
109    /// without a status check.
110    pub fn new(resolver: R, verifier: V) -> Self {
111        Self {
112            resolver,
113            verifier,
114            status: None,
115        }
116    }
117
118    /// This validator checking `credentialStatus` and the `status` claim with `check`.
119    #[must_use]
120    pub fn with_status_check(mut self, check: impl StatusCheck + 'static) -> Self {
121        self.status = Some(Box::new(check));
122        self
123    }
124
125    /// The key resolver.
126    pub fn resolver(&self) -> &R {
127        &self.resolver
128    }
129
130    /// The signature verifier.
131    pub fn verifier(&self) -> &V {
132        &self.verifier
133    }
134
135    /// Whether a status check is configured.
136    pub fn has_status_check(&self) -> bool {
137        self.status.is_some()
138    }
139
140    /// Validates a VCDM 1.1 credential JWT.
141    ///
142    /// # Errors
143    ///
144    /// The first [`ValidationError`] found, in the order the [module documentation](super)
145    /// lists the checks.
146    pub async fn validate(
147        &self,
148        jwt: &Jwt,
149        options: &CredentialValidationOptions,
150    ) -> Result<DecodedCredential, ValidationError> {
151        let jws = jwt.decode()?;
152        let decoded = decode(&jws, &options.additional_typ)?;
153        let issuer = &decoded.credential.issuer;
154        let (reference, key) = self
155            .verify(&jws, KeyRole::Issuer, Some(issuer.id().as_str()))
156            .await?;
157        check_controller(issuer, &reference, &key, "issuer")?;
158        options.time.check_claims(&decoded.claims)?;
159        options.time.check(
160            Some(decoded.credential.issuance_date),
161            decoded.credential.expiration_date,
162            None,
163        )?;
164        let status = status_claim(&decoded.claims, options.status)?;
165        self.check_status(
166            decoded
167                .credential
168                .credential_status
169                .iter()
170                .map(CredentialStatus::Vcdm)
171                .chain(status.iter().map(status_claim_entry))
172                .collect(),
173            options.status,
174            options.time,
175        )
176        .await?;
177        Ok(decoded)
178    }
179
180    /// Validates a VCDM 2.0 credential JWT, whose `typ` is `vc+jwt` when present.
181    ///
182    /// # Errors
183    ///
184    /// As [`validate`](Self::validate).
185    pub async fn validate_v2(
186        &self,
187        jwt: &Jwt,
188        options: &CredentialValidationOptions,
189    ) -> Result<DecodedCredentialV2, ValidationError> {
190        let jws = jwt.decode()?;
191        let decoded = decode_v2(&jws, &options.additional_typ)?;
192        let issuer = &decoded.credential.issuer;
193        let (reference, key) = self
194            .verify(&jws, KeyRole::Issuer, Some(issuer.id().as_str()))
195            .await?;
196        check_controller(issuer, &reference, &key, "issuer")?;
197        options.time.check_claims(&decoded.claims)?;
198        options.time.check(
199            decoded.credential.valid_from,
200            decoded.credential.valid_until,
201            None,
202        )?;
203        let status = status_claim(&decoded.claims, options.status)?;
204        self.check_status(
205            decoded
206                .credential
207                .statuses()
208                .map(CredentialStatus::Vcdm)
209                .chain(status.iter().map(status_claim_entry))
210                .collect(),
211            options.status,
212            options.time,
213        )
214        .await?;
215        Ok(decoded)
216    }
217
218    /// Resolves the key `jws` names, `iss` being its issuer, for `role` and verifies the
219    /// signature; the reference and the key.
220    pub(super) async fn verify(
221        &self,
222        jws: &CompactJws,
223        role: KeyRole,
224        iss: Option<&str>,
225    ) -> Result<(KeyReference, Jwk), ValidationError> {
226        let reference = KeyReference::from_jws(jws, iss)?;
227        let key = self
228            .resolver
229            .resolve_key(&reference, role)
230            .await
231            .map_err(|source| ValidationError::KeyResolution {
232                key: Box::new(reference.clone()),
233                source,
234            })?;
235        jws.verify(&self.verifier, &key)?;
236        Ok((reference, key))
237    }
238
239    /// Checks every status entry with this validator's check, per `policy`, at `time`.
240    pub(super) async fn check_status(
241        &self,
242        statuses: Vec<CredentialStatus<'_>>,
243        policy: StatusPolicy,
244        time: TimeOptions,
245    ) -> Result<(), ValidationError> {
246        check_statuses(self.status.as_deref(), statuses, policy, time).await
247    }
248}
249
250impl<R: core::fmt::Debug, V: core::fmt::Debug> core::fmt::Debug for JwtCredentialValidator<R, V> {
251    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
252        f.debug_struct("JwtCredentialValidator")
253            .field("resolver", &self.resolver)
254            .field("verifier", &self.verifier)
255            .field("status", &self.status.as_ref().map(|_| "StatusCheck"))
256            .finish()
257    }
258}
259
260/// Decodes a VCDM 1.1 credential JWT without verifying or validating anything.
261///
262/// # Errors
263///
264/// [`ValidationError::Jws`], [`ValidationError::Payload`], [`ValidationError::UnexpectedTyp`]
265/// or [`ValidationError::Credential`] when the token does not decode to a credential, and
266/// [`ValidationError::SdJwtPayload`] when it is the issuer-signed JWT of an SD-JWT.
267pub fn decode_credential(jwt: &Jwt) -> Result<DecodedCredential, ValidationError> {
268    decode(&jwt.decode()?, &NO_TYP)
269}
270
271/// Decodes a VCDM 2.0 credential JWT without verifying or validating anything.
272///
273/// # Errors
274///
275/// As [`decode_credential`].
276pub fn decode_credential_v2(jwt: &Jwt) -> Result<DecodedCredentialV2, ValidationError> {
277    decode_v2(&jwt.decode()?, &NO_TYP)
278}
279
280/// No `typ` besides the profile's own.
281pub(super) static NO_TYP: BTreeSet<String> = BTreeSet::new();
282
283/// Decodes a VCDM 1.1 credential JWT whose `typ`, when present, is `JWT` or one of
284/// `additional_typ`.
285pub(super) fn decode(
286    jws: &CompactJws,
287    additional_typ: &BTreeSet<String>,
288) -> Result<DecodedCredential, ValidationError> {
289    check_typ(jws.header(), "JWT", additional_typ)?;
290    let claims = plain_claims(jws)?;
291    let credential = Credential::from_jwt_claims(&claims)?;
292    Ok(DecodedCredential {
293        header: jws.header().clone(),
294        claims,
295        credential,
296    })
297}
298
299/// Decodes a VCDM 2.0 credential JWT: `typ` is `vc+jwt` when present (VC-JOSE-COSE §3.1.1),
300/// or one of `additional_typ`, so a token typed for another purpose is never read as a
301/// credential.
302pub(super) fn decode_v2(
303    jws: &CompactJws,
304    additional_typ: &BTreeSet<String>,
305) -> Result<DecodedCredentialV2, ValidationError> {
306    check_typ(jws.header(), CredentialV2::JWT_TYP, additional_typ)?;
307    let claims = plain_claims(jws)?;
308    let credential = CredentialV2::from_jwt_claims(&claims)?;
309    Ok(DecodedCredentialV2 {
310        header: jws.header().clone(),
311        claims,
312        credential,
313    })
314}
315
316/// The claims set of `jws`, refused when it is the issuer-signed JWT of an SD-JWT: see
317/// [`ValidationError::SdJwtPayload`].
318pub(super) fn plain_claims(jws: &CompactJws) -> Result<JwtClaims, ValidationError> {
319    let claims: JwtClaims =
320        serde_json::from_slice(jws.payload()).map_err(ValidationError::Payload)?;
321    match claims
322        .additional
323        .iter()
324        .find_map(|(name, value)| sd_jwt_member(name, value))
325    {
326        Some(claim) => Err(ValidationError::SdJwtPayload { claim }),
327        None => Ok(claims),
328    }
329}
330
331/// The names RFC 9901 §4.2 reserves in the payload of an SD-JWT: `_sd` and `_sd_alg` as
332/// member names, and `...` as the one member of an array element standing for a digest.
333const SD_JWT_NAMES: [&str; 2] = ["_sd", "_sd_alg"];
334const ELLIPSIS: &str = "...";
335
336/// The SD-JWT name the member `name` with `value` is, or holds anywhere below it. `serde_json`
337/// limits the nesting of a parsed payload, so the recursion is bounded.
338fn sd_jwt_member(name: &str, value: &Value) -> Option<&'static str> {
339    SD_JWT_NAMES
340        .into_iter()
341        .find(|reserved| *reserved == name)
342        .or_else(|| sd_jwt_name_in(value))
343}
344
345/// As [`sd_jwt_member`], for the members and elements of `value`.
346fn sd_jwt_name_in(value: &Value) -> Option<&'static str> {
347    match value {
348        Value::Object(object) => object
349            .iter()
350            .find_map(|(name, value)| sd_jwt_member(name, value)),
351        Value::Array(array) => array.iter().find_map(|element| match element {
352            Value::Object(object)
353                if object.len() == 1 && object.get(ELLIPSIS).is_some_and(Value::is_string) =>
354            {
355                Some(ELLIPSIS)
356            }
357            element => sd_jwt_name_in(element),
358        }),
359        _ => None,
360    }
361}
362
363/// Rejects a header `typ` other than `expected` and `additional`, when one is present.
364pub(super) fn check_typ(
365    header: &JwsHeader,
366    expected: &'static str,
367    additional: &BTreeSet<String>,
368) -> Result<(), ValidationError> {
369    match header.typ.as_deref() {
370        Some(found) if found != expected && !additional.contains(found) => {
371            Err(ValidationError::UnexpectedTyp {
372                expected,
373                found: found.to_owned(),
374            })
375        }
376        _ => Ok(()),
377    }
378}
379
380/// Checks that `key`, which `reference` resolved to, belongs to `party`
381/// ([`KeyReference::binds_to`]).
382pub(super) fn check_controller(
383    party: &Party,
384    reference: &KeyReference,
385    key: &Jwk,
386    role: &'static str,
387) -> Result<(), ValidationError> {
388    let id = party.id();
389    if !reference.binds_to(Some(id.as_str()), key) {
390        return Err(mismatch(role, id.clone(), reference.clone()));
391    }
392    Ok(())
393}
394
395/// The mismatch error for `role`.
396fn mismatch(role: &'static str, id: Uri, key: KeyReference) -> ValidationError {
397    if role == "holder" {
398        ValidationError::HolderMismatch {
399            holder: id,
400            key: Box::new(key),
401        }
402    } else {
403        ValidationError::IssuerMismatch {
404            issuer: id,
405            key: Box::new(key),
406        }
407    }
408}