1use core::time::Duration;
44use std::collections::BTreeSet;
45
46use chrono::{DateTime, Utc};
47
48use super::{
49 Confirmation, SdJwt, SdJwtCredentialV2, SdJwtCredentialV2Error, SdJwtVc, SdJwtVcError,
50};
51use crate::did::Uri;
52use crate::jose::{DefaultVerifier, Jwk, JwsVerifier};
53use crate::resolver::{KeyReference, KeyReferenceError, KeyResolver, KeyRole, resolve_jws_key};
54use crate::vc::validation::{
55 CredentialStatus, StatusCheck, StatusPolicy, TimeOptions, ValidationError, check_statuses,
56};
57use crate::vc::{CredentialError, JwtClaims};
58
59#[cfg(feature = "did-web")]
61#[cfg_attr(docsrs, doc(cfg(feature = "did-web")))]
62#[deprecated(since = "0.3.0", note = "moved to `status_list::StatusListCheck`")]
63pub type StatusListCheck<C, R, V = DefaultVerifier> = crate::status_list::StatusListCheck<C, R, V>;
64
65#[derive(Debug, Clone, PartialEq, Eq)]
71#[non_exhaustive]
72pub struct KeyBindingOptions {
73 pub audience: String,
75 pub nonce: String,
77 pub time: TimeOptions,
79 pub max_age: Option<Duration>,
81}
82
83impl KeyBindingOptions {
84 pub fn new(audience: impl Into<String>, nonce: impl Into<String>) -> Self {
87 Self {
88 audience: audience.into(),
89 nonce: nonce.into(),
90 time: TimeOptions::default(),
91 max_age: None,
92 }
93 }
94
95 #[must_use]
97 pub fn with_time(mut self, time: TimeOptions) -> Self {
98 self.time = time;
99 self
100 }
101
102 #[must_use]
104 pub fn with_max_age(mut self, max_age: Duration) -> Self {
105 self.max_age = Some(max_age);
106 self
107 }
108}
109
110#[derive(Debug, Clone, Default, PartialEq, Eq)]
112#[non_exhaustive]
113pub struct SdJwtValidationOptions {
114 pub time: TimeOptions,
116 pub key_binding: Option<KeyBindingOptions>,
118 pub status: StatusPolicy,
120 pub reject_legacy_typ: bool,
122 pub additional_typ: BTreeSet<String>,
126}
127
128impl SdJwtValidationOptions {
129 pub fn new() -> Self {
132 Self::default()
133 }
134
135 #[must_use]
137 pub fn with_time(mut self, time: TimeOptions) -> Self {
138 self.time = time;
139 self
140 }
141
142 #[must_use]
144 pub fn with_key_binding(mut self, key_binding: KeyBindingOptions) -> Self {
145 self.key_binding = Some(key_binding);
146 self
147 }
148
149 #[must_use]
151 pub fn with_status(mut self, status: StatusPolicy) -> Self {
152 self.status = status;
153 self
154 }
155
156 #[must_use]
158 pub fn rejecting_legacy_typ(mut self) -> Self {
159 self.reject_legacy_typ = true;
160 self
161 }
162
163 #[must_use]
165 pub fn with_additional_typ(mut self, typ: impl Into<String>) -> Self {
166 self.additional_typ.insert(typ.into());
167 self
168 }
169}
170
171#[derive(Debug, thiserror::Error)]
173#[non_exhaustive]
174pub enum SdJwtValidationError {
175 #[error(transparent)]
177 Credential(#[from] SdJwtVcError),
178 #[error(transparent)]
180 CredentialV2(#[from] SdJwtCredentialV2Error),
181 #[error("header `typ` is the pre-standard `vc+sd-jwt`")]
183 LegacyTyp,
184 #[error(transparent)]
187 Validation(#[from] ValidationError),
188 #[error("key binding is required, but the SD-JWT has no key binding JWT")]
190 KeyBindingRequired,
191 #[error("key binding is required, but `cnf` carries no usable key reference: {0}")]
194 NoHolderKey(KeyReferenceError),
195 #[error("key binding JWT issued at {} is older than {max_age:?} (now is {})", issued_at.to_rfc3339(), now.to_rfc3339())]
197 KeyBindingTooOld {
198 issued_at: DateTime<Utc>,
200 now: DateTime<Utc>,
202 max_age: Duration,
204 },
205 #[error("key binding `sd_hash` {found:?} is not the digest {expected:?} of the SD-JWT")]
207 SdHashMismatch {
208 expected: String,
210 found: Option<String>,
212 },
213}
214
215#[derive(Debug, Clone)]
217#[non_exhaustive]
218pub struct ValidatedSdJwtVc {
219 pub credential: SdJwtVc,
221 pub issuer_key: KeyReference,
223 pub key_binding: Option<JwtClaims>,
225 pub holder_key: Option<(KeyReference, Jwk)>,
229}
230
231#[derive(Debug, Clone)]
233#[non_exhaustive]
234pub struct ValidatedSdJwtCredentialV2 {
235 pub credential: SdJwtCredentialV2,
237 pub issuer_key: KeyReference,
239 pub key_binding: Option<JwtClaims>,
241 pub holder_key: Option<(KeyReference, Jwk)>,
244}
245
246pub struct SdJwtCredentialValidator<R, V = DefaultVerifier> {
248 resolver: R,
249 verifier: V,
250 status: Option<Box<dyn StatusCheck>>,
251}
252
253impl<R: KeyResolver, V: JwsVerifier> SdJwtCredentialValidator<R, V> {
254 pub fn new(resolver: R, verifier: V) -> Self {
257 Self {
258 resolver,
259 verifier,
260 status: None,
261 }
262 }
263
264 #[must_use]
267 pub fn with_status_check(mut self, check: impl StatusCheck + 'static) -> Self {
268 self.status = Some(Box::new(check));
269 self
270 }
271
272 pub fn resolver(&self) -> &R {
274 &self.resolver
275 }
276
277 pub fn verifier(&self) -> &V {
279 &self.verifier
280 }
281
282 pub fn has_status_check(&self) -> bool {
284 self.status.is_some()
285 }
286
287 pub async fn validate(
294 &self,
295 sd_jwt: &SdJwt,
296 options: &SdJwtValidationOptions,
297 ) -> Result<ValidatedSdJwtVc, SdJwtValidationError> {
298 let credential = SdJwtVc::from_sd_jwt(sd_jwt.clone())?;
299 self.validate_credential(credential, options).await
300 }
301
302 pub async fn validate_credential(
308 &self,
309 credential: SdJwtVc,
310 options: &SdJwtValidationOptions,
311 ) -> Result<ValidatedSdJwtVc, SdJwtValidationError> {
312 if options.reject_legacy_typ && credential.has_legacy_typ() {
313 return Err(SdJwtValidationError::LegacyTyp);
314 }
315 let claims = credential.claims();
316 let issuer = claims.iss.as_deref();
317 if issuer.is_none() && !credential.header().additional.contains_key("x5c") {
320 return Err(ValidationError::from(CredentialError::MissingClaim("iss")).into());
321 }
322 let time = options.time.pinned();
324 let (issuer_key, key) = self
325 .verify_issuer_signature(credential.sd_jwt(), issuer, time)
326 .await?;
327 check_issuer(issuer, &issuer_key, &key)?;
328
329 let mut time_claims = JwtClaims::new();
330 time_claims.nbf = claims.nbf;
331 time_claims.exp = claims.exp;
332 time_claims.iat = claims.iat;
333 time.check_claims(&time_claims)?;
334
335 let (key_binding, holder_key) = match &options.key_binding {
336 Some(required) => {
337 let (claims, holder_key) = self
338 .check_key_binding(credential.sd_jwt(), credential.confirmation(), required)
339 .await?;
340 (Some(claims), Some(holder_key))
341 }
342 None => (None, None),
343 };
344
345 self.check_status(
346 claims
347 .status
348 .iter()
349 .map(CredentialStatus::StatusClaim)
350 .collect(),
351 options.status,
352 time,
353 )
354 .await?;
355
356 Ok(ValidatedSdJwtVc {
357 credential,
358 issuer_key,
359 key_binding,
360 holder_key,
361 })
362 }
363
364 pub async fn validate_v2(
371 &self,
372 sd_jwt: &SdJwt,
373 options: &SdJwtValidationOptions,
374 ) -> Result<ValidatedSdJwtCredentialV2, SdJwtValidationError> {
375 let credential =
376 SdJwtCredentialV2::from_sd_jwt_with(sd_jwt.clone(), &options.additional_typ)?;
377 self.validate_credential_v2(credential, options).await
378 }
379
380 pub async fn validate_credential_v2(
386 &self,
387 credential: SdJwtCredentialV2,
388 options: &SdJwtValidationOptions,
389 ) -> Result<ValidatedSdJwtCredentialV2, SdJwtValidationError> {
390 let time = options.time.pinned();
392 let options = &SdJwtValidationOptions {
393 time,
394 ..options.clone()
395 };
396 let validated = self
397 .validate_credential_v2_unchecked_status(credential, options)
398 .await?;
399 let credential = &validated.credential;
400 self.check_status(
401 credential
402 .credential()
403 .statuses()
404 .map(CredentialStatus::Vcdm)
405 .chain(credential.status().map(CredentialStatus::StatusClaim))
406 .collect(),
407 options.status,
408 time,
409 )
410 .await?;
411 Ok(validated)
412 }
413
414 pub(crate) async fn validate_credential_v2_unchecked_status(
417 &self,
418 credential: SdJwtCredentialV2,
419 options: &SdJwtValidationOptions,
420 ) -> Result<ValidatedSdJwtCredentialV2, SdJwtValidationError> {
421 let vc = credential.credential();
422 let issuer = vc.issuer.id().as_str();
423 let time = options.time.pinned();
425 let (issuer_key, key) = self
426 .verify_issuer_signature(credential.sd_jwt(), Some(issuer), time)
427 .await?;
428 check_issuer(Some(issuer), &issuer_key, &key)?;
429 time.check_claims(credential.claims())?;
430 time.check(vc.valid_from, vc.valid_until, None)?;
431 let (key_binding, holder_key) = match &options.key_binding {
432 Some(required) => {
433 let (claims, holder_key) = self
434 .check_key_binding(credential.sd_jwt(), credential.confirmation(), required)
435 .await?;
436 (Some(claims), Some(holder_key))
437 }
438 None => (None, None),
439 };
440 Ok(ValidatedSdJwtCredentialV2 {
441 credential,
442 issuer_key,
443 key_binding,
444 holder_key,
445 })
446 }
447
448 async fn verify_issuer_signature(
451 &self,
452 sd_jwt: &SdJwt,
453 issuer: Option<&str>,
454 time: TimeOptions,
455 ) -> Result<(KeyReference, Jwk), ValidationError> {
456 let jws = sd_jwt.jwt().decode()?;
457 let (reference, key) = resolve_jws_key(
458 &self.resolver,
459 &jws,
460 issuer,
461 KeyRole::Issuer,
462 time.now().timestamp(),
463 )
464 .await?;
465 jws.verify(&self.verifier, &key)?;
466 Ok((reference, key))
467 }
468
469 async fn holder_key(
472 &self,
473 cnf: Option<&Confirmation>,
474 time: TimeOptions,
475 ) -> Result<(KeyReference, Jwk), SdJwtValidationError> {
476 let cnf = cnf.ok_or(SdJwtValidationError::NoHolderKey(
477 KeyReferenceError::Missing,
478 ))?;
479 let reference =
480 KeyReference::from_confirmation(cnf).map_err(SdJwtValidationError::NoHolderKey)?;
481 let key = match &reference {
482 KeyReference::Jwk(jwk) => jwk.public(),
483 reference => self
484 .resolver
485 .resolve_key_at(reference, KeyRole::Subject, time.now().timestamp())
486 .await
487 .map_err(|source| ValidationError::KeyResolution {
488 key: Box::new(reference.clone()),
489 source,
490 })?,
491 };
492 Ok((reference, key))
493 }
494
495 async fn check_key_binding(
498 &self,
499 sd_jwt: &SdJwt,
500 cnf: Option<&Confirmation>,
501 required: &KeyBindingOptions,
502 ) -> Result<(JwtClaims, (KeyReference, Jwk)), SdJwtValidationError> {
503 let kb_jwt = sd_jwt
504 .key_binding_jwt()
505 .ok_or(SdJwtValidationError::KeyBindingRequired)?;
506 let time = required.time.pinned();
508 let holder_key = self.holder_key(cnf, time).await?;
509 let jws = kb_jwt.decode().map_err(ValidationError::from)?;
510 match jws.header().typ.as_deref() {
511 Some(super::KB_JWT_TYP) => {}
512 found => {
513 return Err(ValidationError::UnexpectedTyp {
514 expected: super::KB_JWT_TYP,
515 found: found.unwrap_or("").to_owned(),
516 }
517 .into());
518 }
519 }
520 jws.verify(&self.verifier, &holder_key.1)
521 .map_err(ValidationError::from)?;
522 let claims: JwtClaims =
523 serde_json::from_slice(jws.payload()).map_err(ValidationError::Payload)?;
524
525 if !claims.audiences().any(|aud| aud == required.audience) {
526 return Err(ValidationError::AudienceMismatch {
527 expected: required.audience.clone(),
528 found: claims.aud.clone(),
529 }
530 .into());
531 }
532 let nonce = claims.additional.get("nonce").and_then(|v| v.as_str());
533 if nonce != Some(required.nonce.as_str()) {
534 return Err(ValidationError::NonceMismatch {
535 expected: required.nonce.clone(),
536 found: nonce.map(str::to_owned),
537 }
538 .into());
539 }
540 let iat = claims
541 .iat
542 .ok_or(CredentialError::MissingClaim("iat"))
543 .map_err(ValidationError::from)?;
544 let issued_at = JwtClaims::timestamp(iat).ok_or_else(|| {
545 ValidationError::from(CredentialError::InvalidClaim {
546 claim: "iat",
547 reason: format!("{iat} is out of range"),
548 })
549 })?;
550 time.check(None, None, Some(issued_at))?;
551 if let Some(max_age) = required.max_age {
552 let now = time.now();
553 let oldest = chrono::TimeDelta::from_std(max_age)
555 .ok()
556 .and_then(|delta| now.checked_sub_signed(delta))
557 .unwrap_or(DateTime::<Utc>::MIN_UTC);
558 if issued_at < oldest {
559 return Err(SdJwtValidationError::KeyBindingTooOld {
560 issued_at,
561 now,
562 max_age,
563 });
564 }
565 }
566 let alg = sd_jwt.hash_algorithm().map_err(SdJwtVcError::from)?;
567 let expected = sd_jwt.sd_hash(alg);
568 let found = claims.additional.get("sd_hash").and_then(|v| v.as_str());
569 if found != Some(expected.as_str()) {
570 return Err(SdJwtValidationError::SdHashMismatch {
571 expected,
572 found: found.map(str::to_owned),
573 });
574 }
575 Ok((claims, holder_key))
576 }
577
578 async fn check_status(
581 &self,
582 statuses: Vec<CredentialStatus<'_>>,
583 policy: StatusPolicy,
584 time: TimeOptions,
585 ) -> Result<(), SdJwtValidationError> {
586 Ok(check_statuses(self.status.as_deref(), statuses, policy, time).await?)
587 }
588}
589
590fn check_issuer(
597 issuer: Option<&str>,
598 reference: &KeyReference,
599 key: &Jwk,
600) -> Result<(), ValidationError> {
601 let Some(issuer) = issuer else {
602 if matches!(reference, KeyReference::X509Chain(_)) && reference.binds_to(None, key) {
603 return Ok(());
604 }
605 return Err(CredentialError::MissingClaim("iss").into());
606 };
607 if !reference.binds_to(Some(issuer), key) {
608 return Err(ValidationError::IssuerMismatch {
609 issuer: Uri::parse(issuer).map_err(|e| CredentialError::InvalidClaim {
610 claim: "iss",
611 reason: e.to_string(),
612 })?,
613 key: Box::new(reference.clone()),
614 });
615 }
616 Ok(())
617}
618
619impl<R: core::fmt::Debug, V: core::fmt::Debug> core::fmt::Debug for SdJwtCredentialValidator<R, V> {
620 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
621 f.debug_struct("SdJwtCredentialValidator")
622 .field("resolver", &self.resolver)
623 .field("verifier", &self.verifier)
624 .field("status", &self.status.as_ref().map(|_| "StatusCheck"))
625 .finish()
626 }
627}