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 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 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 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 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
480pub 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#[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
543fn 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
596pub 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
624fn decode_enveloped(enveloped: &EnvelopedVc) -> Result<PresentedCredentialV2, ValidationError> {
626 #[cfg(feature = "sd-jwt")]
627 if enveloped.is_sd_jwt() {
628 let credential = SdJwtCredentialV2::from_sd_jwt(enveloped.to_sd_jwt()?)
629 .map_err(crate::sd_jwt_vc::SdJwtValidationError::from)?;
630 return Ok(PresentedCredentialV2::SdJwt(Box::new(credential)));
631 }
632 Ok(PresentedCredentialV2::Jwt(Box::new(decode_v2(
633 &enveloped.to_jwt()?.decode()?,
634 &NO_TYP,
635 )?)))
636}
637
638fn decode_payload_v2(
641 jws: &CompactJws,
642 additional_typ: &BTreeSet<String>,
643) -> Result<(JwtClaims, PresentationV2), ValidationError> {
644 check_typ(jws.header(), PresentationV2::JWT_TYP, additional_typ)?;
645 let claims = plain_claims(jws)?;
646 let presentation = PresentationV2::from_jwt_claims(&claims)?;
647 Ok((claims, presentation))
648}
649
650fn check_subject_holder<'a>(
652 properties: &IndexMap<String, Value>,
653 subjects: impl Iterator<Item = &'a Subject>,
654 holder: Option<&Uri>,
655 relationship: SubjectHolderRelationship,
656) -> Result<(), ValidationError> {
657 let required = match relationship {
658 SubjectHolderRelationship::AlwaysSubject => true,
659 SubjectHolderRelationship::SubjectOnNonTransferable => properties
660 .get("nonTransferable")
661 .is_some_and(|value| value == &Value::Bool(true)),
662 SubjectHolderRelationship::Any => false,
663 };
664 if !required {
665 return Ok(());
666 }
667 let holder = holder.expect("a validated presentation has a holder");
669 for subject in subjects {
670 if subject.id.as_ref() != Some(holder) {
671 return Err(ValidationError::SubjectHolderMismatch {
672 subject: subject.id.clone(),
673 holder: holder.clone(),
674 });
675 }
676 }
677 Ok(())
678}