Skip to main content

identity_kit/sd_jwt_vc/
validation.rs

1//! Validation of SD-JWT credentials: issuer signature and binding, time claims, key binding,
2//! status.
3//!
4//! [`SdJwtCredentialValidator`] is the SD-JWT counterpart of
5//! [`JwtCredentialValidator`](crate::vc::validation::JwtCredentialValidator), over the same
6//! [`KeyResolver`] and [`JwsVerifier`]. It validates both SD-JWT credential types
7//! ([two SD-JWT credential types](super#two-sd-jwt-credential-types)):
8//! [`validate`](SdJwtCredentialValidator::validate) an SD-JWT VC,
9//! [`validate_v2`](SdJwtCredentialValidator::validate_v2) a VCDM 2.0 credential secured with
10//! SD-JWT. Each checks, in order:
11//!
12//! 1. The SD-JWT parses as an [`SdJwtVc`] (`typ`, disclosures, claims; RFC 9901 §7.1 steps 3
13//!    to 5, SD-JWT VC §2.2) or as an [`SdJwtCredentialV2`] (`typ` `vc+sd-jwt` when present,
14//!    or one of `options.additional_typ`; disclosures; the payload as a
15//!    [`CredentialV2`](crate::vc::CredentialV2) with its registered claims agreeing with it).
16//! 2. The header of the issuer-signed JWT names its key ([`KeyReference::candidates`], with
17//!    the issuer, `iss` or the credential's `issuer`, as `iss`): a `kid` that is a DID URL of
18//!    the form `did:…#fragment` (a path or DID parameters such as `versionId` are refused, as
19//!    in the JWT validators, ADR 0004), a `#fragment` relative to a DID issuer, an `x5c`
20//!    certificate chain (SD-JWT VC §3.5, resolved by `X509Resolver` with the `x509` feature),
21//!    a `kid` into the JWT VC issuer metadata of an HTTPS issuer (SD-JWT VC §3.5, resolved by
22//!    `JwksResolver` with the `jwks` feature), or a `jwk` or `jku` header. The first of them
23//!    the resolver handles is resolved for [`KeyRole::Issuer`] at the validation time,
24//!    verifies the signature, and belongs to the issuer ([`KeyReference::binds_to`]). An
25//!    SD-JWT VC signed with a certificate chain needs no `iss`: its issuer is the subject of
26//!    the first certificate, and an `iss` it does carry must be one that certificate names.
27//!    Signed any other way, it needs one.
28//! 3. `nbf`, `exp` and `iat` hold at the validation time, and so do `validFrom` and
29//!    `validUntil` of a VCDM 2.0 credential.
30//! 4. When the options require key binding (RFC 9901 §7.3): the SD-JWT+KB carries a key
31//!    binding JWT with `typ: kb+jwt`, signed by the holder's key, for the expected audience
32//!    and nonce, issued within the window, with an `sd_hash` over the presented SD-JWT. The
33//!    holder's key is `cnf.jwk`, used as it is since the issuer signed it, or else the key
34//!    `cnf.kid` names, an absolute DID URL resolved for [`KeyRole::Subject`]
35//!    (`authentication`); see [`KeyReference::from_confirmation`].
36//! 5. `status` (as [`CredentialStatus::StatusClaim`]) and the `credentialStatus` entries of a VCDM
37//!    2.0 credential (as [`CredentialStatus::Vcdm`]) pass the [`StatusCheck`], per the
38//!    [`StatusPolicy`].
39//!
40//! Type metadata is a separate step the application runs when its policy asks for it:
41//! [`TypeMetadata::check_claims`](super::TypeMetadata::check_claims).
42
43use 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/// Moved to [`status_list::StatusListCheck`](crate::status_list::StatusListCheck).
60#[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/// What a key binding JWT must prove (RFC 9901 §7.3, step 5).
66///
67/// The key binding JWT must be signed by the holder's key the credential's `cnf` names: by
68/// value in `cnf.jwk`, or by reference in `cnf.kid`, an absolute DID URL the validator's
69/// [`KeyResolver`] resolves for [`KeyRole::Subject`] (`authentication`).
70#[derive(Debug, Clone, PartialEq, Eq)]
71#[non_exhaustive]
72pub struct KeyBindingOptions {
73    /// The audience the key binding JWT must name: this verifier.
74    pub audience: String,
75    /// The nonce it must carry: the one of this transaction.
76    pub nonce: String,
77    /// The time its `iat` is checked against, with leeway.
78    pub time: TimeOptions,
79    /// How old it may be, if bounded.
80    pub max_age: Option<Duration>,
81}
82
83impl KeyBindingOptions {
84    /// Key binding for `audience` with `nonce`, checked at the current time with no age
85    /// bound.
86    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    /// These options checking `iat` against `time`.
96    #[must_use]
97    pub fn with_time(mut self, time: TimeOptions) -> Self {
98        self.time = time;
99        self
100    }
101
102    /// These options rejecting a key binding JWT older than `max_age`.
103    #[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/// Options of [`SdJwtCredentialValidator`].
111#[derive(Debug, Clone, Default, PartialEq, Eq)]
112#[non_exhaustive]
113pub struct SdJwtValidationOptions {
114    /// The validation time and leeway of the issuer-signed JWT.
115    pub time: TimeOptions,
116    /// The key binding required, if any; a key binding JWT is not verified otherwise.
117    pub key_binding: Option<KeyBindingOptions>,
118    /// What to do about `status` (and `credentialStatus`).
119    pub status: StatusPolicy,
120    /// Whether to reject the pre-standard `typ: vc+sd-jwt` on an SD-JWT VC.
121    pub reject_legacy_typ: bool,
122    /// Header `typ` values accepted for a VCDM 2.0 credential besides `vc+sd-jwt`; none by
123    /// default. A token without `typ` is always accepted there. An SD-JWT VC's `typ` is fixed
124    /// by its specification and not affected.
125    pub additional_typ: BTreeSet<String>,
126}
127
128impl SdJwtValidationOptions {
129    /// Default options: validate now without leeway, no key binding required,
130    /// [`StatusPolicy::Strict`], `vc+sd-jwt` accepted.
131    pub fn new() -> Self {
132        Self::default()
133    }
134
135    /// These options with `time`.
136    #[must_use]
137    pub fn with_time(mut self, time: TimeOptions) -> Self {
138        self.time = time;
139        self
140    }
141
142    /// These options requiring `key_binding`.
143    #[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    /// These options with `status`.
150    #[must_use]
151    pub fn with_status(mut self, status: StatusPolicy) -> Self {
152        self.status = status;
153        self
154    }
155
156    /// These options rejecting `typ: vc+sd-jwt` on an SD-JWT VC.
157    #[must_use]
158    pub fn rejecting_legacy_typ(mut self) -> Self {
159        self.reject_legacy_typ = true;
160        self
161    }
162
163    /// These options also accepting a VCDM 2.0 credential whose header `typ` is `typ`.
164    #[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/// Why an SD-JWT credential did not validate.
172#[derive(Debug, thiserror::Error)]
173#[non_exhaustive]
174pub enum SdJwtValidationError {
175    /// The SD-JWT is not a well-formed SD-JWT VC.
176    #[error(transparent)]
177    Credential(#[from] SdJwtVcError),
178    /// The SD-JWT is not a well-formed VCDM 2.0 credential secured with SD-JWT.
179    #[error(transparent)]
180    CredentialV2(#[from] SdJwtCredentialV2Error),
181    /// The issuer-signed JWT has the pre-standard `typ: vc+sd-jwt`, which the options reject.
182    #[error("header `typ` is the pre-standard `vc+sd-jwt`")]
183    LegacyTyp,
184    /// A check shared with the JWT validators failed: `kid`, key resolution, signature,
185    /// issuer binding, time, audience, nonce, status.
186    #[error(transparent)]
187    Validation(#[from] ValidationError),
188    /// Key binding is required and the SD-JWT carries no key binding JWT.
189    #[error("key binding is required, but the SD-JWT has no key binding JWT")]
190    KeyBindingRequired,
191    /// Key binding is required and `cnf` names no key this crate can look for: there is no
192    /// `cnf`, or [`KeyReference::from_confirmation`] refuses it.
193    #[error("key binding is required, but `cnf` carries no usable key reference: {0}")]
194    NoHolderKey(KeyReferenceError),
195    /// The key binding JWT is older than allowed.
196    #[error("key binding JWT issued at {} is older than {max_age:?} (now is {})", issued_at.to_rfc3339(), now.to_rfc3339())]
197    KeyBindingTooOld {
198        /// Its `iat`.
199        issued_at: DateTime<Utc>,
200        /// The validation time.
201        now: DateTime<Utc>,
202        /// The bound.
203        max_age: Duration,
204    },
205    /// The key binding JWT's `sd_hash` is not the digest of the presented SD-JWT.
206    #[error("key binding `sd_hash` {found:?} is not the digest {expected:?} of the SD-JWT")]
207    SdHashMismatch {
208        /// The digest of the SD-JWT.
209        expected: String,
210        /// The `sd_hash` found.
211        found: Option<String>,
212    },
213}
214
215/// A validated SD-JWT VC.
216#[derive(Debug, Clone)]
217#[non_exhaustive]
218pub struct ValidatedSdJwtVc {
219    /// The credential, with the presented disclosures applied.
220    pub credential: SdJwtVc,
221    /// Where the issuer-signed JWT says its key is.
222    pub issuer_key: KeyReference,
223    /// The claims of the key binding JWT, when key binding was required and verified.
224    pub key_binding: Option<JwtClaims>,
225    /// The holder's key that verified the key binding JWT, and where `cnf` said it is (a DID
226    /// URL to compare with the presentation's holder or the credential subject, say), when key
227    /// binding was required and verified.
228    pub holder_key: Option<(KeyReference, Jwk)>,
229}
230
231/// A validated VCDM 2.0 credential secured with SD-JWT.
232#[derive(Debug, Clone)]
233#[non_exhaustive]
234pub struct ValidatedSdJwtCredentialV2 {
235    /// The credential, with the presented disclosures applied.
236    pub credential: SdJwtCredentialV2,
237    /// Where the issuer-signed JWT says its key is.
238    pub issuer_key: KeyReference,
239    /// The claims of the key binding JWT, when key binding was required and verified.
240    pub key_binding: Option<JwtClaims>,
241    /// The holder's key that verified the key binding JWT, and where `cnf` said it is, when key
242    /// binding was required and verified.
243    pub holder_key: Option<(KeyReference, Jwk)>,
244}
245
246/// Validates SD-JWT credentials; see the [module documentation](self) for the checks.
247pub 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    /// A validator resolving keys with `resolver` and verifying signatures with `verifier`,
255    /// without a status check.
256    pub fn new(resolver: R, verifier: V) -> Self {
257        Self {
258            resolver,
259            verifier,
260            status: None,
261        }
262    }
263
264    /// This validator checking the `status` claim and, for a VCDM 2.0 credential, the
265    /// `credentialStatus` entries with `check`.
266    #[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    /// The key resolver.
273    pub fn resolver(&self) -> &R {
274        &self.resolver
275    }
276
277    /// The signature verifier.
278    pub fn verifier(&self) -> &V {
279        &self.verifier
280    }
281
282    /// Whether a status check is configured.
283    pub fn has_status_check(&self) -> bool {
284        self.status.is_some()
285    }
286
287    /// Validates `sd_jwt` as an SD-JWT VC.
288    ///
289    /// # Errors
290    ///
291    /// The first [`SdJwtValidationError`] found, in the order the [module
292    /// documentation](self) lists the checks.
293    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    /// Validates the parsed `credential`.
303    ///
304    /// # Errors
305    ///
306    /// As [`validate`](Self::validate).
307    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        // Only a certificate chain identifies an issuer without `iss`: anything else fails
318        // here, before a key is looked for.
319        if issuer.is_none() && !credential.header().additional.contains_key("x5c") {
320            return Err(ValidationError::from(CredentialError::MissingClaim("iss")).into());
321        }
322        // One validation time for the key and the claims.
323        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    /// Validates `sd_jwt` as a VCDM 2.0 credential secured with SD-JWT (VC-JOSE-COSE §3.2.1).
365    ///
366    /// # Errors
367    ///
368    /// The first [`SdJwtValidationError`] found, in the order the [module
369    /// documentation](self) lists the checks.
370    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    /// Validates the parsed `credential`.
381    ///
382    /// # Errors
383    ///
384    /// As [`validate_v2`](Self::validate_v2).
385    pub async fn validate_credential_v2(
386        &self,
387        credential: SdJwtCredentialV2,
388        options: &SdJwtValidationOptions,
389    ) -> Result<ValidatedSdJwtCredentialV2, SdJwtValidationError> {
390        // One validation time for the key, the claims and the status.
391        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    /// Steps 2 to 4 of [`validate_credential_v2`](Self::validate_credential_v2): everything
415    /// but the status checks, which the presentation validator runs with its own check.
416    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        // One validation time for the key and the claims.
424        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    /// Resolves the key the issuer-signed JWT names, `issuer` being its `iss`, for
449    /// [`KeyRole::Issuer`] at `time` and verifies the signature; the reference and the key.
450    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    /// The holder's key `cnf` names: `cnf.jwk` as it is, since the issuer signed it, or the
470    /// key a `cnf.kid` resolves to for [`KeyRole::Subject`].
471    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    /// RFC 9901 §7.3, step 5: the key binding JWT of `sd_jwt`, signed by the key `cnf` names;
496    /// its claims and that key.
497    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        // One validation time for the holder's key and the key binding JWT.
507        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            // A `max_age` beyond what `chrono` represents bounds nothing.
554            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    /// Checks every status entry with this validator's check, per `policy`, at `time`, the
579    /// time the credential was validated at.
580    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
590/// Checks that `key`, which `reference` resolved to, belongs to `issuer`, the `iss` of the
591/// credential ([`KeyReference::binds_to`]).
592///
593/// A credential signed with a certificate chain needs no `iss`: its issuer is the subject of
594/// the first certificate (SD-JWT VC §3.5). Any other reference identifies the issuer by `iss`
595/// alone, so it must be there; a key by value in particular binds to no party at all.
596fn 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}