Skip to main content

identity_kit/vc/validation/
mod.rs

1//! Validation of credential and presentation JWTs: signature, binding to the issuer or holder,
2//! validity period, audience, nonce and status.
3//!
4//! The validators take two extension points: a [`KeyResolver`] (from
5//! [`resolver`](crate::resolver), re-exported here), which turns the [`KeyReference`] of a JWT
6//! into the public key of its signer, and a [`JwsVerifier`](crate::jose::JwsVerifier), which
7//! checks the signature and is [`DefaultVerifier`](crate::jose::DefaultVerifier) unless an
8//! application substitutes its own. The crate's [`Resolver`](crate::resolver::Resolver)
9//! resolves DID URLs; a [`CompositeKeyResolver`](crate::resolver::CompositeKeyResolver) adds
10//! keys by value ([`JwkResolver`](crate::resolver::JwkResolver)) or the key sets of HTTPS
11//! issuers (`JwksResolver`, feature `jwks`). A [`StatusCheck`] is a third, optional extension
12//! point, for `credentialStatus` and the `status` claim, shared with the SD-JWT validators.
13//!
14//! # What is checked
15//!
16//! For a credential ([`JwtCredentialValidator`]):
17//!
18//! 1. The token is a compact JWS whose header names its key
19//!    ([`KeyReference::from_jws`], with the issuer as `iss`): a `kid` that is a DID URL of the
20//!    form `did:…#fragment`, a `#fragment` relative to a DID issuer, a `kid` into the key set of
21//!    an HTTPS issuer, or a `jwk`, `x5c` or `jku` header. A path or DID parameters such as
22//!    `versionId` in a DID URL are refused, so the signer cannot pick the document version its
23//!    key is looked up in (ADR 0004). When `typ` is present it names the profile: `JWT` for
24//!    VCDM 1.1, `vc+jwt` for VCDM 2.0, or one of the values the options add
25//!    (`CredentialValidationOptions::additional_typ`).
26//! 2. The payload is a claims set that maps to a [`Credential`](crate::vc::Credential) (or a
27//!    [`CredentialV2`](crate::vc::CredentialV2)), with its registered claims agreeing with the
28//!    credential. A payload with `_sd` or `_sd_alg` as a member name anywhere, or an array
29//!    element `{"...": "<digest>"}`, is the issuer-signed JWT of an SD-JWT and is refused
30//!    ([`ValidationError::SdJwtPayload`]), typed or not: read as a plain JWT, its digests would
31//!    be properties and its concealed claims would look absent. The `typ` check alone does not
32//!    catch it, since an untyped token is accepted; `SdJwtCredentialValidator` of `sd_jwt_vc`
33//!    validates it.
34//! 3. The key the reference names is resolved for [`KeyRole::Issuer`] (`assertionMethod` in a
35//!    DID document) and verifies the signature.
36//! 4. The key belongs to the issuer ([`KeyReference::binds_to`]): the issuer is the DID of the
37//!    DID URL, the `did:jwk` or thumbprint of a key by value, or the HTTPS issuer of the key
38//!    set.
39//! 5. `nbf`, `exp` and `iat`, and the credential's own validity period, hold at the validation
40//!    time, within the leeway.
41//! 6. `credentialStatus` passes the [`StatusCheck`], per the [`StatusPolicy`], and so does a
42//!    `status` claim, which the Token Status List defines for any JWT (§6.1), as
43//!    `CredentialStatus::StatusClaim` after the `credentialStatus` entries. With the
44//!    `status-list` feature (which `sd-jwt` implies) a `status` claim that does not parse, or
45//!    names no status mechanism, is refused; without it the claim cannot be checked, so it
46//!    fails under [`StatusPolicy::Strict`] and is ignored otherwise.
47//!
48//! For a presentation ([`JwtPresentationValidator`]): the same for the presentation JWT, with
49//! the key resolved for [`KeyRole::Subject`] (`authentication`) and bound to the holder, plus the expected
50//! audience and nonce; then every credential it carries is validated as above, and its subject
51//! is checked against the holder per the [`SubjectHolderRelationship`]. A VCDM 1.1
52//! presentation (`typ` `JWT`, [`validate`](JwtPresentationValidator::validate)) carries
53//! credential JWTs in its `vp` claim; a VCDM 2.0 one (`typ` `vp+jwt`,
54//! [`validate_v2`](JwtPresentationValidator::validate_v2)) is the payload itself and envelopes
55//! `vc+jwt` credentials and, with the `sd-jwt` feature, `vc+sd-jwt` ones (validated as
56//! `SdJwtCredentialValidator::validate_v2` of `sd_jwt_vc` does, with the key binding the
57//! presentation options require); an envelope of another media type fails for that
58//! credential alone.
59//!
60//! Everything a verifier decides by policy (which issuers to trust, which credential types to
61//! accept, what the claims must say) is left to the application, which gets the decoded
62//! credential back. [`decode_credential`], [`decode_credential_v2`], [`decode_presentation`]
63//! and [`decode_presentation_v2`] decode without verifying, for a look at a token before
64//! deciding how to validate it, and refuse an SD-JWT payload as the validators do; [`extract_issuer`] and [`extract_holder`] read just the signer's DID.
65
66use core::time::Duration;
67use std::collections::BTreeSet;
68use std::sync::Arc;
69
70use chrono::{DateTime, TimeDelta, Utc};
71
72use crate::did::Did;
73pub use crate::resolver::{
74    KeyReference, KeyReferenceError, KeyResolutionError, KeyResolver, KeyRole,
75};
76use crate::vc::{Jwt, JwtClaims, TypedObject, claims};
77
78mod credential;
79mod error;
80mod presentation;
81
82pub use credential::{
83    DecodedCredential, DecodedCredentialV2, JwtCredentialValidator, decode_credential,
84    decode_credential_v2,
85};
86pub use error::{PresentationValidationError, StatusError, ValidationError};
87#[cfg(feature = "linked-vp")]
88pub(crate) use presentation::decode_presentation_entries;
89pub use presentation::{
90    DecodedPresentation, DecodedPresentationV2, JwtPresentationValidator, PresentedCredentialV2,
91    decode_presentation, decode_presentation_v2,
92};
93
94/// A status entry of a credential, of either credential format, for a [`StatusCheck`].
95///
96/// # Examples
97///
98/// ```
99/// use identity_kit::vc::TypedObject;
100/// use identity_kit::vc::validation::CredentialStatus;
101///
102/// let entry: TypedObject = serde_json::from_value(serde_json::json!({
103///     "id": "https://example.com/credentials/status/3#94567",
104///     "type": "BitstringStatusListEntry",
105/// }))?;
106/// assert_eq!(CredentialStatus::Vcdm(&entry).mechanism(), "BitstringStatusListEntry");
107/// # Ok::<(), serde_json::Error>(())
108/// ```
109#[derive(Debug, Clone, Copy, PartialEq)]
110#[non_exhaustive]
111pub enum CredentialStatus<'a> {
112    /// A `credentialStatus` entry of a VCDM credential.
113    Vcdm(&'a TypedObject),
114    /// The `status` claim of a JWT credential of either profile, of an SD-JWT VC or of a VCDM
115    /// 2.0 credential secured with SD-JWT (IETF Token Status List §6.1 and other mechanisms).
116    #[cfg(feature = "status-list")]
117    #[cfg_attr(docsrs, doc(cfg(feature = "status-list")))]
118    StatusClaim(&'a crate::status_list::Status),
119}
120
121impl CredentialStatus<'_> {
122    /// What a check reports as [`StatusError::Unsupported`] for this entry: the `type` of a
123    /// `credentialStatus` entry, or the names of the mechanisms in a `status` claim
124    /// (`status_list`, and the members of other mechanisms), comma separated.
125    pub fn mechanism(&self) -> String {
126        match self {
127            Self::Vcdm(entry) => entry.object_type().to_owned(),
128            #[cfg(feature = "status-list")]
129            Self::StatusClaim(status) => status
130                .mechanisms()
131                .map(|mechanism| match mechanism {
132                    crate::status_list::StatusMechanism::StatusList(_) => "status_list",
133                    crate::status_list::StatusMechanism::Other { name, .. } => name,
134                })
135                .collect::<Vec<_>>()
136                .join(", "),
137        }
138    }
139}
140
141/// Checks the status of a credential: fetches the status list, bitmap or registry an entry
142/// points to and reports whether the credential is still good.
143///
144/// One check serves both credential formats: the validators hand it every `credentialStatus`
145/// entry of a VCDM credential as [`CredentialStatus::Vcdm`] and the `status` claim of a JWT
146/// or SD-JWT credential as `CredentialStatus::StatusClaim` (feature `status-list`), so an
147/// application implements status checking once. A check that does not understand an entry
148/// reports [`StatusError::Unsupported`], which the [`StatusPolicy`] decides about.
149/// `StatusListCheck` of `status_list` (features `status-list` and `did-web`) checks the Token
150/// Status List and reports every VCDM entry as unsupported.
151///
152/// # Examples
153///
154/// A check that knows only the Token Status List, and only the list it was given:
155///
156/// ```
157/// use identity_kit::vc::validation::{CredentialStatus, StatusCheck, StatusError, TimeOptions};
158///
159/// struct Revoked;
160///
161/// #[async_trait::async_trait]
162/// impl StatusCheck for Revoked {
163///     async fn check(&self, status: CredentialStatus<'_>, _: TimeOptions) -> Result<(), StatusError> {
164///         match status {
165///             #[cfg(feature = "status-list")]
166///             CredentialStatus::StatusClaim(status) if status.status_list.is_some() => {
167///                 Err(StatusError::Invalid("revoked".to_owned()))
168///             }
169///             other => Err(StatusError::Unsupported(other.mechanism())),
170///         }
171///     }
172/// }
173/// ```
174#[async_trait::async_trait]
175pub trait StatusCheck: Send + Sync {
176    /// Checks `status` at the validation time `time`, against which, with its leeway, a check
177    /// judges what it fetched (when a status list token was issued and expires, for
178    /// instance). The validators pin `time` to a fixed `now`.
179    ///
180    /// # Errors
181    ///
182    /// A [`StatusError`]: [`Unsupported`](StatusError::Unsupported) for an entry or mechanism
183    /// the check does not know, [`Unavailable`](StatusError::Unavailable) and the other
184    /// variants when the status could not be obtained or trusted,
185    /// [`Invalid`](StatusError::Invalid) when the credential is revoked
186    /// or suspended.
187    async fn check(
188        &self,
189        status: CredentialStatus<'_>,
190        time: TimeOptions,
191    ) -> Result<(), StatusError>;
192}
193
194// Implements `StatusCheck` for `&T`, `Box<T>` and `Arc<T>` by forwarding every method to `T`.
195// A method added to the trait is added here too: one with a default body would still compile
196// if left out, and calls through these wrappers would then run the default, not `T`'s
197// override. `clippy::missing_trait_methods` turns that omission into an error.
198macro_rules! forward_status_check {
199    ($($ty:ty),* $(,)?) => {
200        $(
201            #[async_trait::async_trait]
202            #[deny(clippy::missing_trait_methods)]
203            impl<T: StatusCheck + ?Sized> StatusCheck for $ty {
204                async fn check(
205                    &self,
206                    status: CredentialStatus<'_>,
207                    time: TimeOptions,
208                ) -> Result<(), StatusError> {
209                    (**self).check(status, time).await
210                }
211            }
212        )*
213    };
214}
215
216forward_status_check!(&T, Box<T>, Arc<T>);
217
218/// Checks every entry of `statuses` with `check` per `policy`, at `time`, pinned to one `now`
219/// for all of them.
220pub(crate) async fn check_statuses(
221    check: Option<&dyn StatusCheck>,
222    statuses: Vec<CredentialStatus<'_>>,
223    policy: StatusPolicy,
224    time: TimeOptions,
225) -> Result<(), ValidationError> {
226    if policy == StatusPolicy::SkipAll {
227        return Ok(());
228    }
229    let time = TimeOptions::at(time.now()).with_leeway(time.leeway);
230    for status in statuses {
231        let result = match check {
232            Some(check) => check.check(status, time).await,
233            None => Err(StatusError::Unsupported(status.mechanism())),
234        };
235        match result {
236            Ok(()) => {}
237            Err(StatusError::Unsupported(_)) if policy == StatusPolicy::SkipUnsupported => {}
238            Err(StatusError::Unsupported(mechanism)) => {
239                return Err(ValidationError::StatusUnchecked(mechanism));
240            }
241            Err(error) => return Err(ValidationError::Status(error)),
242        }
243    }
244    Ok(())
245}
246
247/// The `status` claim of a JWT credential, which the Token Status List defines for any JWT
248/// (§6.1): a `status_list::Status` with the `status-list` feature, uninhabited without it.
249#[cfg(feature = "status-list")]
250pub(super) type StatusClaim = crate::status_list::Status;
251
252/// The `status` claim of a JWT credential, which the Token Status List defines for any JWT
253/// (§6.1): a `status_list::Status` with the `status-list` feature, uninhabited without it.
254#[cfg(not(feature = "status-list"))]
255pub(super) enum StatusClaim {}
256
257/// The `status` claim of `claims`, for the [`StatusCheck`] beside the `credentialStatus`
258/// entries.
259///
260/// With the `status-list` feature the claim is parsed, and one that does not parse, or names no
261/// status mechanism, is an [`InvalidClaim`](crate::vc::CredentialError::InvalidClaim)
262/// whatever the `policy`. Without it the claim cannot be handed to a check, so it fails under
263/// [`StatusPolicy::Strict`] as an unchecked entry and is ignored otherwise.
264pub(super) fn status_claim(
265    claims: &JwtClaims,
266    policy: StatusPolicy,
267) -> Result<Option<StatusClaim>, ValidationError> {
268    let Some(status) = claims.additional.get("status") else {
269        return Ok(None);
270    };
271    #[cfg(feature = "status-list")]
272    {
273        let _ = policy;
274        let invalid = |reason: String| crate::vc::CredentialError::InvalidClaim {
275            claim: "status",
276            reason,
277        };
278        let status: StatusClaim =
279            serde_json::from_value(status.clone()).map_err(|e| invalid(e.to_string()))?;
280        // The claim references at least one status mechanism (Token Status List §6.1).
281        if status.is_empty() {
282            return Err(invalid("names no status mechanism".to_owned()).into());
283        }
284        Ok(Some(status))
285    }
286    #[cfg(not(feature = "status-list"))]
287    {
288        let _ = status;
289        match policy {
290            StatusPolicy::Strict => Err(ValidationError::StatusUnchecked("status".to_owned())),
291            _ => Ok(None),
292        }
293    }
294}
295
296/// `status` as the entry a [`StatusCheck`] is handed.
297pub(super) fn status_claim_entry(status: &StatusClaim) -> CredentialStatus<'_> {
298    #[cfg(feature = "status-list")]
299    {
300        CredentialStatus::StatusClaim(status)
301    }
302    #[cfg(not(feature = "status-list"))]
303    {
304        match *status {}
305    }
306}
307
308/// What to do about a status entry: a `credentialStatus` entry, or the `status` claim of an
309/// SD-JWT credential or of a JWT credential.
310#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
311#[non_exhaustive]
312pub enum StatusPolicy {
313    /// Every entry must pass the validator's [`StatusCheck`]; without one, or for a type it
314    /// does not support, validation fails.
315    #[default]
316    Strict,
317    /// Entries of a type the [`StatusCheck`] does not support, or any entry when there is no
318    /// check, are ignored.
319    SkipUnsupported,
320    /// Every status entry is ignored: `credentialStatus` and the `status` claim.
321    SkipAll,
322}
323
324/// Whether to stop at the first failing credential of a presentation.
325#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
326#[non_exhaustive]
327pub enum FailFast {
328    /// Stop at the first credential that fails.
329    #[default]
330    FirstError,
331    /// Validate every credential and report all failures.
332    AllErrors,
333}
334
335/// How the subject of a presented credential must relate to the holder presenting it.
336#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
337#[non_exhaustive]
338pub enum SubjectHolderRelationship {
339    /// Every subject of every credential must be the holder. A bearer credential fails.
340    #[default]
341    AlwaysSubject,
342    /// As [`AlwaysSubject`](Self::AlwaysSubject), but only for credentials whose
343    /// `nonTransferable` property is `true`.
344    SubjectOnNonTransferable,
345    /// Not checked.
346    Any,
347}
348
349/// The validation time and the clock skew allowed around it.
350///
351/// # Examples
352///
353/// ```
354/// use std::time::Duration;
355///
356/// use chrono::{TimeZone as _, Utc};
357/// use identity_kit::vc::validation::TimeOptions;
358///
359/// let fixed = TimeOptions::at(Utc.with_ymd_and_hms(2019, 11, 6, 0, 0, 0).unwrap())
360///     .with_leeway(Duration::from_secs(60));
361/// assert_eq!(fixed.now().to_rfc3339(), "2019-11-06T00:00:00+00:00");
362/// assert_eq!(fixed.leeway, Duration::from_secs(60));
363/// assert!(TimeOptions::default().now() > fixed.now());
364/// ```
365#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
366#[non_exhaustive]
367pub struct TimeOptions {
368    /// The validation time; the current time when `None`.
369    pub now: Option<DateTime<Utc>>,
370    /// How far `nbf`, `exp` and `iat` may miss the validation time and still pass; zero by
371    /// default.
372    pub leeway: Duration,
373}
374
375impl TimeOptions {
376    /// Options validating at `now`.
377    pub fn at(now: DateTime<Utc>) -> Self {
378        Self {
379            now: Some(now),
380            leeway: Duration::ZERO,
381        }
382    }
383
384    /// These options with `leeway`.
385    #[must_use]
386    pub fn with_leeway(mut self, leeway: Duration) -> Self {
387        self.leeway = leeway;
388        self
389    }
390
391    /// The validation time.
392    pub fn now(&self) -> DateTime<Utc> {
393        self.now.unwrap_or_else(Utc::now)
394    }
395
396    /// The leeway as a `chrono` delta, saturated.
397    fn delta(&self) -> TimeDelta {
398        TimeDelta::from_std(self.leeway).unwrap_or(TimeDelta::MAX)
399    }
400
401    /// The validation time, and the earliest and latest times the leeway lets pass for it.
402    pub(crate) fn window(&self) -> (DateTime<Utc>, DateTime<Utc>, DateTime<Utc>) {
403        let now = self.now();
404        let delta = self.delta();
405        // A leeway past the range `chrono` represents saturates rather than overflowing.
406        let earliest = now
407            .checked_sub_signed(delta)
408            .unwrap_or(DateTime::<Utc>::MIN_UTC);
409        let latest = now
410            .checked_add_signed(delta)
411            .unwrap_or(DateTime::<Utc>::MAX_UTC);
412        (now, earliest, latest)
413    }
414
415    /// Checks that `now` is within `[not_before, expires)` with the leeway, and that
416    /// `issued_at` is not in the future.
417    ///
418    /// # Errors
419    ///
420    /// [`ValidationError::NotYetValid`], [`ValidationError::Expired`] or
421    /// [`ValidationError::IssuedInFuture`].
422    pub fn check(
423        &self,
424        not_before: Option<DateTime<Utc>>,
425        expires: Option<DateTime<Utc>>,
426        issued_at: Option<DateTime<Utc>>,
427    ) -> Result<(), ValidationError> {
428        let (now, earliest, latest) = self.window();
429        if let Some(not_before) = not_before
430            && not_before > latest
431        {
432            return Err(ValidationError::NotYetValid { not_before, now });
433        }
434        if let Some(expired_at) = expires
435            && expired_at <= earliest
436        {
437            return Err(ValidationError::Expired { expired_at, now });
438        }
439        if let Some(issued_at) = issued_at
440            && issued_at > latest
441        {
442            return Err(ValidationError::IssuedInFuture { issued_at, now });
443        }
444        Ok(())
445    }
446
447    /// Checks the registered time claims of `claims`: `nbf`, `exp` and `iat`.
448    ///
449    /// # Errors
450    ///
451    /// As [`check`](Self::check), or [`ValidationError::Credential`] for a claim out of
452    /// range.
453    pub fn check_claims(&self, claims: &JwtClaims) -> Result<(), ValidationError> {
454        self.check(
455            timestamp(claims.nbf, "nbf")?,
456            timestamp(claims.exp, "exp")?,
457            timestamp(claims.iat, "iat")?,
458        )
459    }
460}
461
462/// The time a `NumericDate` claim names.
463fn timestamp(
464    value: Option<i64>,
465    claim: &'static str,
466) -> Result<Option<DateTime<Utc>>, ValidationError> {
467    value
468        .map(|value| {
469            JwtClaims::timestamp(value).ok_or_else(|| {
470                ValidationError::Credential(crate::vc::CredentialError::InvalidClaim {
471                    claim,
472                    reason: format!("{value} is out of range"),
473                })
474            })
475        })
476        .transpose()
477}
478
479/// Options of [`JwtCredentialValidator`].
480#[derive(Debug, Clone, Default, PartialEq, Eq)]
481#[non_exhaustive]
482pub struct CredentialValidationOptions {
483    /// The validation time and leeway.
484    pub time: TimeOptions,
485    /// What to do about `credentialStatus`.
486    pub status: StatusPolicy,
487    /// Header `typ` values accepted besides the profile's own (`JWT` for VCDM 1.1, `vc+jwt`
488    /// for VCDM 2.0); none by default. A token without `typ` is always accepted.
489    pub additional_typ: BTreeSet<String>,
490}
491
492impl CredentialValidationOptions {
493    /// Default options: validate now without leeway, [`StatusPolicy::Strict`].
494    pub fn new() -> Self {
495        Self::default()
496    }
497
498    /// These options with `time`.
499    #[must_use]
500    pub fn with_time(mut self, time: TimeOptions) -> Self {
501        self.time = time;
502        self
503    }
504
505    /// These options with `status`.
506    #[must_use]
507    pub fn with_status(mut self, status: StatusPolicy) -> Self {
508        self.status = status;
509        self
510    }
511
512    /// These options also accepting a credential whose header `typ` is `typ`.
513    #[must_use]
514    pub fn with_additional_typ(mut self, typ: impl Into<String>) -> Self {
515        self.additional_typ.insert(typ.into());
516        self
517    }
518}
519
520/// Options of [`JwtPresentationValidator`].
521#[derive(Debug, Clone, Default, PartialEq, Eq)]
522#[non_exhaustive]
523pub struct PresentationValidationOptions {
524    /// The validation time and leeway of the presentation JWT.
525    pub time: TimeOptions,
526    /// The audience the presentation must name in `aud`, if any is required.
527    pub audience: Option<String>,
528    /// The `nonce` the presentation must carry, if one is required.
529    pub nonce: Option<String>,
530    /// How credential subjects must relate to the holder.
531    pub subject_holder: SubjectHolderRelationship,
532    /// The options every presented credential is validated with.
533    pub credentials: CredentialValidationOptions,
534    /// Whether to stop at the first failing credential.
535    pub fail_fast: FailFast,
536    /// Header `typ` values accepted for the presentation JWT besides the profile's own (`JWT`
537    /// for VCDM 1.1, `vp+jwt` for VCDM 2.0), by both profiles; none by default. A token
538    /// without `typ` is always accepted. The credentials' own are
539    /// [`CredentialValidationOptions::additional_typ`].
540    pub additional_typ: BTreeSet<String>,
541    /// The key binding every enveloped credential secured with SD-JWT must prove, if any
542    /// is required; none by default, since the presentation JWT already proves holder
543    /// control. See [`JwtPresentationValidator::validate_v2`].
544    #[cfg(feature = "sd-jwt")]
545    #[cfg_attr(docsrs, doc(cfg(feature = "sd-jwt")))]
546    pub key_binding: Option<crate::sd_jwt_vc::KeyBindingOptions>,
547}
548
549impl PresentationValidationOptions {
550    /// Default options: validate now without leeway, no audience or nonce required,
551    /// [`SubjectHolderRelationship::AlwaysSubject`], default credential options,
552    /// [`FailFast::FirstError`].
553    pub fn new() -> Self {
554        Self::default()
555    }
556
557    /// These options with `time`, for the presentation JWT only.
558    #[must_use]
559    pub fn with_time(mut self, time: TimeOptions) -> Self {
560        self.time = time;
561        self
562    }
563
564    /// These options requiring `audience`.
565    #[must_use]
566    pub fn with_audience(mut self, audience: impl Into<String>) -> Self {
567        self.audience = Some(audience.into());
568        self
569    }
570
571    /// These options requiring `nonce`.
572    #[must_use]
573    pub fn with_nonce(mut self, nonce: impl Into<String>) -> Self {
574        self.nonce = Some(nonce.into());
575        self
576    }
577
578    /// These options with `relationship`.
579    #[must_use]
580    pub fn with_subject_holder(mut self, relationship: SubjectHolderRelationship) -> Self {
581        self.subject_holder = relationship;
582        self
583    }
584
585    /// These options validating credentials with `credentials`.
586    #[must_use]
587    pub fn with_credentials(mut self, credentials: CredentialValidationOptions) -> Self {
588        self.credentials = credentials;
589        self
590    }
591
592    /// These options with `fail_fast`.
593    #[must_use]
594    pub fn with_fail_fast(mut self, fail_fast: FailFast) -> Self {
595        self.fail_fast = fail_fast;
596        self
597    }
598
599    /// These options also accepting a presentation whose header `typ` is `typ`.
600    #[must_use]
601    pub fn with_additional_typ(mut self, typ: impl Into<String>) -> Self {
602        self.additional_typ.insert(typ.into());
603        self
604    }
605
606    /// These options requiring `key_binding` of every enveloped credential secured with
607    /// SD-JWT.
608    #[cfg(feature = "sd-jwt")]
609    #[cfg_attr(docsrs, doc(cfg(feature = "sd-jwt")))]
610    #[must_use]
611    pub fn with_key_binding(mut self, key_binding: crate::sd_jwt_vc::KeyBindingOptions) -> Self {
612        self.key_binding = Some(key_binding);
613        self
614    }
615}
616
617/// The DID of the issuer of a credential JWT, read without verifying anything: `iss`, else
618/// the `issuer` of the `vc` claim (VCDM 1.1) or of the payload (VCDM 2.0).
619///
620/// # Errors
621///
622/// [`ValidationError::Jws`] or [`ValidationError::Payload`] when the token does not decode,
623/// [`ValidationError::Credential`] when it names no issuer, and [`ValidationError::NotDid`]
624/// when the issuer is not a DID.
625pub fn extract_issuer(jwt: &Jwt) -> Result<Did, ValidationError> {
626    let claims = decode_claims(jwt)?;
627    let issuer = claims
628        .iss
629        .clone()
630        .or_else(|| property_id(&claims, "vc", "issuer"))
631        .ok_or(crate::vc::CredentialError::MissingClaim("iss"))?;
632    Did::parse(&issuer).map_err(|_| ValidationError::NotDid {
633        role: "issuer",
634        id: issuer,
635    })
636}
637
638/// The DID of the holder of a presentation JWT, read without verifying anything: `iss`, else
639/// the `holder` of the `vp` claim (VCDM 1.1) or of the payload (VCDM 2.0).
640///
641/// # Errors
642///
643/// As [`extract_issuer`], for the holder.
644pub fn extract_holder(jwt: &Jwt) -> Result<Did, ValidationError> {
645    let claims = decode_claims(jwt)?;
646    let holder = claims
647        .iss
648        .clone()
649        .or_else(|| property_id(&claims, "vp", "holder"))
650        .ok_or(crate::vc::CredentialError::MissingClaim("iss"))?;
651    Did::parse(&holder).map_err(|_| ValidationError::NotDid {
652        role: "holder",
653        id: holder,
654    })
655}
656
657/// The identifier of `property` in the `container` claim (VCDM 1.1), or in the payload.
658fn property_id(claims: &JwtClaims, container: &str, property: &str) -> Option<String> {
659    let value = match claims.additional.get(container) {
660        Some(container) => container.get(property)?,
661        None => claims.additional.get(property)?,
662    };
663    claims::id_of(value).map(str::to_owned)
664}
665
666/// The claims set of `jwt`, unverified.
667pub(super) fn decode_claims(jwt: &Jwt) -> Result<JwtClaims, ValidationError> {
668    let jws = jwt.decode()?;
669    serde_json::from_slice(jws.payload()).map_err(ValidationError::Payload)
670}