Skip to main content

identity_kit/vc/validation/
presentation.rs

1//! `JwtPresentationValidator`.
2
3use std::collections::{BTreeMap, BTreeSet};
4
5use indexmap::IndexMap;
6use serde_json::Value;
7
8use crate::did::Uri;
9use crate::jose::{CompactJws, DefaultVerifier, JwsHeader, JwsVerifier};
10#[cfg(feature = "sd-jwt")]
11use crate::sd_jwt_vc::{SdJwtCredentialV2, SdJwtCredentialValidator, SdJwtValidationOptions};
12use crate::vc::{
13    CredentialError, CredentialV2, EnvelopedVc, Jwt, JwtClaims, Party, Presentation,
14    PresentationV2, Subject,
15};
16
17#[cfg(feature = "sd-jwt")]
18use super::CredentialStatus;
19use super::credential::{NO_TYP, check_controller, check_typ, decode, decode_v2, plain_claims};
20use super::{
21    DecodedCredential, DecodedCredentialV2, FailFast, JwtCredentialValidator, KeyResolver, KeyRole,
22    PresentationValidationError, PresentationValidationOptions, StatusCheck,
23    SubjectHolderRelationship, ValidationError,
24};
25
26/// A validated or decoded VCDM 1.1 presentation JWT: its header, its claims (custom ones
27/// included), the presentation, and its credentials decoded.
28#[derive(Debug, Clone)]
29#[non_exhaustive]
30pub struct DecodedPresentation {
31    /// The JWS header.
32    pub header: JwsHeader,
33    /// The claims set, `vp` included.
34    pub claims: JwtClaims,
35    /// The presentation, with `iss` and `jti` mapped back into it.
36    pub presentation: Presentation,
37    /// The presented credentials, in the order of `verifiableCredential`.
38    pub credentials: Vec<DecodedCredential>,
39}
40
41impl DecodedPresentation {
42    /// The holder: `holder` of the presentation, which decoding set from `iss`.
43    pub fn holder(&self) -> Option<&Uri> {
44        self.presentation.holder.as_ref().map(Party::id)
45    }
46}
47
48/// A validated or decoded VCDM 2.0 presentation JWT (`vp+jwt`): its header, its claims, the
49/// presentation, and its enveloped credentials unwrapped and decoded.
50#[derive(Debug, Clone)]
51#[non_exhaustive]
52pub struct DecodedPresentationV2 {
53    /// The JWS header.
54    pub header: JwsHeader,
55    /// The claims set, which is the presentation plus any registered claims.
56    pub claims: JwtClaims,
57    /// The presentation, with `iss` and `jti` mapped into `holder` and `id` when those are
58    /// absent.
59    pub presentation: PresentationV2,
60    /// The presented credentials, in the order of `verifiableCredential`, each in the form
61    /// its envelope held.
62    pub credentials: Vec<PresentedCredentialV2>,
63}
64
65impl DecodedPresentationV2 {
66    /// The holder: `holder` of the presentation, or `iss` when it has none.
67    pub fn holder(&self) -> Option<&Uri> {
68        self.presentation.holder.as_ref().map(Party::id)
69    }
70}
71
72/// A credential unwrapped from an `EnvelopedVerifiableCredential` of a VCDM 2.0
73/// presentation: secured as a JWT (`application/vc+jwt`) or, with the `sd-jwt` feature, with
74/// SD-JWT (`application/vc+sd-jwt`).
75#[derive(Debug, Clone)]
76#[non_exhaustive]
77pub enum PresentedCredentialV2 {
78    /// A `vc+jwt` credential, decoded.
79    Jwt(Box<DecodedCredentialV2>),
80    /// A `vc+sd-jwt` credential, with the disclosures it was presented with applied.
81    #[cfg(feature = "sd-jwt")]
82    #[cfg_attr(docsrs, doc(cfg(feature = "sd-jwt")))]
83    SdJwt(Box<SdJwtCredentialV2>),
84}
85
86impl PresentedCredentialV2 {
87    /// The credential, whichever way it was secured.
88    pub fn credential(&self) -> &CredentialV2 {
89        match self {
90            Self::Jwt(decoded) => &decoded.credential,
91            #[cfg(feature = "sd-jwt")]
92            Self::SdJwt(credential) => credential.credential(),
93        }
94    }
95
96    /// The header of the JWT securing it (the issuer-signed JWT, for SD-JWT).
97    pub fn header(&self) -> &JwsHeader {
98        match self {
99            Self::Jwt(decoded) => &decoded.header,
100            #[cfg(feature = "sd-jwt")]
101            Self::SdJwt(credential) => credential.header(),
102        }
103    }
104
105    /// The decoded JWT, when the credential was secured as one.
106    pub fn as_jwt(&self) -> Option<&DecodedCredentialV2> {
107        match self {
108            Self::Jwt(decoded) => Some(decoded),
109            #[cfg(feature = "sd-jwt")]
110            Self::SdJwt(_) => None,
111        }
112    }
113
114    /// The SD-JWT credential, when the credential was secured with SD-JWT.
115    #[cfg(feature = "sd-jwt")]
116    #[cfg_attr(docsrs, doc(cfg(feature = "sd-jwt")))]
117    pub fn as_sd_jwt(&self) -> Option<&SdJwtCredentialV2> {
118        match self {
119            Self::SdJwt(credential) => Some(credential),
120            Self::Jwt(_) => None,
121        }
122    }
123}
124
125/// Validates presentation JWTs and the credential JWTs they carry, see the [module
126/// documentation](super) for the checks.
127///
128/// Built over a [`JwtCredentialValidator`], which validates the credentials with the same key
129/// resolver, verifier and status check.
130///
131/// Each profile has its own method, as for credentials: [`validate`](Self::validate) for the
132/// VCDM 1.1 JWT profile (`typ` `JWT`, the `vp` claim, credentials as JWTs) and
133/// [`validate_v2`](Self::validate_v2) for VCDM 2.0 secured with VC-JOSE-COSE (`typ`
134/// `vp+jwt`, the payload is the presentation, credentials enveloped). Neither accepts the
135/// other's `typ`. A verifier that takes both picks by `typ`, and since `typ` is optional in
136/// both profiles, picks a token without one by its payload: VCDM 1.1 puts the presentation in
137/// a `vp` claim, VCDM 2.0 never has one.
138///
139/// ```
140/// # #[cfg(feature = "did-key")]
141/// # {
142/// use identity_kit::jose::DefaultVerifier;
143/// use identity_kit::methods::DidKey;
144/// use identity_kit::resolver::Resolver;
145/// use identity_kit::vc::validation::{JwtPresentationValidator, PresentationValidationOptions};
146/// use identity_kit::vc::{Jwt, JwtClaims, PresentationV2};
147///
148/// /// Whether `jwt` is a VCDM 2.0 presentation rather than a VCDM 1.1 one.
149/// fn is_v2(jwt: &Jwt) -> Result<bool, Box<dyn std::error::Error>> {
150///     let jws = jwt.decode()?;
151///     Ok(match jws.header().typ.as_deref() {
152///         Some(typ) => typ == PresentationV2::JWT_TYP,
153///         None => {
154///             let claims: JwtClaims = serde_json::from_slice(jws.payload())?;
155///             !claims.additional.contains_key("vp")
156///         }
157///     })
158/// }
159///
160/// async fn holder_of(
161///     validator: &JwtPresentationValidator<Resolver>,
162///     jwt: &Jwt,
163///     options: &PresentationValidationOptions,
164/// ) -> Result<Option<String>, Box<dyn std::error::Error>> {
165///     let holder = if is_v2(jwt)? {
166///         validator.validate_v2(jwt, options).await?.holder().cloned()
167///     } else {
168///         validator.validate(jwt, options).await?.holder().cloned()
169///     };
170///     Ok(holder.map(|holder| holder.to_string()))
171/// }
172///
173/// let resolver = Resolver::builder().with(DidKey::default()).build();
174/// let _validator = JwtPresentationValidator::new(resolver, DefaultVerifier);
175/// # }
176/// ```
177pub struct JwtPresentationValidator<R, V = DefaultVerifier> {
178    credentials: JwtCredentialValidator<R, V>,
179}
180
181impl<R: KeyResolver, V: JwsVerifier> JwtPresentationValidator<R, V> {
182    /// A validator resolving keys with `resolver` and verifying signatures with `verifier`,
183    /// without a status check.
184    pub fn new(resolver: R, verifier: V) -> Self {
185        Self {
186            credentials: JwtCredentialValidator::new(resolver, verifier),
187        }
188    }
189
190    /// A validator over `credentials`, sharing its resolver, verifier and status check.
191    pub fn from_credential_validator(credentials: JwtCredentialValidator<R, V>) -> Self {
192        Self { credentials }
193    }
194
195    /// This validator checking `credentialStatus` with `check`.
196    #[must_use]
197    pub fn with_status_check(mut self, check: impl StatusCheck + 'static) -> Self {
198        self.credentials = self.credentials.with_status_check(check);
199        self
200    }
201
202    /// The credential validator.
203    pub fn credential_validator(&self) -> &JwtCredentialValidator<R, V> {
204        &self.credentials
205    }
206
207    /// Validates a presentation JWT and every credential it carries.
208    ///
209    /// An entry of `verifiableCredential` that is not a compact JWT fails as that credential,
210    /// under its index, not as the presentation: the holder's signature covers it, so the
211    /// presentation itself can still verify.
212    ///
213    /// # Errors
214    ///
215    /// A [`PresentationValidationError`] naming what failed: the presentation (in which case
216    /// no credential was validated), or the credentials that failed, all of them under
217    /// [`FailFast::AllErrors`].
218    pub async fn validate(
219        &self,
220        jwt: &Jwt,
221        options: &PresentationValidationOptions,
222    ) -> Result<DecodedPresentation, PresentationValidationError> {
223        let (mut decoded, entries) = self
224            .validate_presentation(jwt, options)
225            .await
226            .map_err(PresentationValidationError::presentation)?;
227        let holder = decoded.holder().cloned();
228        let mut errors = BTreeMap::new();
229        for (index, entry) in entries.into_iter().enumerate() {
230            let result = match entry {
231                Ok(credential) => {
232                    self.credentials
233                        .validate(&credential, &options.credentials)
234                        .await
235                }
236                Err(error) => Err(error),
237            };
238            let result = result.and_then(|validated| {
239                let credential = &validated.credential;
240                check_subject_holder(
241                    &credential.properties,
242                    credential.credential_subject.iter(),
243                    holder.as_ref(),
244                    options.subject_holder,
245                )?;
246                Ok(validated)
247            });
248            match result {
249                Ok(validated) => decoded.credentials.push(validated),
250                Err(error) => {
251                    errors.insert(index, error);
252                    if options.fail_fast == FailFast::FirstError {
253                        break;
254                    }
255                }
256            }
257        }
258        if errors.is_empty() {
259            Ok(decoded)
260        } else {
261            Err(PresentationValidationError::credentials(errors))
262        }
263    }
264
265    /// Validates a VCDM 2.0 presentation JWT secured with VC-JOSE-COSE and every credential
266    /// it envelopes.
267    ///
268    /// The checks are those of [`validate`](Self::validate), with the profile's own shape:
269    /// `typ`, when present, is `vp+jwt` (or one of `options.additional_typ`); the payload is
270    /// the presentation, with `iss` and `jti` agreeing with `holder` and `id` and no `vp`
271    /// claim; the holder, from `holder` or else `iss`, is required and owns the signing key
272    /// ([`KeyReference::binds_to`](crate::resolver::KeyReference::binds_to)).
273    /// Each credential is unwrapped from its `EnvelopedVerifiableCredential` and validated
274    /// under `options.credentials`: an `application/vc+jwt` one with
275    /// [`JwtCredentialValidator::validate_v2`]; with the `sd-jwt` feature, an
276    /// `application/vc+sd-jwt` one as `SdJwtCredentialValidator::validate_v2` of `sd_jwt_vc`
277    /// does, with its `credentialStatus` entries and its `status` claim checked by this
278    /// validator's [`StatusCheck`] and the key binding of `options.key_binding` required when
279    /// set (none by default: the presentation JWT already proves holder control). An envelope
280    /// of another media type (a COSE credential) fails for that credential alone.
281    ///
282    /// # Errors
283    ///
284    /// As [`validate`](Self::validate).
285    pub async fn validate_v2(
286        &self,
287        jwt: &Jwt,
288        options: &PresentationValidationOptions,
289    ) -> Result<DecodedPresentationV2, PresentationValidationError> {
290        let mut decoded = self
291            .validate_presentation_v2(jwt, options)
292            .await
293            .map_err(PresentationValidationError::presentation)?;
294        let holder = decoded.holder().cloned();
295        let mut errors = BTreeMap::new();
296        for (index, enveloped) in decoded
297            .presentation
298            .verifiable_credential
299            .iter()
300            .enumerate()
301        {
302            match self
303                .validate_enveloped(enveloped, holder.as_ref(), options)
304                .await
305            {
306                Ok(validated) => decoded.credentials.push(validated),
307                Err(error) => {
308                    errors.insert(index, error);
309                    if options.fail_fast == FailFast::FirstError {
310                        break;
311                    }
312                }
313            }
314        }
315        if errors.is_empty() {
316            Ok(decoded)
317        } else {
318            Err(PresentationValidationError::credentials(errors))
319        }
320    }
321
322    /// Validates the credential `enveloped` holds, by its media type, and its subjects
323    /// against `holder`.
324    async fn validate_enveloped(
325        &self,
326        enveloped: &EnvelopedVc,
327        holder: Option<&Uri>,
328        options: &PresentationValidationOptions,
329    ) -> Result<PresentedCredentialV2, ValidationError> {
330        #[cfg(feature = "sd-jwt")]
331        if enveloped.is_sd_jwt() {
332            let sd_jwt = enveloped.to_sd_jwt()?;
333            let credential =
334                SdJwtCredentialV2::from_sd_jwt_with(sd_jwt, &options.credentials.additional_typ)
335                    .map_err(crate::sd_jwt_vc::SdJwtValidationError::from)?;
336            // No status policy here: the status is checked below, for both kinds of entry.
337            let sd_jwt_options = SdJwtValidationOptions {
338                time: options.credentials.time,
339                key_binding: options.key_binding.clone(),
340                ..SdJwtValidationOptions::default()
341            };
342            let validated = SdJwtCredentialValidator::new(
343                self.credentials.resolver(),
344                self.credentials.verifier(),
345            )
346            .validate_credential_v2_unchecked_status(credential, &sd_jwt_options)
347            .await?;
348            let credential = validated.credential;
349            self.credentials
350                .check_status(
351                    credential
352                        .credential()
353                        .statuses()
354                        .map(CredentialStatus::Vcdm)
355                        .chain(credential.status().map(CredentialStatus::StatusClaim))
356                        .collect(),
357                    options.credentials.status,
358                    options.credentials.time,
359                )
360                .await?;
361            check_subject_holder(
362                &credential.credential().properties,
363                credential.credential().credential_subject.iter(),
364                holder,
365                options.subject_holder,
366            )?;
367            return Ok(PresentedCredentialV2::SdJwt(Box::new(credential)));
368        }
369        let jwt = enveloped.to_jwt()?;
370        let validated = self
371            .credentials
372            .validate_v2(&jwt, &options.credentials)
373            .await?;
374        check_subject_holder(
375            &validated.credential.properties,
376            validated.credential.credential_subject.iter(),
377            holder,
378            options.subject_holder,
379        )?;
380        Ok(PresentedCredentialV2::Jwt(Box::new(validated)))
381    }
382
383    /// Validates the presentation JWT itself; the credentials are left to validate, one entry
384    /// of `verifiableCredential` each, as [`presentation_entries`] reads them.
385    async fn validate_presentation(
386        &self,
387        jwt: &Jwt,
388        options: &PresentationValidationOptions,
389    ) -> Result<(DecodedPresentation, Vec<Result<Jwt, ValidationError>>), ValidationError> {
390        let jws = jwt.decode()?;
391        check_typ(jws.header(), "JWT", &options.additional_typ)?;
392        let claims = plain_claims(&jws)?;
393        let (presentation, entries) = presentation_entries(&claims)?;
394        self.check_holder_and_claims(&jws, presentation.holder.as_ref(), "iss", &claims, options)
395            .await?;
396        let decoded = DecodedPresentation {
397            header: jws.header().clone(),
398            claims,
399            presentation,
400            credentials: Vec::new(),
401        };
402        Ok((decoded, entries))
403    }
404
405    /// Validates the VCDM 2.0 presentation JWT itself; the credentials are left to unwrap.
406    async fn validate_presentation_v2(
407        &self,
408        jwt: &Jwt,
409        options: &PresentationValidationOptions,
410    ) -> Result<DecodedPresentationV2, ValidationError> {
411        let jws = jwt.decode()?;
412        let (claims, presentation) = decode_payload_v2(&jws, &options.additional_typ)?;
413        self.check_holder_and_claims(
414            &jws,
415            presentation.holder.as_ref(),
416            "holder",
417            &claims,
418            options,
419        )
420        .await?;
421        Ok(DecodedPresentationV2 {
422            header: jws.header().clone(),
423            claims,
424            presentation,
425            credentials: Vec::new(),
426        })
427    }
428
429    /// The checks both profiles share once the payload is decoded: the signature under a key
430    /// resolved for [`KeyRole::Subject`], the key belongs to the holder (reported missing as
431    /// `missing`), the time claims, the audience and the nonce.
432    async fn check_holder_and_claims(
433        &self,
434        jws: &CompactJws,
435        holder: Option<&Party>,
436        missing: &'static str,
437        claims: &JwtClaims,
438        options: &PresentationValidationOptions,
439    ) -> Result<(), ValidationError> {
440        let (reference, key) = self
441            .credentials
442            .verify(
443                jws,
444                KeyRole::Subject,
445                holder.map(|holder| holder.id().as_str()),
446            )
447            .await?;
448        let holder = holder.ok_or(CredentialError::MissingClaim(missing))?;
449        check_controller(holder, &reference, &key, "holder")?;
450        options.time.check_claims(claims)?;
451        if let Some(expected) = &options.audience
452            && !claims.audiences().any(|aud| aud == expected)
453        {
454            return Err(ValidationError::AudienceMismatch {
455                expected: expected.clone(),
456                found: claims.aud.clone(),
457            });
458        }
459        if let Some(expected) = &options.nonce {
460            let found = claims.additional.get("nonce").and_then(Value::as_str);
461            if found != Some(expected.as_str()) {
462                return Err(ValidationError::NonceMismatch {
463                    expected: expected.clone(),
464                    found: found.map(str::to_owned),
465                });
466            }
467        }
468        Ok(())
469    }
470}
471
472impl<R: core::fmt::Debug, V: core::fmt::Debug> core::fmt::Debug for JwtPresentationValidator<R, V> {
473    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
474        f.debug_struct("JwtPresentationValidator")
475            .field("credentials", &self.credentials)
476            .finish()
477    }
478}
479
480/// Decodes a VCDM 1.1 presentation JWT and its credentials without verifying or validating
481/// anything.
482///
483/// # Errors
484///
485/// [`ValidationError::Jws`], [`ValidationError::Payload`], [`ValidationError::UnexpectedTyp`]
486/// or [`ValidationError::Credential`] when the token or one of its credentials does not decode,
487/// and [`ValidationError::SdJwtPayload`] when one of them is the issuer-signed JWT of an
488/// SD-JWT.
489pub fn decode_presentation(jwt: &Jwt) -> Result<DecodedPresentation, ValidationError> {
490    let jws = jwt.decode()?;
491    check_typ(jws.header(), "JWT", &NO_TYP)?;
492    let claims = plain_claims(&jws)?;
493    let presentation = Presentation::from_jwt_claims(&claims)?;
494    let credentials = presentation
495        .verifiable_credential
496        .iter()
497        .map(|credential| decode(&credential.decode()?, &NO_TYP))
498        .collect::<Result<_, _>>()?;
499    Ok(DecodedPresentation {
500        header: jws.header().clone(),
501        claims,
502        presentation,
503        credentials,
504    })
505}
506
507/// Decodes a VCDM 1.1 presentation JWT, accepting `presentation_typ`, and each entry of its
508/// `verifiableCredential` on its own, accepting `credential_typ`: one result per entry, in
509/// order. The returned presentation's `credentials` stay empty.
510///
511/// # Errors
512///
513/// As [`decode_presentation`], for the presentation alone.
514#[cfg(feature = "linked-vp")]
515pub(crate) fn decode_presentation_entries(
516    jwt: &Jwt,
517    presentation_typ: &BTreeSet<String>,
518    credential_typ: &BTreeSet<String>,
519) -> Result<
520    (
521        DecodedPresentation,
522        Vec<Result<DecodedCredential, ValidationError>>,
523    ),
524    ValidationError,
525> {
526    let jws = jwt.decode()?;
527    check_typ(jws.header(), "JWT", presentation_typ)?;
528    let claims = plain_claims(&jws)?;
529    let (presentation, entries) = presentation_entries(&claims)?;
530    let credentials = entries
531        .into_iter()
532        .map(|entry| decode(&entry?.decode()?, credential_typ))
533        .collect();
534    let decoded = DecodedPresentation {
535        header: jws.header().clone(),
536        claims,
537        presentation,
538        credentials: Vec::new(),
539    };
540    Ok((decoded, credentials))
541}
542
543/// The presentation of `claims` and the entries of its `verifiableCredential`, each a compact
544/// JWT or why it is not one. An entry that is not a JWT is left out of the presentation, so it
545/// fails alone rather than the presentation with it; a `verifiableCredential` that is not an
546/// array is the presentation's error, as before.
547///
548/// # Errors
549///
550/// As [`Presentation::from_jwt_claims`].
551fn presentation_entries(
552    claims: &JwtClaims,
553) -> Result<(Presentation, Vec<Result<Jwt, ValidationError>>), ValidationError> {
554    let Some(Value::Array(values)) = claims
555        .additional
556        .get("vp")
557        .and_then(|vp| vp.get("verifiableCredential"))
558    else {
559        let presentation = Presentation::from_jwt_claims(claims)?;
560        let entries = presentation
561            .verifiable_credential
562            .iter()
563            .cloned()
564            .map(Ok)
565            .collect();
566        return Ok((presentation, entries));
567    };
568    let entries: Vec<Result<Jwt, ValidationError>> = values
569        .iter()
570        .map(|value| match value {
571            Value::String(token) => Jwt::new(token.as_str()).map_err(ValidationError::from),
572            _ => Err(CredentialError::InvalidClaim {
573                claim: "vp",
574                reason: "a `verifiableCredential` entry is not a string".to_owned(),
575            }
576            .into()),
577        })
578        .collect();
579    let presentation = if entries.iter().all(Result::is_ok) {
580        Presentation::from_jwt_claims(claims)?
581    } else {
582        let mut claims = claims.clone();
583        if let Some(Value::Object(vp)) = claims.additional.get_mut("vp") {
584            let jwts = entries
585                .iter()
586                .filter_map(|entry| entry.as_ref().ok())
587                .map(|jwt| Value::String(jwt.as_str().to_owned()))
588                .collect();
589            vp.insert("verifiableCredential".to_owned(), Value::Array(jwts));
590        }
591        Presentation::from_jwt_claims(&claims)?
592    };
593    Ok((presentation, entries))
594}
595
596/// Decodes a VCDM 2.0 presentation JWT and unwraps and decodes its credentials without
597/// verifying or validating anything. A credential secured with SD-JWT (feature `sd-jwt`) has
598/// its disclosures processed, which checks the digests, but no signature is verified.
599///
600/// # Errors
601///
602/// [`ValidationError::Jws`], [`ValidationError::Payload`], [`ValidationError::UnexpectedTyp`]
603/// or [`ValidationError::Credential`] when the token, or one of its credentials, does not
604/// decode, and `ValidationError::SdJwt` when an SD-JWT credential does not; an envelope of
605/// a media type other than `application/vc+jwt` (or `application/vc+sd-jwt`) is a
606/// [`CredentialError::UnsupportedMediaType`]. A `vp+jwt` payload, or a `vc+jwt` one, that is
607/// the issuer-signed JWT of an SD-JWT is a [`ValidationError::SdJwtPayload`].
608pub fn decode_presentation_v2(jwt: &Jwt) -> Result<DecodedPresentationV2, ValidationError> {
609    let jws = jwt.decode()?;
610    let (claims, presentation) = decode_payload_v2(&jws, &NO_TYP)?;
611    let credentials = presentation
612        .verifiable_credential
613        .iter()
614        .map(decode_enveloped)
615        .collect::<Result<_, _>>()?;
616    Ok(DecodedPresentationV2 {
617        header: jws.header().clone(),
618        claims,
619        presentation,
620        credentials,
621    })
622}
623
624/// Decodes a VCDM 2.0 presentation JWT, accepting `presentation_typ`, and each credential it
625/// envelopes on its own: one result per entry, in order. The returned presentation's
626/// `credentials` stay empty.
627///
628/// # Errors
629///
630/// As [`decode_presentation_v2`], for the presentation alone.
631#[cfg(feature = "linked-vp")]
632pub(crate) fn decode_presentation_entries_v2(
633    jwt: &Jwt,
634    presentation_typ: &BTreeSet<String>,
635) -> Result<
636    (
637        DecodedPresentationV2,
638        Vec<Result<PresentedCredentialV2, ValidationError>>,
639    ),
640    ValidationError,
641> {
642    let jws = jwt.decode()?;
643    let (claims, presentation) = decode_payload_v2(&jws, presentation_typ)?;
644    let credentials = presentation
645        .verifiable_credential
646        .iter()
647        .map(decode_enveloped)
648        .collect();
649    let decoded = DecodedPresentationV2 {
650        header: jws.header().clone(),
651        claims,
652        presentation,
653        credentials: Vec::new(),
654    };
655    Ok((decoded, credentials))
656}
657
658/// Decodes the credential `enveloped` holds, by its media type.
659fn decode_enveloped(enveloped: &EnvelopedVc) -> Result<PresentedCredentialV2, ValidationError> {
660    #[cfg(feature = "sd-jwt")]
661    if enveloped.is_sd_jwt() {
662        let credential = SdJwtCredentialV2::from_sd_jwt(enveloped.to_sd_jwt()?)
663            .map_err(crate::sd_jwt_vc::SdJwtValidationError::from)?;
664        return Ok(PresentedCredentialV2::SdJwt(Box::new(credential)));
665    }
666    Ok(PresentedCredentialV2::Jwt(Box::new(decode_v2(
667        &enveloped.to_jwt()?.decode()?,
668        &NO_TYP,
669    )?)))
670}
671
672/// The claims and presentation of a VCDM 2.0 presentation JWT whose `typ`, when present, is
673/// `vp+jwt` or one of `additional_typ`.
674fn decode_payload_v2(
675    jws: &CompactJws,
676    additional_typ: &BTreeSet<String>,
677) -> Result<(JwtClaims, PresentationV2), ValidationError> {
678    check_typ(jws.header(), PresentationV2::JWT_TYP, additional_typ)?;
679    let claims = plain_claims(jws)?;
680    let presentation = PresentationV2::from_jwt_claims(&claims)?;
681    Ok((claims, presentation))
682}
683
684/// Checks `subjects` of a credential with `properties` against `holder` per `relationship`.
685fn check_subject_holder<'a>(
686    properties: &IndexMap<String, Value>,
687    subjects: impl Iterator<Item = &'a Subject>,
688    holder: Option<&Uri>,
689    relationship: SubjectHolderRelationship,
690) -> Result<(), ValidationError> {
691    let required = match relationship {
692        SubjectHolderRelationship::AlwaysSubject => true,
693        SubjectHolderRelationship::SubjectOnNonTransferable => properties
694            .get("nonTransferable")
695            .is_some_and(|value| value == &Value::Bool(true)),
696        SubjectHolderRelationship::Any => false,
697    };
698    if !required {
699        return Ok(());
700    }
701    // The presentation validator sets the holder before validating credentials.
702    let holder = holder.expect("a validated presentation has a holder");
703    for subject in subjects {
704        if subject.id.as_ref() != Some(holder) {
705            return Err(ValidationError::SubjectHolderMismatch {
706                subject: subject.id.clone(),
707                holder: holder.clone(),
708            });
709        }
710    }
711    Ok(())
712}