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            // One validation time for the key, the claims and the status.
338            let time = options.credentials.time.pinned();
339            let sd_jwt_options = SdJwtValidationOptions {
340                time,
341                key_binding: options.key_binding.clone(),
342                ..SdJwtValidationOptions::default()
343            };
344            let validated = SdJwtCredentialValidator::new(
345                self.credentials.resolver(),
346                self.credentials.verifier(),
347            )
348            .validate_credential_v2_unchecked_status(credential, &sd_jwt_options)
349            .await?;
350            let credential = validated.credential;
351            self.credentials
352                .check_status(
353                    credential
354                        .credential()
355                        .statuses()
356                        .map(CredentialStatus::Vcdm)
357                        .chain(credential.status().map(CredentialStatus::StatusClaim))
358                        .collect(),
359                    options.credentials.status,
360                    time,
361                )
362                .await?;
363            check_subject_holder(
364                &credential.credential().properties,
365                credential.credential().credential_subject.iter(),
366                holder,
367                options.subject_holder,
368            )?;
369            return Ok(PresentedCredentialV2::SdJwt(Box::new(credential)));
370        }
371        let jwt = enveloped.to_jwt()?;
372        let validated = self
373            .credentials
374            .validate_v2(&jwt, &options.credentials)
375            .await?;
376        check_subject_holder(
377            &validated.credential.properties,
378            validated.credential.credential_subject.iter(),
379            holder,
380            options.subject_holder,
381        )?;
382        Ok(PresentedCredentialV2::Jwt(Box::new(validated)))
383    }
384
385    /// Validates the presentation JWT itself; the credentials are left to validate, one entry
386    /// of `verifiableCredential` each, as [`presentation_entries`] reads them.
387    async fn validate_presentation(
388        &self,
389        jwt: &Jwt,
390        options: &PresentationValidationOptions,
391    ) -> Result<(DecodedPresentation, Vec<Result<Jwt, ValidationError>>), ValidationError> {
392        let jws = jwt.decode()?;
393        check_typ(jws.header(), "JWT", &options.additional_typ)?;
394        let claims = plain_claims(&jws)?;
395        let (presentation, entries) = presentation_entries(&claims)?;
396        self.check_holder_and_claims(&jws, presentation.holder.as_ref(), "iss", &claims, options)
397            .await?;
398        let decoded = DecodedPresentation {
399            header: jws.header().clone(),
400            claims,
401            presentation,
402            credentials: Vec::new(),
403        };
404        Ok((decoded, entries))
405    }
406
407    /// Validates the VCDM 2.0 presentation JWT itself; the credentials are left to unwrap.
408    async fn validate_presentation_v2(
409        &self,
410        jwt: &Jwt,
411        options: &PresentationValidationOptions,
412    ) -> Result<DecodedPresentationV2, ValidationError> {
413        let jws = jwt.decode()?;
414        let (claims, presentation) = decode_payload_v2(&jws, &options.additional_typ)?;
415        self.check_holder_and_claims(
416            &jws,
417            presentation.holder.as_ref(),
418            "holder",
419            &claims,
420            options,
421        )
422        .await?;
423        Ok(DecodedPresentationV2 {
424            header: jws.header().clone(),
425            claims,
426            presentation,
427            credentials: Vec::new(),
428        })
429    }
430
431    /// The checks both profiles share once the payload is decoded: the signature under a key
432    /// resolved for [`KeyRole::Subject`], the key belongs to the holder (reported missing as
433    /// `missing`), the time claims, the audience and the nonce.
434    async fn check_holder_and_claims(
435        &self,
436        jws: &CompactJws,
437        holder: Option<&Party>,
438        missing: &'static str,
439        claims: &JwtClaims,
440        options: &PresentationValidationOptions,
441    ) -> Result<(), ValidationError> {
442        // One validation time for the key and the claims.
443        let time = options.time.pinned();
444        let (reference, key) = self
445            .credentials
446            .verify(
447                jws,
448                KeyRole::Subject,
449                holder.map(|holder| holder.id().as_str()),
450                time,
451            )
452            .await?;
453        let holder = holder.ok_or(CredentialError::MissingClaim(missing))?;
454        check_controller(holder, &reference, &key, "holder")?;
455        time.check_claims(claims)?;
456        if let Some(expected) = &options.audience
457            && !claims.audiences().any(|aud| aud == expected)
458        {
459            return Err(ValidationError::AudienceMismatch {
460                expected: expected.clone(),
461                found: claims.aud.clone(),
462            });
463        }
464        if let Some(expected) = &options.nonce {
465            let found = claims.additional.get("nonce").and_then(Value::as_str);
466            if found != Some(expected.as_str()) {
467                return Err(ValidationError::NonceMismatch {
468                    expected: expected.clone(),
469                    found: found.map(str::to_owned),
470                });
471            }
472        }
473        Ok(())
474    }
475}
476
477impl<R: core::fmt::Debug, V: core::fmt::Debug> core::fmt::Debug for JwtPresentationValidator<R, V> {
478    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
479        f.debug_struct("JwtPresentationValidator")
480            .field("credentials", &self.credentials)
481            .finish()
482    }
483}
484
485/// Decodes a VCDM 1.1 presentation JWT and its credentials without verifying or validating
486/// anything.
487///
488/// # Errors
489///
490/// [`ValidationError::Jws`], [`ValidationError::Payload`], [`ValidationError::UnexpectedTyp`]
491/// or [`ValidationError::Credential`] when the token or one of its credentials does not decode,
492/// and [`ValidationError::SdJwtPayload`] when one of them is the issuer-signed JWT of an
493/// SD-JWT.
494pub fn decode_presentation(jwt: &Jwt) -> Result<DecodedPresentation, ValidationError> {
495    let jws = jwt.decode()?;
496    check_typ(jws.header(), "JWT", &NO_TYP)?;
497    let claims = plain_claims(&jws)?;
498    let presentation = Presentation::from_jwt_claims(&claims)?;
499    let credentials = presentation
500        .verifiable_credential
501        .iter()
502        .map(|credential| decode(&credential.decode()?, &NO_TYP))
503        .collect::<Result<_, _>>()?;
504    Ok(DecodedPresentation {
505        header: jws.header().clone(),
506        claims,
507        presentation,
508        credentials,
509    })
510}
511
512/// Decodes a VCDM 1.1 presentation JWT, accepting `presentation_typ`, and each entry of its
513/// `verifiableCredential` on its own, accepting `credential_typ`: one result per entry, in
514/// order. The returned presentation's `credentials` stay empty.
515///
516/// # Errors
517///
518/// As [`decode_presentation`], for the presentation alone.
519#[cfg(feature = "linked-vp")]
520pub(crate) fn decode_presentation_entries(
521    jwt: &Jwt,
522    presentation_typ: &BTreeSet<String>,
523    credential_typ: &BTreeSet<String>,
524) -> Result<
525    (
526        DecodedPresentation,
527        Vec<Result<DecodedCredential, ValidationError>>,
528    ),
529    ValidationError,
530> {
531    let jws = jwt.decode()?;
532    check_typ(jws.header(), "JWT", presentation_typ)?;
533    let claims = plain_claims(&jws)?;
534    let (presentation, entries) = presentation_entries(&claims)?;
535    let credentials = entries
536        .into_iter()
537        .map(|entry| decode(&entry?.decode()?, credential_typ))
538        .collect();
539    let decoded = DecodedPresentation {
540        header: jws.header().clone(),
541        claims,
542        presentation,
543        credentials: Vec::new(),
544    };
545    Ok((decoded, credentials))
546}
547
548/// The presentation of `claims` and the entries of its `verifiableCredential`, each a compact
549/// JWT or why it is not one. An entry that is not a JWT is left out of the presentation, so it
550/// fails alone rather than the presentation with it; a `verifiableCredential` that is not an
551/// array is the presentation's error, as before.
552///
553/// # Errors
554///
555/// As [`Presentation::from_jwt_claims`].
556fn presentation_entries(
557    claims: &JwtClaims,
558) -> Result<(Presentation, Vec<Result<Jwt, ValidationError>>), ValidationError> {
559    let Some(Value::Array(values)) = claims
560        .additional
561        .get("vp")
562        .and_then(|vp| vp.get("verifiableCredential"))
563    else {
564        let presentation = Presentation::from_jwt_claims(claims)?;
565        let entries = presentation
566            .verifiable_credential
567            .iter()
568            .cloned()
569            .map(Ok)
570            .collect();
571        return Ok((presentation, entries));
572    };
573    let entries: Vec<Result<Jwt, ValidationError>> = values
574        .iter()
575        .map(|value| match value {
576            Value::String(token) => Jwt::new(token.as_str()).map_err(ValidationError::from),
577            _ => Err(CredentialError::InvalidClaim {
578                claim: "vp",
579                reason: "a `verifiableCredential` entry is not a string".to_owned(),
580            }
581            .into()),
582        })
583        .collect();
584    let presentation = if entries.iter().all(Result::is_ok) {
585        Presentation::from_jwt_claims(claims)?
586    } else {
587        let mut claims = claims.clone();
588        if let Some(Value::Object(vp)) = claims.additional.get_mut("vp") {
589            let jwts = entries
590                .iter()
591                .filter_map(|entry| entry.as_ref().ok())
592                .map(|jwt| Value::String(jwt.as_str().to_owned()))
593                .collect();
594            vp.insert("verifiableCredential".to_owned(), Value::Array(jwts));
595        }
596        Presentation::from_jwt_claims(&claims)?
597    };
598    Ok((presentation, entries))
599}
600
601/// Decodes a VCDM 2.0 presentation JWT and unwraps and decodes its credentials without
602/// verifying or validating anything. A credential secured with SD-JWT (feature `sd-jwt`) has
603/// its disclosures processed, which checks the digests, but no signature is verified.
604///
605/// # Errors
606///
607/// [`ValidationError::Jws`], [`ValidationError::Payload`], [`ValidationError::UnexpectedTyp`]
608/// or [`ValidationError::Credential`] when the token, or one of its credentials, does not
609/// decode, and `ValidationError::SdJwt` when an SD-JWT credential does not; an envelope of
610/// a media type other than `application/vc+jwt` (or `application/vc+sd-jwt`) is a
611/// [`CredentialError::UnsupportedMediaType`]. A `vp+jwt` payload, or a `vc+jwt` one, that is
612/// the issuer-signed JWT of an SD-JWT is a [`ValidationError::SdJwtPayload`].
613pub fn decode_presentation_v2(jwt: &Jwt) -> Result<DecodedPresentationV2, ValidationError> {
614    let jws = jwt.decode()?;
615    let (claims, presentation) = decode_payload_v2(&jws, &NO_TYP)?;
616    let credentials = presentation
617        .verifiable_credential
618        .iter()
619        .map(decode_enveloped)
620        .collect::<Result<_, _>>()?;
621    Ok(DecodedPresentationV2 {
622        header: jws.header().clone(),
623        claims,
624        presentation,
625        credentials,
626    })
627}
628
629/// Decodes a VCDM 2.0 presentation JWT, accepting `presentation_typ`, and each credential it
630/// envelopes on its own: one result per entry, in order. The returned presentation's
631/// `credentials` stay empty.
632///
633/// # Errors
634///
635/// As [`decode_presentation_v2`], for the presentation alone.
636#[cfg(feature = "linked-vp")]
637pub(crate) fn decode_presentation_entries_v2(
638    jwt: &Jwt,
639    presentation_typ: &BTreeSet<String>,
640) -> Result<
641    (
642        DecodedPresentationV2,
643        Vec<Result<PresentedCredentialV2, ValidationError>>,
644    ),
645    ValidationError,
646> {
647    let jws = jwt.decode()?;
648    let (claims, presentation) = decode_payload_v2(&jws, presentation_typ)?;
649    let credentials = presentation
650        .verifiable_credential
651        .iter()
652        .map(decode_enveloped)
653        .collect();
654    let decoded = DecodedPresentationV2 {
655        header: jws.header().clone(),
656        claims,
657        presentation,
658        credentials: Vec::new(),
659    };
660    Ok((decoded, credentials))
661}
662
663/// Decodes the credential `enveloped` holds, by its media type.
664fn decode_enveloped(enveloped: &EnvelopedVc) -> Result<PresentedCredentialV2, ValidationError> {
665    #[cfg(feature = "sd-jwt")]
666    if enveloped.is_sd_jwt() {
667        let credential = SdJwtCredentialV2::from_sd_jwt(enveloped.to_sd_jwt()?)
668            .map_err(crate::sd_jwt_vc::SdJwtValidationError::from)?;
669        return Ok(PresentedCredentialV2::SdJwt(Box::new(credential)));
670    }
671    Ok(PresentedCredentialV2::Jwt(Box::new(decode_v2(
672        &enveloped.to_jwt()?.decode()?,
673        &NO_TYP,
674    )?)))
675}
676
677/// The claims and presentation of a VCDM 2.0 presentation JWT whose `typ`, when present, is
678/// `vp+jwt` or one of `additional_typ`.
679fn decode_payload_v2(
680    jws: &CompactJws,
681    additional_typ: &BTreeSet<String>,
682) -> Result<(JwtClaims, PresentationV2), ValidationError> {
683    check_typ(jws.header(), PresentationV2::JWT_TYP, additional_typ)?;
684    let claims = plain_claims(jws)?;
685    let presentation = PresentationV2::from_jwt_claims(&claims)?;
686    Ok((claims, presentation))
687}
688
689/// Checks `subjects` of a credential with `properties` against `holder` per `relationship`.
690fn check_subject_holder<'a>(
691    properties: &IndexMap<String, Value>,
692    subjects: impl Iterator<Item = &'a Subject>,
693    holder: Option<&Uri>,
694    relationship: SubjectHolderRelationship,
695) -> Result<(), ValidationError> {
696    let required = match relationship {
697        SubjectHolderRelationship::AlwaysSubject => true,
698        SubjectHolderRelationship::SubjectOnNonTransferable => properties
699            .get("nonTransferable")
700            .is_some_and(|value| value == &Value::Bool(true)),
701        SubjectHolderRelationship::Any => false,
702    };
703    if !required {
704        return Ok(());
705    }
706    // The presentation validator sets the holder before validating credentials.
707    let holder = holder.expect("a validated presentation has a holder");
708    for subject in subjects {
709        if subject.id.as_ref() != Some(holder) {
710            return Err(ValidationError::SubjectHolderMismatch {
711                subject: subject.id.clone(),
712                holder: holder.clone(),
713            });
714        }
715    }
716    Ok(())
717}