diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f802060..13a49766 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,12 @@ This file was started retroactively on 2026-07-03 at v0.4.0; entries for ### Breaking +- **`sd_jwt_vc::verify` takes `VerifyOptions`.** The final argument is required to set the + clock-skew leeway and verifier audience. A present `aud` must name that audience, or the + token is refused; a token with `aud` is refused when no audience is configured. **Migration:** + append `VerifyOptions::new()` to an existing call to retain default verification for + credentials without `aud`, and use `.for_audience(...)` for credentials that carry it. (#693) + - **Signing and publishing take a `KeyBackend`, not a `KeyStore`.** `jws::sign`, `jws::sign_typed`, `jws::verify`, `build_did_document`, `build_issuer_metadata`, `sd_jwt_vc::issue` and `sign_access_credential` take `&dyn KeyBackend`, and @@ -217,6 +223,10 @@ This file was started retroactively on 2026-07-03 at v0.4.0; entries for ### Added +- **Configurable clock-skew leeway for JWT, COSE, and SD-JWT temporal verification.** + `VerifyOptions::with_leeway(seconds)` defaults to zero, is capped at five minutes, and + applies equally to `exp` and `nbf`. (#693) + - **`TransferChain::from_value`: a stored chain read with its refusal as a value.** It applies the check `Deserialize` applies, and returns `ChainReadError`. `Refused` holds `TransferError::InvalidChain`, which names the passport and the record that breaks the diff --git a/benches/src/sd_jwt.rs b/benches/src/sd_jwt.rs index 5fdbebd2..2aee5343 100644 --- a/benches/src/sd_jwt.rs +++ b/benches/src/sd_jwt.rs @@ -10,6 +10,7 @@ use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main}; use dpp_crypto::sd_jwt::{SdJwt, conceal, conceal_elements}; use dpp_domain::access::ProductGroupAccessPolicy; use dpp_domain::{Passport, ProductGroup}; +use dpp_vc::jose::VerifyOptions; use dpp_vc::sd_jwt_vc::{Issuance, issue, vct_for, verify}; use serde_json::{Map, Value, json}; @@ -82,7 +83,17 @@ fn credential(c: &mut Criterion) { let public_key = store.load_key(KEY_ID).unwrap().public_key(); c.bench_function("sd_jwt_vc_verify_battery", |b| { - b.iter(|| verify(&serialised, &public_key, &vct, now, None).unwrap()); + b.iter(|| { + verify( + &serialised, + &public_key, + &vct, + now, + None, + VerifyOptions::new(), + ) + .unwrap() + }); }); // The wire format on its own, without the signature check. diff --git a/crates/dpp-tests/tests/jws_crit_rejection.rs b/crates/dpp-tests/tests/jws_crit_rejection.rs index 76aaec7d..1ba2c5aa 100644 --- a/crates/dpp-tests/tests/jws_crit_rejection.rs +++ b/crates/dpp-tests/tests/jws_crit_rejection.rs @@ -29,6 +29,7 @@ use dpp_rules::bundle::{ }; use dpp_tests::fixtures::make_subject; use dpp_vc::credential::authenticate_access_credential; +use dpp_vc::jose::VerifyOptions; use dpp_vc::sd_jwt_vc::{Issuance, issue, verify}; use dpp_vc::{ CredentialBuilder, CredentialRole, LocalIdentityService, SD_JWT_VC_TYP, SdJwtVcError, @@ -248,7 +249,8 @@ fn an_sd_jwt_vc_with_crit_is_refused() { &key, &vct, now, - None + None, + VerifyOptions::new(), ) .is_ok(), "control: the same credential without crit must verify" @@ -259,7 +261,8 @@ fn an_sd_jwt_vc_with_crit_is_refused() { &key, &vct, now, - None + None, + VerifyOptions::new(), ), Err(SdJwtVcError::BadSignature) )); diff --git a/crates/dpp-tests/tests/sdjwt_vc_oracle_corpus.rs b/crates/dpp-tests/tests/sdjwt_vc_oracle_corpus.rs index e0c31104..7213339d 100644 --- a/crates/dpp-tests/tests/sdjwt_vc_oracle_corpus.rs +++ b/crates/dpp-tests/tests/sdjwt_vc_oracle_corpus.rs @@ -62,6 +62,7 @@ use dpp_tests::fixtures::{ passport_with, schema_compat_fixture as fixture_for, schema_for, with_restricted_envelope_members, with_restricted_members, }; +use dpp_vc::jose::VerifyOptions; use dpp_vc::sd_jwt_vc::{Issuance, PASSPORT_CLAIM, SdJwtVcError, issue, vct_for, verify}; use serde_json::{Map, Number, Value, json}; @@ -191,7 +192,7 @@ fn verify_under( policy: Option<&KeyBindingPolicy>, ) -> Result, SdJwtVcError> { match ed25519_key(public_key_b64) { - Some(key) => verify(token, &key, vct, now, policy), + Some(key) => verify(token, &key, vct, now, policy, VerifyOptions::new()), None => Err(SdJwtVcError::BadSignature), } } diff --git a/crates/dpp-vc/src/jose/cose_verify.rs b/crates/dpp-vc/src/jose/cose_verify.rs index 9f3f0aa2..547e1651 100644 --- a/crates/dpp-vc/src/jose/cose_verify.rs +++ b/crates/dpp-vc/src/jose/cose_verify.rs @@ -62,9 +62,9 @@ pub(super) const PRESENTATION_COSE_TYP: &str = "vp+cose"; /// header", and §1 says a recipient "MUST NOT use the information in the CWT Claims header /// parameter beyond the integrity protection or authentication afforded", so one in the /// unprotected header is refused by the COSE layer. The claims are applied as the same JWT -/// claims are in [`verify_credential`](super::verify_credential): `exp` must be later than a -/// `now` and `nbf` not later, with no leeway, and neither is read without a `now`; an `aud` -/// is accepted only when it names the audience the caller identifies as (RFC 7519 §4.1.3, +/// claims are in [`verify_credential`](super::verify_credential): `exp` and `nbf` use the +/// leeway in `options`, and neither is read without a `now`; an `aud` is accepted only when it +/// names the audience the caller identifies as (RFC 7519 §4.1.3, /// which RFC 8392 §3.1.3 adopts), and a message that carries one is refused when the caller /// gave none. `iat` is never checked. /// @@ -159,9 +159,10 @@ fn open( if let Some(now) = options.now { // Exact for every instant a NumericDate can sensibly name, as in the JOSE form. let now = now as f64; + let leeway = options.leeway().as_secs_f64(); for (claim, seconds) in [("exp", exp), ("nbf", nbf)] { if let Some(seconds) = seconds { - check_instant(claim, seconds, now)?; + check_instant(claim, seconds, now, leeway)?; } } } diff --git a/crates/dpp-vc/src/jose/mod.rs b/crates/dpp-vc/src/jose/mod.rs index f4777809..b51ce362 100644 --- a/crates/dpp-vc/src/jose/mod.rs +++ b/crates/dpp-vc/src/jose/mod.rs @@ -66,12 +66,12 @@ //! ([`JoseError::KidNotAbsolute`]) when there is no `iss` and the issuer, or the holder of a //! presentation, is a URL, so the tokens this crate writes stay strict. //! -//! **Time is explicit.** A [`VerifyOptions`] carries `now`, seconds since the epoch. -//! Under a `now`, `exp` must be a number and `now` before it, and `nbf` must be a -//! number and not after `now`, with no leeway, as in `sd_jwt_vc::verify`. With none -//! neither claim is read. `iat` is never checked: §3.1.3 says it describes -//! the signature, not the credential. A credential's own `validFrom` and -//! `validUntil` are the caller's to check. +//! **Time is explicit.** A [`VerifyOptions`] carries `now`, seconds since the epoch, and an +//! optional leeway for `exp` and `nbf`, capped at [`MAX_LEEWAY_SECONDS`]. Leeway defaults to +//! zero. `sd_jwt_vc::verify` takes the same options for the same JWT time claims. With no `now`, +//! JOSE and COSE do not read `exp` or `nbf`. `iat` is never checked: §3.1.3 says it describes +//! the signature, not the credential. A credential's own `validFrom` and `validUntil` are +//! checked separately by `verify_credential_claims` and do not use this leeway. //! //! **The audience is explicit too.** The same [`VerifyOptions`] carries the audience the //! caller identifies as. RFC 7519 §4.1.3 says a JWT "MUST be rejected" when the principal @@ -227,12 +227,13 @@ mod tests; pub use cose_sign::{sign_credential_cose, sign_presentation_cose}; pub use cose_verify::{verify_credential_cose, verify_presentation_cose}; pub use error::JoseError; -pub use options::{KeyBindingRequirement, VerifyOptions}; +pub use options::{KeyBindingRequirement, MAX_LEEWAY_SECONDS, VerifyOptions}; pub use presentation::verify_presentation; pub use sd_jwt_sign::{sign_credential_sd_jwt, sign_presentation_sd_jwt}; pub use sd_jwt_verify::{verify_credential_sd_jwt, verify_presentation_sd_jwt}; pub use sign::{sign_credential, sign_presentation}; pub use unverified_envelope::UnverifiedEnvelope; pub use verified_presentation::VerifiedPresentation; +pub(crate) use verify::check_audience; pub use verify::verify_credential; pub use vocabulary::{CREDENTIAL_TERMS, PRESENTATION_TERMS}; diff --git a/crates/dpp-vc/src/jose/options.rs b/crates/dpp-vc/src/jose/options.rs index 55556c7c..e1568629 100644 --- a/crates/dpp-vc/src/jose/options.rs +++ b/crates/dpp-vc/src/jose/options.rs @@ -1,16 +1,23 @@ -//! What a caller decides before it verifies a token: the time, the audience it identifies -//! as, and, for an SD-JWT, whether Key Binding is required. +//! What a caller decides before it verifies a token: the time, its clock-skew allowance, +//! the audience it identifies as, and, for an SD-JWT, whether Key Binding is required. + +use std::time::Duration; use dpp_crypto::sd_jwt::KeyBindingPolicy; -/// The time and the audience a verifier checks a token against. +/// The greatest clock-skew allowance a verifier can configure, in seconds. +pub const MAX_LEEWAY_SECONDS: u64 = 300; + +/// The time, clock-skew allowance, and audience a verifier checks a token against. /// -/// Both are the caller's to supply, and neither has a value that is assumed: +/// The time and audience are the caller's to supply; the leeway defaults to zero: /// /// - **`now`** is seconds since the Unix epoch, supplied rather than read, as in /// [`sd_jwt_vc::verify`](crate::sd_jwt_vc::verify): a result that depends on a hidden /// clock cannot be reproduced. With a `now`, `exp` and `nbf` are checked (RFC 7519 /// §4.1.4 and §4.1.5). Without one they are not read. +/// - **`leeway`** is an optional allowance for clock skew, applied alike to `exp` and `nbf`. +/// It defaults to zero and is capped at [`MAX_LEEWAY_SECONDS`]. /// - **`audience`** is the value the caller identifies itself with. RFC 7519 §4.1.3 says /// "If the principal processing the claim does not identify itself with a value in the /// "aud" claim when this claim is present, then the JWT MUST be rejected." So a token @@ -18,26 +25,31 @@ use dpp_crypto::sd_jwt::KeyBindingPolicy; /// identifies itself with nothing, so a token that carries `aud` is refused. A token /// with no `aud` is not affected by either case. /// -/// `VerifyOptions::new()` is `now` unset and no audience, which checks no time and refuses -/// a token that carries `aud`. +/// `VerifyOptions::new()` is `now` unset, no leeway, and no audience, which checks no time +/// and refuses a token that carries `aud`. /// /// ``` /// use dpp_vc::jose::VerifyOptions; /// -/// let options = VerifyOptions::new().at(1_800_000_000).for_audience("https://verifier.example"); +/// let options = VerifyOptions::new() +/// .at(1_800_000_000) +/// .with_leeway(30) +/// .for_audience("https://verifier.example"); /// # let _ = options; /// ``` #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct VerifyOptions<'a> { pub(crate) now: Option, + pub(crate) leeway: Duration, pub(crate) audience: Option<&'a str>, } impl<'a> VerifyOptions<'a> { - /// No time and no audience. + /// No time, leeway, or audience. pub const fn new() -> Self { Self { now: None, + leeway: Duration::ZERO, audience: None, } } @@ -49,12 +61,30 @@ impl<'a> VerifyOptions<'a> { self } + /// Allow up to `seconds` of clock skew for `exp` and `nbf` checks. + /// + /// Values above [`MAX_LEEWAY_SECONDS`] are capped at that limit. The default is zero. + #[must_use] + pub const fn with_leeway(mut self, seconds: u64) -> Self { + let seconds = if seconds > MAX_LEEWAY_SECONDS { + MAX_LEEWAY_SECONDS + } else { + seconds + }; + self.leeway = Duration::from_secs(seconds); + self + } + /// Identify as `audience`: a token whose `aud` names it is accepted. #[must_use] pub const fn for_audience(mut self, audience: &'a str) -> Self { self.audience = Some(audience); self } + + pub(crate) const fn leeway(self) -> Duration { + self.leeway + } } /// Whether Key Binding is required of an SD-JWT, which RFC 9901 §9.5 says "Verifiers MUST diff --git a/crates/dpp-vc/src/jose/tests/cose/claims.rs b/crates/dpp-vc/src/jose/tests/cose/claims.rs index e2cbf349..54e2f0bd 100644 --- a/crates/dpp-vc/src/jose/tests/cose/claims.rs +++ b/crates/dpp-vc/src/jose/tests/cose/claims.rs @@ -88,6 +88,23 @@ fn a_credential_that_is_not_yet_valid_is_refused_under_a_now_and_not_without_one assert!(verify_vc(&message).is_ok()); } +#[test] +fn configured_leeway_applies_equally_to_exp_and_nbf() { + let exp = forged_credential(&credential(), &cwt(vec![claim(4, uint(1_000))])); + assert!(verify_vc_with(&exp, VerifyOptions::new().at(1_002).with_leeway(3)).is_ok()); + assert_eq!( + verify_vc_with(&exp, VerifyOptions::new().at(1_003).with_leeway(3)), + Err(JoseError::Expired) + ); + + let nbf = forged_credential(&credential(), &cwt(vec![claim(5, uint(2_000))])); + assert!(verify_vc_with(&nbf, VerifyOptions::new().at(1_997).with_leeway(3)).is_ok()); + assert_eq!( + verify_vc_with(&nbf, VerifyOptions::new().at(1_996).with_leeway(3)), + Err(JoseError::NotYetValid) + ); +} + /// A NumericDate may be fractional, and `iat` is never checked (§3.3.3: it describes the /// signature, not the credential). #[test] diff --git a/crates/dpp-vc/src/jose/tests/temporal.rs b/crates/dpp-vc/src/jose/tests/temporal.rs index 96bfa41e..be1389fe 100644 --- a/crates/dpp-vc/src/jose/tests/temporal.rs +++ b/crates/dpp-vc/src/jose/tests/temporal.rs @@ -8,8 +8,8 @@ use serde_json::{Value, json}; use dpp_crypto::jws::KeyAlgorithm; use dpp_crypto::keystore::KeyEntry; -use super::super::VerifyOptions; use super::super::{JoseError, verify_credential, verify_presentation}; +use super::super::{MAX_LEEWAY_SECONDS, VerifyOptions}; use crate::test_support::NOT_REQUIRED; use crate::test_support::at; use crate::test_support::{ @@ -30,7 +30,15 @@ fn credential_with(key: &KeyEntry, claim: &str, value: Value) -> String { } fn verify(token: &str, key: &KeyEntry, now: Option) -> Result { - verify_credential(token, &key.public_key(), at(now)) + verify_with_options(token, key, at(now)) +} + +fn verify_with_options( + token: &str, + key: &KeyEntry, + options: VerifyOptions<'_>, +) -> Result { + verify_credential(token, &key.public_key(), options) } // ── exp ─────────────────────────────────────────────────────────────────────── @@ -57,6 +65,50 @@ fn exp_may_be_fractional() { ); } +#[test] +fn exp_leeway_accepts_inside_and_refuses_outside() { + let key = key(); + let token = credential_with(&key, "exp", json!(NOW)); + + assert!(verify_with_options(&token, &key, at(Some(NOW + 2)).with_leeway(3),).is_ok()); + assert_eq!( + verify_with_options(&token, &key, at(Some(NOW + 3)).with_leeway(3)), + Err(JoseError::Expired) + ); +} + +#[test] +fn nbf_leeway_accepts_inside_and_refuses_outside() { + let key = key(); + let token = credential_with(&key, "nbf", json!(NOW)); + + assert!(verify_with_options(&token, &key, at(Some(NOW - 3)).with_leeway(3),).is_ok()); + assert_eq!( + verify_with_options(&token, &key, at(Some(NOW - 4)).with_leeway(3)), + Err(JoseError::NotYetValid) + ); +} + +#[test] +fn leeway_is_capped_at_five_minutes() { + let key = key(); + let token = credential_with(&key, "exp", json!(NOW)); + let max = i64::try_from(MAX_LEEWAY_SECONDS).expect("maximum leeway fits i64"); + + assert!( + verify_with_options( + &token, + &key, + at(Some(NOW + max - 1)).with_leeway(MAX_LEEWAY_SECONDS), + ) + .is_ok() + ); + assert_eq!( + verify_with_options(&token, &key, at(Some(NOW + max)).with_leeway(u64::MAX),), + Err(JoseError::Expired) + ); +} + // ── nbf ─────────────────────────────────────────────────────────────────────── #[test] diff --git a/crates/dpp-vc/src/jose/verify.rs b/crates/dpp-vc/src/jose/verify.rs index 1e319b5e..9466a0af 100644 --- a/crates/dpp-vc/src/jose/verify.rs +++ b/crates/dpp-vc/src/jose/verify.rs @@ -57,15 +57,15 @@ pub(crate) const PRESENTATION_CTY: &str = "vp"; /// /// # Time /// -/// `options` carries `now`, seconds since the Unix epoch, supplied rather than read, as in -/// [`sd_jwt_vc::verify`](crate::sd_jwt_vc::verify): a result that depends on a -/// hidden clock cannot be reproduced. +/// `options` carries `now`, seconds since the Unix epoch, supplied rather than read, and a +/// leeway for clock skew, as in [`sd_jwt_vc::verify`](crate::sd_jwt_vc::verify): a result that +/// depends on a hidden clock cannot be reproduced. Leeway defaults to zero and is capped at +/// [`super::MAX_LEEWAY_SECONDS`]. /// /// - **A `now`**: `exp`, if present, must be a JSON number and `now` must be /// before it (RFC 7519 §4.1.4); `nbf`, if present, must be a JSON number and /// `now` must not be before it (RFC 7519 §4.1.5). A value that is not a number is -/// refused, not skipped. There is no leeway: the comparison is exact, as in -/// `sd_jwt_vc::verify`. +/// refused, not skipped. The configured leeway is applied alike to both claims. /// - **No `now`**: no check of `exp` or `nbf`, and not their type either. /// /// # Audience @@ -200,7 +200,7 @@ pub(crate) fn claims_of( } } if let Some(now) = options.now { - check_time(&payload, now)?; + check_time(&payload, now, options.leeway().as_secs_f64())?; } check_audience(&payload, options.audience)?; Ok(payload) @@ -252,7 +252,7 @@ pub(crate) fn check_temporal_claims(payload: &Map) -> Result<(), /// `sd_jwt_vc::verify` makes: skipping an `exp` that does not parse would turn it /// into an absent `exp`, which is the unbounded case. A NumericDate may be /// fractional (RFC 7519 §2), so the claim is read as a number and compared as one. -fn check_time(payload: &Map, now: i64) -> Result<(), JoseError> { +fn check_time(payload: &Map, now: i64, leeway: f64) -> Result<(), JoseError> { // Exact for every instant a NumericDate can sensibly name; an `i64` that does // not fit an `f64`'s 53 bits is far past the year 285 million. let now = now as f64; @@ -260,18 +260,23 @@ fn check_time(payload: &Map, now: i64) -> Result<(), JoseError> { let Some(seconds) = numeric_date(payload, claim)? else { continue; }; - check_instant(claim, seconds, now)?; + check_instant(claim, seconds, now, leeway)?; } Ok(()) } /// One time claim against `now`: `exp` of `seconds` has been reached when `now` is not before /// it (RFC 7519 §4.1.4), and `nbf` of `seconds` has not been when `now` is before it (§4.1.5). -/// Any other claim name passes. Exact, with no leeway. -pub(crate) fn check_instant(claim: &str, seconds: f64, now: f64) -> Result<(), JoseError> { +/// `leeway` is applied in either direction. Any other claim name passes. +pub(crate) fn check_instant( + claim: &str, + seconds: f64, + now: f64, + leeway: f64, +) -> Result<(), JoseError> { match claim { - "exp" if now >= seconds => Err(JoseError::Expired), - "nbf" if now < seconds => Err(JoseError::NotYetValid), + "exp" if now >= seconds && now - seconds >= leeway => Err(JoseError::Expired), + "nbf" if now < seconds && seconds - now > leeway => Err(JoseError::NotYetValid), _ => Ok(()), } } @@ -281,7 +286,10 @@ pub(crate) fn check_instant(claim: &str, seconds: f64, now: f64) -> Result<(), J /// string, or an array of strings of which one is equal to it, compared exactly. An `aud` /// of any other shape is refused first, so a `null` or a number cannot read as no `aud`, /// and an array with one entry that is not a string is refused whatever else it holds. -fn check_audience(payload: &Map, audience: Option<&str>) -> Result<(), JoseError> { +pub(crate) fn check_audience( + payload: &Map, + audience: Option<&str>, +) -> Result<(), JoseError> { let Some(aud) = payload.get("aud") else { return Ok(()); }; diff --git a/crates/dpp-vc/src/sd_jwt_vc/error.rs b/crates/dpp-vc/src/sd_jwt_vc/error.rs index cf7246b8..b882327f 100644 --- a/crates/dpp-vc/src/sd_jwt_vc/error.rs +++ b/crates/dpp-vc/src/sd_jwt_vc/error.rs @@ -30,6 +30,9 @@ pub enum SdJwtVcError { /// The disclosure mechanism rejected the token. #[error(transparent)] SdJwt(#[from] SdJwtError), + /// The credential's `aud` does not name the caller, or is not a string or array of strings. + #[error(transparent)] + Audience(#[from] crate::jose::JoseError), /// `typ` is absent or is not [`TYP`]. #[error("typ is '{0}', expected '{TYP}'")] WrongTyp(String), diff --git a/crates/dpp-vc/src/sd_jwt_vc/tests/algorithm.rs b/crates/dpp-vc/src/sd_jwt_vc/tests/algorithm.rs index 1d50723b..f5e523e9 100644 --- a/crates/dpp-vc/src/sd_jwt_vc/tests/algorithm.rs +++ b/crates/dpp-vc/src/sd_jwt_vc/tests/algorithm.rs @@ -148,6 +148,7 @@ fn every_issuer_and_holder_algorithm_pair_issues_binds_and_verifies() { &vct(), now(), Some(&key_binding_policy()), + VerifyOptions::new(), ) .unwrap_or_else(|e| panic!("{label}: a bound presentation must verify, got {e:?}")); @@ -197,7 +198,8 @@ fn a_presentation_for_another_audience_is_refused_for_every_pair() { &public_key(store), &vct(), now(), - Some(&key_binding_policy()) + Some(&key_binding_policy()), + VerifyOptions::new(), ) .is_ok(), "{label}: control: the presentation verifies for its own audience" @@ -208,7 +210,8 @@ fn a_presentation_for_another_audience_is_refused_for_every_pair() { &public_key(store), &vct(), now(), - Some(&elsewhere) + Some(&elsewhere), + VerifyOptions::new(), ), Err(SdJwtVcError::SdJwt(SdJwtError::KeyBindingRejected("aud"))), "{label}: a Key Binding JWT for another audience is refused" @@ -256,7 +259,15 @@ fn an_ec_issuer_key_is_published_under_the_kid_its_credentials_name() { assert_eq!(jwk["use"], "sig", "{alg}: use"); let key = PublicKey::from_jwk(jwk).expect("the published key reads back"); - verify(&credential.serialise(), &key, &vct(), now(), None).unwrap_or_else(|e| { + verify( + &credential.serialise(), + &key, + &vct(), + now(), + None, + VerifyOptions::new(), + ) + .unwrap_or_else(|e| { panic!( "{alg}: a verifier holding the published key must accept the credential, got {e:?}" ) @@ -291,7 +302,15 @@ fn a_rotation_to_an_ec_key_keeps_every_credential_verifiable() { resolved, "{name}: the key a credential issued {when} the rotation resolves to" ); - verify(&credential.serialise(), &key, &vct(), now(), None).unwrap_or_else(|e| { + verify( + &credential.serialise(), + &key, + &vct(), + now(), + None, + VerifyOptions::new(), + ) + .unwrap_or_else(|e| { panic!("{name}: a credential issued {when} the rotation must verify, got {e:?}") }); } @@ -323,7 +342,15 @@ fn credentials_issued_while_the_key_rotates_verify_under_the_metadata_published_ let kid = kid_of(credential.jwt()); let key = PublicKey::from_jwk(published_jwk(&metadata, &kid)) .expect("the published key reads back"); - verify(&credential.serialise(), &key, &vct(), now(), None).unwrap_or_else(|e| { + verify( + &credential.serialise(), + &key, + &vct(), + now(), + None, + VerifyOptions::new(), + ) + .unwrap_or_else(|e| { panic!( "credential {i} of {} names {kid} and does not verify under it: {e:?}", credentials.len() diff --git a/crates/dpp-vc/src/sd_jwt_vc/tests/claim_path.rs b/crates/dpp-vc/src/sd_jwt_vc/tests/claim_path.rs index 06af7885..1adbd044 100644 --- a/crates/dpp-vc/src/sd_jwt_vc/tests/claim_path.rs +++ b/crates/dpp-vc/src/sd_jwt_vc/tests/claim_path.rs @@ -28,6 +28,7 @@ fn presented(store: &KeyStore, credential: &SdJwt, chosen: &[String]) -> Map, +) -> Result<(), SdJwtVcError> { + check_with_options(store, credential, at, VerifyOptions::new()) +} + +pub(super) fn check_with_options( + store: &KeyStore, + credential: &str, + at: DateTime, + options: VerifyOptions<'_>, ) -> Result<(), SdJwtVcError> { verify( credential, @@ -126,6 +136,7 @@ pub(super) fn check( &vct_for(ProductGroup::Battery, SCHEMA_VERSION), at, None, + options, ) .map(|_| ()) } diff --git a/crates/dpp-vc/src/sd_jwt_vc/tests/expiry.rs b/crates/dpp-vc/src/sd_jwt_vc/tests/expiry.rs index 088ab131..4a1b272f 100644 --- a/crates/dpp-vc/src/sd_jwt_vc/tests/expiry.rs +++ b/crates/dpp-vc/src/sd_jwt_vc/tests/expiry.rs @@ -68,6 +68,7 @@ fn verified( &vct_for(ProductGroup::Battery, SCHEMA_VERSION), instant, None, + VerifyOptions::new(), ) } diff --git a/crates/dpp-vc/src/sd_jwt_vc/tests/key_binding.rs b/crates/dpp-vc/src/sd_jwt_vc/tests/key_binding.rs index dd45d180..5752a43f 100644 --- a/crates/dpp-vc/src/sd_jwt_vc/tests/key_binding.rs +++ b/crates/dpp-vc/src/sd_jwt_vc/tests/key_binding.rs @@ -72,7 +72,14 @@ fn verify_as( store: &KeyStore, policy: Option<&KeyBindingPolicy>, ) -> Result, SdJwtVcError> { - verify(token, &public_key(store), &vct(), now(), policy) + verify( + token, + &public_key(store), + &vct(), + now(), + policy, + VerifyOptions::new(), + ) } /// The JWT's payload as signed, without processing any Disclosure. diff --git a/crates/dpp-vc/src/sd_jwt_vc/tests/passport_claim.rs b/crates/dpp-vc/src/sd_jwt_vc/tests/passport_claim.rs index 7f78bf40..19ef4b22 100644 --- a/crates/dpp-vc/src/sd_jwt_vc/tests/passport_claim.rs +++ b/crates/dpp-vc/src/sd_jwt_vc/tests/passport_claim.rs @@ -147,6 +147,7 @@ fn a_passport_member_named_like_a_registered_claim_stays_in_the_passport() { &vct_for(ProductGroup::Battery, SCHEMA_VERSION), now(), None, + VerifyOptions::new(), ) .expect("the credential's own claims are well-formed whatever the passport holds"); assert_eq!(claims["iss"], json!(ISSUER)); @@ -179,6 +180,7 @@ fn the_passports_own_status_is_not_the_credentials() { &vct_for(ProductGroup::Battery, SCHEMA_VERSION), now(), None, + VerifyOptions::new(), ) .expect("verifies"); assert!(claims.get("status").is_none()); diff --git a/crates/dpp-vc/src/sd_jwt_vc/tests/status.rs b/crates/dpp-vc/src/sd_jwt_vc/tests/status.rs index 8dc005d0..f1e29000 100644 --- a/crates/dpp-vc/src/sd_jwt_vc/tests/status.rs +++ b/crates/dpp-vc/src/sd_jwt_vc/tests/status.rs @@ -51,6 +51,7 @@ fn verified(store: &KeyStore, credential: &SdJwt) -> serde_json::Map>()) .expect("each chosen Disclosure is referenced") .serialise(); - let after = verify(&withheld, &public_key(&store), &vct, now(), None).expect("still verifies"); + let after = verify( + &withheld, + &public_key(&store), + &vct, + now(), + None, + VerifyOptions::new(), + ) + .expect("still verifies"); assert!( !after[PASSPORT_CLAIM]["productGroupData"] .as_object() @@ -229,7 +246,8 @@ fn tampering_with_a_revealed_value_refuses_the_credential() { &public_key(&store), &vct_for(ProductGroup::Battery, SCHEMA_VERSION), now(), - None + None, + VerifyOptions::new(), ), Err(SdJwtVcError::SdJwt(SdJwtError::UnusedDisclosures(1))) ); @@ -247,7 +265,8 @@ fn a_credential_signed_by_another_key_does_not_verify() { &public_key(&other), &vct_for(ProductGroup::Battery, SCHEMA_VERSION), now(), - None + None, + VerifyOptions::new(), ), Err(SdJwtVcError::BadSignature) ); @@ -275,7 +294,8 @@ fn a_mutated_signature_is_refused_before_the_claims_are_read() { &public_key(&store), &vct_for(ProductGroup::Battery, SCHEMA_VERSION), now(), - None + None, + VerifyOptions::new(), ), Err(SdJwtVcError::BadSignature) ); @@ -292,6 +312,7 @@ fn a_credential_of_another_type_is_refused() { &vct_for(ProductGroup::Battery, "2.5.0"), now(), None, + VerifyOptions::new(), ) .unwrap_err(); @@ -317,3 +338,61 @@ fn two_issuances_of_one_passport_share_no_digest() { // And the signed tokens therefore differ too. assert_ne!(first.jwt(), second.jwt()); } + +#[test] +fn a_credential_for_another_audience_is_refused() { + let store = temp_store("sdjwtvc-audience", KEY_ID); + let credential = credential_with(&store, &[("aud", json!("https://other.example"))]); + + assert_eq!( + check_with_options( + &store, + &credential, + now(), + VerifyOptions::new().for_audience("https://verifier.example"), + ), + Err(SdJwtVcError::Audience( + crate::jose::JoseError::AudienceMismatch { + audience: Some("https://verifier.example".to_owned()) + } + )) + ); +} + +#[test] +fn the_audience_is_checked_only_when_the_credential_carries_it() { + let store = temp_store("sdjwtvc-audience-policy", KEY_ID); + let no_audience = issued(&store).serialise(); + let matching_audience = credential_with( + &store, + &[( + "aud", + json!(["https://other.example", "https://verifier.example"]), + )], + ); + let audience_without_verifier = + credential_with(&store, &[("aud", json!("https://verifier.example"))]); + let malformed_audience = credential_with(&store, &[("aud", json!(null))]); + + let with_verifier = VerifyOptions::new().for_audience("https://verifier.example"); + assert!(check_with_options(&store, &no_audience, now(), VerifyOptions::new()).is_ok()); + assert!(check_with_options(&store, &no_audience, now(), with_verifier).is_ok()); + assert!(check_with_options(&store, &matching_audience, now(), with_verifier).is_ok()); + assert_eq!( + check_with_options( + &store, + &audience_without_verifier, + now(), + VerifyOptions::new(), + ), + Err(SdJwtVcError::Audience( + crate::jose::JoseError::AudienceMismatch { audience: None } + )) + ); + assert_eq!( + check_with_options(&store, &malformed_audience, now(), with_verifier), + Err(SdJwtVcError::Audience( + crate::jose::JoseError::MalformedAudience + )) + ); +} diff --git a/crates/dpp-vc/src/sd_jwt_vc/verify.rs b/crates/dpp-vc/src/sd_jwt_vc/verify.rs index f7c8dba1..812fddca 100644 --- a/crates/dpp-vc/src/sd_jwt_vc/verify.rs +++ b/crates/dpp-vc/src/sd_jwt_vc/verify.rs @@ -1,6 +1,6 @@ //! Verification — signature first, then the profile's claims, then disclosures. -use chrono::{DateTime, Utc}; +use chrono::{DateTime, Duration, Utc}; use serde_json::{Map, Value}; use dpp_crypto::sd_jwt::{KeyBindingPolicy, SdJwt}; @@ -10,6 +10,7 @@ use crate::token_status_list::StatusReference; use super::TYP; use super::error::SdJwtVcError; +use crate::jose::{VerifyOptions, check_audience}; /// The temporal claims of draft-ietf-oauth-sd-jwt-vc-19 clause 2.2.2, each /// OPTIONAL, each a JWT `NumericDate` (RFC 7519 clause 2) when present. @@ -40,8 +41,8 @@ const NEVER_DISCLOSED: [&str; 8] = [ /// disclosure mechanism, which refuses any disclosure that matches nothing; Key /// Binding, as `key_binding` asks; that no claim clause 2.2.2.3 keeps out of /// Disclosures arrived in one; that a `status`, if present, is an object and any -/// `status_list` in it is an index and a URI; the presence of `iss` and `vct`; `vct` -/// against what the caller expected; and the validity window. +/// `status_list` in it is an index and a URI; the presence of `iss` and `vct`; `vct` against +/// what the caller expected; `aud` against the audience in `options`; and the validity window. /// /// **The status itself is not looked up.** That needs the list, which is fetched. /// Read the reference with @@ -77,6 +78,10 @@ const NEVER_DISCLOSED: [&str; 8] = [ /// an expiry test that cannot be written for a fixed instant does not get /// written. /// +/// `options` supplies the same bounded clock-skew leeway as the JOSE verifiers. +/// It defaults to zero and is applied equally to `exp` and `nbf`. +/// The `aud` claim follows the same audience rule as the JOSE verifiers. +/// /// `nbf` and `exp` are OPTIONAL in the profile, so their absence is valid and /// means "no bound". Present and passed, or present and not yet reached, is a /// refusal — otherwise a signed credential replays for ever, which is the whole @@ -94,6 +99,7 @@ pub fn verify( expected_vct: &str, now: DateTime, key_binding: Option<&KeyBindingPolicy>, + options: VerifyOptions<'_>, ) -> Result, SdJwtVcError> { let sd_jwt = SdJwt::parse(serialised)?; @@ -153,7 +159,8 @@ pub fn verify( }); } - check_validity_window(&payload, now)?; + check_audience(&payload, options.audience)?; + check_validity_window(&payload, now, options.leeway())?; Ok(payload) } @@ -167,7 +174,13 @@ pub fn verify( fn check_validity_window( payload: &Map, now: DateTime, + leeway: std::time::Duration, ) -> Result<(), SdJwtVcError> { + #[expect( + clippy::cast_possible_wrap, + reason = "VerifyOptions bounds leeway to 300 seconds" + )] + let leeway = Duration::seconds(leeway.as_secs() as i64); for claim in TEMPORAL_CLAIMS { let Some(value) = payload.get(claim) else { continue; @@ -200,8 +213,12 @@ fn check_validity_window( return Err(SdJwtVcError::MalformedTemporalClaim(claim)); }; match claim { - "exp" if now >= instant => return Err(SdJwtVcError::Expired { at: instant }), - "nbf" if now < instant => return Err(SdJwtVcError::NotYetValid { from: instant }), + "exp" if now >= instant && now.signed_duration_since(instant) >= leeway => { + return Err(SdJwtVcError::Expired { at: instant }); + } + "nbf" if now < instant && instant.signed_duration_since(now) > leeway => { + return Err(SdJwtVcError::NotYetValid { from: instant }); + } _ => {} } }