1use 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#[derive(Debug, Clone)]
29#[non_exhaustive]
30pub struct DecodedPresentation {
31 pub header: JwsHeader,
33 pub claims: JwtClaims,
35 pub presentation: Presentation,
37 pub credentials: Vec<DecodedCredential>,
39}
40
41impl DecodedPresentation {
42 pub fn holder(&self) -> Option<&Uri> {
44 self.presentation.holder.as_ref().map(Party::id)
45 }
46}
47
48#[derive(Debug, Clone)]
51#[non_exhaustive]
52pub struct DecodedPresentationV2 {
53 pub header: JwsHeader,
55 pub claims: JwtClaims,
57 pub presentation: PresentationV2,
60 pub credentials: Vec<PresentedCredentialV2>,
63}
64
65impl DecodedPresentationV2 {
66 pub fn holder(&self) -> Option<&Uri> {
68 self.presentation.holder.as_ref().map(Party::id)
69 }
70}
71
72#[derive(Debug, Clone)]
76#[non_exhaustive]
77pub enum PresentedCredentialV2 {
78 Jwt(Box<DecodedCredentialV2>),
80 #[cfg(feature = "sd-jwt")]
82 #[cfg_attr(docsrs, doc(cfg(feature = "sd-jwt")))]
83 SdJwt(Box<SdJwtCredentialV2>),
84}
85
86impl PresentedCredentialV2 {
87 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 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 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 #[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
125pub struct JwtPresentationValidator<R, V = DefaultVerifier> {
178 credentials: JwtCredentialValidator<R, V>,
179}
180
181impl<R: KeyResolver, V: JwsVerifier> JwtPresentationValidator<R, V> {
182 pub fn new(resolver: R, verifier: V) -> Self {
185 Self {
186 credentials: JwtCredentialValidator::new(resolver, verifier),
187 }
188 }
189
190 pub fn from_credential_validator(credentials: JwtCredentialValidator<R, V>) -> Self {
192 Self { credentials }
193 }
194
195 #[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 pub fn credential_validator(&self) -> &JwtCredentialValidator<R, V> {
204 &self.credentials
205 }
206
207 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 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 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 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 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 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 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 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
485pub 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#[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
548fn 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
601pub 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#[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
663fn 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
677fn 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
689fn 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 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}