identity_kit/resolver/jwt.rs
1//! `JwtValidator`: validation of a JWT that is not a credential or a presentation.
2
3use core::fmt;
4use core::time::Duration;
5use std::collections::BTreeSet;
6use std::time::{SystemTime, UNIX_EPOCH};
7
8use serde::de::DeserializeOwned;
9
10use super::{
11 JwsKeyError, KeyReference, KeyReferenceError, KeyResolutionError, KeyResolver, KeyRole,
12 resolve_jws_key,
13};
14use crate::jose::{
15 CompactJws, DefaultVerifier, Jwk, JwsAlgorithm, JwsError, JwsHeader, JwsVerifier, JwtClaims,
16 OneOrMany, VerificationError,
17};
18
19/// Validates a compact JWT that is neither a credential nor a presentation: an OAuth 2.0 access
20/// token (RFC 9068), an ID token, a request object.
21///
22/// The checks follow RFC 7519 §7.2 and the best current practices of RFC 8725, in this order:
23///
24/// 1. The token is a compact JWS ([`CompactJws::decode`]), whose `alg` is one the options allow
25/// (RFC 8725 §3.1) and whose header `typ` is the one the options expect, if they expect one
26/// (RFC 8725 §3.11). `typ` is compared as RFC 7515 §4.1.9 says: ignoring case and an
27/// `application/` prefix.
28/// 2. The payload is a JSON claims set.
29/// 3. The key the header names ([`KeyReference::candidates`], with the `iss` of the claims,
30/// the first of them the resolver handles) is resolved for the [`KeyRole`] of the options
31/// at the validation time and verifies the signature.
32/// 4. Under [`IssuerBinding::KeyOfIssuer`], the default, the key belongs to `iss`
33/// ([`KeyReference::binds_to`]): `iss` is the DID of a `kid` DID URL, the HTTPS issuer of a
34/// key set, the `did:jwk` or thumbprint of a key by value, or, for an `x5c` certificate
35/// chain, absent or named by the first certificate.
36/// 5. `iss` is the expected issuer, and `aud` includes the expected audience, when the options
37/// name them.
38/// 6. `exp`, `nbf` and `iat` hold at the validation time, within the leeway.
39/// 7. Every claim the options require is present.
40///
41/// What else a token must say (a `scope`, a `client_id`, a `nonce`) is the application's to
42/// check, on the claims it gets back. Explicit typing is what keeps one kind of JWT from being
43/// accepted as another (RFC 8725 §3.11); name the `typ` whenever the token has one.
44///
45/// # Examples
46///
47/// An authorization server signs an access token with the Ed25519 key of RFC 8037 Appendix
48/// A.1, naming it by a DID URL while its `iss` is its HTTPS URL. The resource server pins that
49/// one key: its resolver knows no other, so the key need not belong to `iss`. A resolver that
50/// returns any key a token carries, such as [`JwkResolver`](super::JwkResolver), must never be
51/// combined with [`IssuerBinding::Any`]: anyone could sign with their own key.
52///
53/// ```
54/// use identity_kit::jose::{DefaultVerifier, Jwk, JwsAlgorithm, JwsHeader, JwtClaims, SignError, Signer, encode_compact};
55/// use identity_kit::resolver::{
56/// IssuerBinding, JwtValidationError, JwtValidationOptions, JwtValidator, KeyReference,
57/// KeyResolutionError, KeyResolver, KeyRole,
58/// };
59///
60/// struct Server(ed25519_dalek::SigningKey);
61///
62/// #[async_trait::async_trait]
63/// impl Signer for Server {
64/// fn alg(&self) -> JwsAlgorithm { JwsAlgorithm::EdDSA }
65/// fn kid(&self) -> Option<&str> { None }
66/// async fn sign(&self, input: &[u8]) -> Result<Vec<u8>, SignError> {
67/// use ed25519_dalek::Signer as _;
68/// Ok(self.0.sign(input).to_bytes().to_vec())
69/// }
70/// }
71///
72/// /// The authorization server's one key, under the one DID URL it signs with.
73/// struct Pinned(Jwk);
74///
75/// #[async_trait::async_trait]
76/// impl KeyResolver for Pinned {
77/// async fn resolve_key(&self, key: &KeyReference, _: KeyRole) -> Result<Jwk, KeyResolutionError> {
78/// match key {
79/// KeyReference::DidUrl(url) if url.as_str() == "did:example:as#key-1" => Ok(self.0.clone()),
80/// other => Err(KeyResolutionError::unsupported(other)),
81/// }
82/// }
83/// }
84///
85/// # tokio::runtime::Builder::new_current_thread().build()?.block_on(async {
86/// let secret = [
87/// 0x9d, 0x61, 0xb1, 0x9d, 0xef, 0xfd, 0x5a, 0x60, 0xba, 0x84, 0x4a, 0xf4, 0x92, 0xec, 0x2c, 0xc4,
88/// 0x44, 0x49, 0xc5, 0x69, 0x7b, 0x32, 0x69, 0x19, 0x70, 0x3b, 0xac, 0x03, 0x1c, 0xae, 0x7f, 0x60,
89/// ];
90/// let server = Server(ed25519_dalek::SigningKey::from_bytes(&secret));
91/// let key = Jwk::from_ed25519_public(server.0.verifying_key().as_bytes())?;
92///
93/// let header = JwsHeader::new(JwsAlgorithm::EdDSA)
94/// .with_typ("at+jwt")
95/// .with_kid("did:example:as#key-1");
96/// let mut claims = JwtClaims::new()
97/// .with_iss("https://as.example.com")
98/// .with_sub("5ba552d67")
99/// .with_aud("https://rs.example.com")
100/// .with_jti("dbe39bf3a3ba4238a513f51d6e1691c4")
101/// .with_claim("client_id", "s6BhdRkqt3")
102/// .with_claim("scope", "openid profile");
103/// claims.iat = Some(1_700_000_000);
104/// claims.exp = Some(1_700_003_600);
105/// let token = encode_compact(&header, &serde_json::to_vec(&claims)?, &server).await?;
106///
107/// // The key is the pinned one, not the DID of `iss`, so the binding is waived.
108/// let validator = JwtValidator::new(Pinned(key.clone()), DefaultVerifier);
109/// let options = JwtValidationOptions::new()
110/// .with_typ("at+jwt")
111/// .with_algorithm(JwsAlgorithm::EdDSA)
112/// .with_issuer("https://as.example.com")
113/// .with_audience("https://rs.example.com")
114/// .with_issuer_binding(IssuerBinding::Any)
115/// .with_required_claims(["exp", "iat", "jti", "sub", "client_id"])
116/// .at(1_700_000_100);
117/// let validated = validator.validate(&token, &options).await?;
118/// assert_eq!(validated.claims.sub.as_deref(), Some("5ba552d67"));
119/// assert_eq!(validated.key, key);
120///
121/// // A token naming any other key is refused.
122/// let forged = encode_compact(
123/// &JwsHeader::new(JwsAlgorithm::EdDSA).with_typ("at+jwt").with_kid("did:example:attacker#key-1"),
124/// &serde_json::to_vec(&claims)?,
125/// &server,
126/// )
127/// .await?;
128/// let error = validator.validate(&forged, &options).await.unwrap_err();
129/// assert!(matches!(error, JwtValidationError::KeyResolution { .. }));
130///
131/// // An hour and a minute later it has expired.
132/// let error = validator.validate(&token, &options.at(1_700_003_660)).await.unwrap_err();
133/// assert!(matches!(error, JwtValidationError::Expired { expired_at: 1_700_003_600, .. }));
134/// # Ok::<(), Box<dyn std::error::Error>>(())
135/// # })?;
136/// # Ok::<(), Box<dyn std::error::Error>>(())
137/// ```
138pub struct JwtValidator<R, V = DefaultVerifier> {
139 resolver: R,
140 verifier: V,
141}
142
143impl<R: KeyResolver, V: JwsVerifier> JwtValidator<R, V> {
144 /// A validator resolving keys with `resolver` and verifying signatures with `verifier`.
145 pub fn new(resolver: R, verifier: V) -> Self {
146 Self { resolver, verifier }
147 }
148
149 /// The key resolver.
150 pub fn resolver(&self) -> &R {
151 &self.resolver
152 }
153
154 /// The signature verifier.
155 pub fn verifier(&self) -> &V {
156 &self.verifier
157 }
158
159 /// Validates `token`, returning its claims as a [`JwtClaims`] set.
160 ///
161 /// # Errors
162 ///
163 /// The first [`JwtValidationError`] found, in the order [`JwtValidator`] lists the checks.
164 pub async fn validate(
165 &self,
166 token: &str,
167 options: &JwtValidationOptions,
168 ) -> Result<ValidatedJwt, JwtValidationError> {
169 self.validate_as(token, options).await
170 }
171
172 /// Validates `token`, returning its claims read into `T`, once the registered claims have
173 /// been checked.
174 ///
175 /// # Errors
176 ///
177 /// As [`validate`](Self::validate), and [`JwtValidationError::Claims`] when the payload
178 /// does not fit `T`.
179 pub async fn validate_as<T: DeserializeOwned>(
180 &self,
181 token: &str,
182 options: &JwtValidationOptions,
183 ) -> Result<ValidatedJwt<T>, JwtValidationError> {
184 let jws = CompactJws::decode(token)?;
185 let header = jws.header();
186 if !options.allows(header.alg) {
187 return Err(JwtValidationError::DisallowedAlgorithm(header.alg));
188 }
189 if let Some(expected) = &options.typ
190 && !header
191 .typ
192 .as_deref()
193 .is_some_and(|typ| same_typ(typ, expected))
194 {
195 return Err(JwtValidationError::UnexpectedTyp {
196 expected: expected.clone(),
197 found: header.typ.clone(),
198 });
199 }
200 let claims: JwtClaims =
201 serde_json::from_slice(jws.payload()).map_err(JwtValidationError::Payload)?;
202
203 // One validation time for the key and for the claims.
204 let now = options.now();
205 let (reference, key) = resolve_jws_key(
206 &self.resolver,
207 &jws,
208 claims.iss.as_deref(),
209 options.role,
210 now,
211 )
212 .await
213 .map_err(|error| match error {
214 JwsKeyError::Reference(error) => JwtValidationError::KeyReference(error),
215 JwsKeyError::Resolution { key, source } => {
216 JwtValidationError::KeyResolution { key, source }
217 }
218 })?;
219 jws.verify(&self.verifier, &key)?;
220 if options.issuer_binding == IssuerBinding::KeyOfIssuer
221 && !reference.binds_to(claims.iss.as_deref(), &key)
222 {
223 return Err(JwtValidationError::KeyNotIssuers {
224 issuer: claims.iss.clone(),
225 key: Box::new(reference),
226 });
227 }
228
229 if let Some(expected) = &options.issuer
230 && claims.iss.as_ref() != Some(expected)
231 {
232 return Err(JwtValidationError::IssuerMismatch {
233 expected: expected.clone(),
234 found: claims.iss.clone(),
235 });
236 }
237 if let Some(expected) = &options.audience
238 && !claims.audiences().any(|audience| audience == expected)
239 {
240 return Err(JwtValidationError::AudienceMismatch {
241 expected: expected.clone(),
242 found: claims.aud.clone(),
243 });
244 }
245 options.check_times(&claims, now)?;
246 for claim in &options.required_claims {
247 if !has_claim(&claims, claim) {
248 return Err(JwtValidationError::MissingClaim(claim.clone()));
249 }
250 }
251
252 let typed = serde_json::from_slice(jws.payload()).map_err(JwtValidationError::Claims)?;
253 Ok(ValidatedJwt {
254 header: header.clone(),
255 claims: typed,
256 key,
257 key_reference: reference,
258 })
259 }
260}
261
262impl<R: fmt::Debug, V: fmt::Debug> fmt::Debug for JwtValidator<R, V> {
263 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
264 f.debug_struct("JwtValidator")
265 .field("resolver", &self.resolver)
266 .field("verifier", &self.verifier)
267 .finish()
268 }
269}
270
271/// Whether the header `typ` `found` is the media type `expected`: compared ignoring ASCII case,
272/// with an `application/` prefix on either side optional (RFC 7515 §4.1.9).
273fn same_typ(found: &str, expected: &str) -> bool {
274 fn bare(typ: &str) -> &str {
275 match typ.get(..12) {
276 Some(prefix) if prefix.eq_ignore_ascii_case("application/") => &typ[12..],
277 _ => typ,
278 }
279 }
280 bare(found).eq_ignore_ascii_case(bare(expected))
281}
282
283/// Whether `claims` has the claim `name`, registered or not.
284fn has_claim(claims: &JwtClaims, name: &str) -> bool {
285 match name {
286 "iss" => claims.iss.is_some(),
287 "sub" => claims.sub.is_some(),
288 "aud" => claims.aud.is_some(),
289 "exp" => claims.exp.is_some(),
290 "nbf" => claims.nbf.is_some(),
291 "iat" => claims.iat.is_some(),
292 "jti" => claims.jti.is_some(),
293 other => claims.additional.contains_key(other),
294 }
295}
296
297/// A JWT that passed [`JwtValidator::validate`]: its header, its claims and the key that signed
298/// it.
299#[derive(Debug, Clone)]
300#[non_exhaustive]
301pub struct ValidatedJwt<T = JwtClaims> {
302 /// The JWS header.
303 pub header: JwsHeader,
304 /// The claims, as a [`JwtClaims`] set or the type [`JwtValidator::validate_as`] read them
305 /// into.
306 pub claims: T,
307 /// The public key that verified the signature.
308 pub key: Jwk,
309 /// Where the header said the key was.
310 pub key_reference: KeyReference,
311}
312
313/// Whether the key that signed a token must belong to its issuer.
314#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
315#[non_exhaustive]
316pub enum IssuerBinding {
317 /// The key must belong to `iss` ([`KeyReference::binds_to`]): a `kid` DID URL of the DID
318 /// `iss`, a key of the key set of the HTTPS `iss`, a key by value whose `did:jwk` or
319 /// thumbprint is `iss`, or which comes with no `iss` at all, or the key of a certificate
320 /// chain whose first certificate names `iss`, or which comes with no `iss`.
321 #[default]
322 KeyOfIssuer,
323 /// Any key the [`KeyResolver`] resolves is accepted, whatever `iss` says: for a resolver
324 /// that only resolves keys the application trusts, such as an authorization server's
325 /// signing keys behind a `kid` that is a DID URL of a DID other than its `iss` URL.
326 ///
327 /// Never with a resolver that returns a key the token itself carries, such as
328 /// [`JwkResolver`](super::JwkResolver) for a `jwk` header, or one that resolves any DID:
329 /// the issuer binding is then the only thing tying the key to `iss`, and without it anyone
330 /// can sign a token with their own key. The same holds for `X509Resolver`: without the
331 /// binding, anyone holding a certificate under one of its trust anchors can sign a token
332 /// with any `iss`.
333 Any,
334}
335
336/// Options of [`JwtValidator`]: what the token must be, and when.
337///
338/// The default accepts every algorithm the crate verifies, any `typ`, any issuer and audience,
339/// with the key bound to `iss`, at the current time without leeway, and requires no claim.
340#[derive(Debug, Clone, Default, PartialEq, Eq)]
341#[non_exhaustive]
342pub struct JwtValidationOptions {
343 /// The algorithms accepted; every algorithm when empty.
344 pub algorithms: BTreeSet<JwsAlgorithm>,
345 /// The header `typ` the token must have, if any.
346 pub typ: Option<String>,
347 /// The `iss` the token must have, if any.
348 pub issuer: Option<String>,
349 /// The audience the token's `aud` must include, if any.
350 pub audience: Option<String>,
351 /// The role the signing key is resolved for: [`KeyRole::Issuer`] (`assertionMethod` in a
352 /// DID document) by default, [`KeyRole::Subject`] (`authentication`) for a token that
353 /// proves possession.
354 pub role: KeyRole,
355 /// Whether the signing key must belong to `iss`.
356 pub issuer_binding: IssuerBinding,
357 /// Claims that must be present, registered or not.
358 pub required_claims: BTreeSet<String>,
359 /// The validation time in seconds since the Unix epoch; the current time when `None`.
360 pub now: Option<i64>,
361 /// How far `exp`, `nbf` and `iat` may miss the validation time and still pass.
362 pub leeway: Duration,
363}
364
365impl JwtValidationOptions {
366 /// The default options.
367 pub fn new() -> Self {
368 Self::default()
369 }
370
371 /// These options also accepting `alg`. Once one algorithm is named, only the named ones
372 /// are accepted.
373 #[must_use]
374 pub fn with_algorithm(mut self, alg: JwsAlgorithm) -> Self {
375 self.algorithms.insert(alg);
376 self
377 }
378
379 /// These options requiring the header `typ` to be `typ`.
380 #[must_use]
381 pub fn with_typ(mut self, typ: impl Into<String>) -> Self {
382 self.typ = Some(typ.into());
383 self
384 }
385
386 /// These options requiring `iss` to be `issuer`.
387 #[must_use]
388 pub fn with_issuer(mut self, issuer: impl Into<String>) -> Self {
389 self.issuer = Some(issuer.into());
390 self
391 }
392
393 /// These options requiring `aud` to include `audience`.
394 #[must_use]
395 pub fn with_audience(mut self, audience: impl Into<String>) -> Self {
396 self.audience = Some(audience.into());
397 self
398 }
399
400 /// These options resolving the signing key for `role`.
401 #[must_use]
402 pub fn with_role(mut self, role: KeyRole) -> Self {
403 self.role = role;
404 self
405 }
406
407 /// These options with `binding`.
408 #[must_use]
409 pub fn with_issuer_binding(mut self, binding: IssuerBinding) -> Self {
410 self.issuer_binding = binding;
411 self
412 }
413
414 /// These options also requiring every claim of `claims`.
415 #[must_use]
416 pub fn with_required_claims<I, S>(mut self, claims: I) -> Self
417 where
418 I: IntoIterator<Item = S>,
419 S: Into<String>,
420 {
421 self.required_claims
422 .extend(claims.into_iter().map(Into::into));
423 self
424 }
425
426 /// These options validating at `now`, in seconds since the Unix epoch.
427 #[must_use]
428 pub fn at(mut self, now: i64) -> Self {
429 self.now = Some(now);
430 self
431 }
432
433 /// These options with `leeway`.
434 #[must_use]
435 pub fn with_leeway(mut self, leeway: Duration) -> Self {
436 self.leeway = leeway;
437 self
438 }
439
440 /// The validation time, in seconds since the Unix epoch.
441 pub fn now(&self) -> i64 {
442 self.now.unwrap_or_else(|| {
443 let since_epoch = SystemTime::now()
444 .duration_since(UNIX_EPOCH)
445 .unwrap_or(Duration::ZERO);
446 i64::try_from(since_epoch.as_secs()).unwrap_or(i64::MAX)
447 })
448 }
449
450 /// Whether `alg` is accepted.
451 fn allows(&self, alg: JwsAlgorithm) -> bool {
452 self.algorithms.is_empty() || self.algorithms.contains(&alg)
453 }
454
455 /// Checks `exp`, `nbf` and `iat` at `now`, within the leeway.
456 fn check_times(&self, claims: &JwtClaims, now: i64) -> Result<(), JwtValidationError> {
457 let leeway = i64::try_from(self.leeway.as_secs()).unwrap_or(i64::MAX);
458 let latest = now.saturating_add(leeway);
459 let earliest = now.saturating_sub(leeway);
460 if let Some(expired_at) = claims.exp
461 && expired_at <= earliest
462 {
463 return Err(JwtValidationError::Expired { expired_at, now });
464 }
465 if let Some(not_before) = claims.nbf
466 && not_before > latest
467 {
468 return Err(JwtValidationError::NotYetValid { not_before, now });
469 }
470 if let Some(issued_at) = claims.iat
471 && issued_at > latest
472 {
473 return Err(JwtValidationError::IssuedInFuture { issued_at, now });
474 }
475 Ok(())
476 }
477}
478
479/// Why a JWT did not pass [`JwtValidator::validate`].
480///
481/// Times are `NumericDate` seconds since the Unix epoch.
482#[derive(Debug, thiserror::Error)]
483#[non_exhaustive]
484pub enum JwtValidationError {
485 /// The token is not a compact JWS this crate decodes.
486 #[error("invalid JWS: {0}")]
487 Jws(#[from] JwsError),
488 /// The header `alg` is not one the options accept.
489 #[error("algorithm `{0}` is not accepted")]
490 DisallowedAlgorithm(JwsAlgorithm),
491 /// The header `typ` is not the one the options require, or is missing.
492 #[error("header `typ` is {found:?}, not `{expected}`")]
493 UnexpectedTyp {
494 /// The `typ` required.
495 expected: String,
496 /// The `typ` found.
497 found: Option<String>,
498 },
499 /// The payload is not a JSON claims set; the source is the JSON error.
500 #[error("the payload is not a JWT claims set: {0}")]
501 Payload(#[source] serde_json::Error),
502 /// The header names no key this crate can look for.
503 #[error(transparent)]
504 KeyReference(#[from] KeyReferenceError),
505 /// The key the token names could not be resolved.
506 #[error("resolving key {key}: {source}")]
507 KeyResolution {
508 /// Where the token says its key is.
509 key: Box<KeyReference>,
510 /// What went wrong.
511 #[source]
512 source: KeyResolutionError,
513 },
514 /// The signature does not verify under the resolved key.
515 #[error("signature: {0}")]
516 Signature(#[from] VerificationError),
517 /// The key that signed the token does not belong to its `iss`.
518 #[error("signing key {key} does not belong to issuer {issuer:?}")]
519 KeyNotIssuers {
520 /// The `iss`, if the token has one.
521 issuer: Option<String>,
522 /// Where the token says its key is.
523 key: Box<KeyReference>,
524 },
525 /// `iss` is not the expected issuer.
526 #[error("issuer {found:?} is not {expected:?}")]
527 IssuerMismatch {
528 /// The issuer expected.
529 expected: String,
530 /// The `iss` found.
531 found: Option<String>,
532 },
533 /// `aud` does not include the expected audience.
534 #[error("audience {found:?} does not include {expected:?}")]
535 AudienceMismatch {
536 /// The audience expected.
537 expected: String,
538 /// The `aud` found.
539 found: Option<OneOrMany<String>>,
540 },
541 /// The token has expired.
542 #[error("expired at {expired_at} (now is {now})")]
543 Expired {
544 /// The `exp`.
545 expired_at: i64,
546 /// The validation time.
547 now: i64,
548 },
549 /// The token is not valid yet.
550 #[error("not valid before {not_before} (now is {now})")]
551 NotYetValid {
552 /// The `nbf`.
553 not_before: i64,
554 /// The validation time.
555 now: i64,
556 },
557 /// The token claims to have been issued in the future.
558 #[error("issued at {issued_at}, after now ({now})")]
559 IssuedInFuture {
560 /// The `iat`.
561 issued_at: i64,
562 /// The validation time.
563 now: i64,
564 },
565 /// A claim the options require is missing.
566 #[error("missing claim `{0}`")]
567 MissingClaim(String),
568 /// The claims do not fit the type [`JwtValidator::validate_as`] reads them into; the source
569 /// is the JSON error.
570 #[error("the claims do not fit the expected type: {0}")]
571 Claims(#[source] serde_json::Error),
572}