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