jose-rs 0.14.0

Pure-Rust JOSE library (JWS, JWE, JWK, JWT) with software and HSM key support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
//! JWT Validation configuration (RFC 7519).

use crate::algorithm::JwsAlgorithm;
use crate::error::{JoseError, Result};
use crate::header::JoseHeader;
use crate::jwt::claims::Claims;
use crate::jwt::NumericDate;
use std::time::{SystemTime, UNIX_EPOCH};

/// Validation configuration for JWT decoding.
///
/// Construct this via [`Validation::new`] or [`Default::default`]. The type is
/// non-exhaustive so future validation toggles can be added without another
/// semver break.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Validation {
    /// Required issuer. If set, `iss` claim must match.
    pub issuer: Option<String>,
    /// Required audience. If set, `aud` claim must contain this value.
    pub audience: Option<String>,
    /// Required subject. If set, `sub` claim must match.
    pub subject: Option<String>,
    /// Required `typ` header value (RFC 8725 §3.11). If set, the JWS
    /// protected header's `typ` field must equal this string.
    pub required_typ: Option<String>,
    /// Maximum acceptable age (seconds) between the `iat` claim and now.
    /// If set, `iat` is required and tokens older than this are rejected.
    pub max_age: Option<u64>,
    /// Allow-list of JwsAlgorithm values. If non-empty, the token's
    /// header `alg` must map to one of these. Empty means no restriction
    /// beyond the verifier-algorithm binding.
    /// `Ed25519`, `Ed448` and legacy `EdDSA` are distinct entries; the JWK pin
    /// aliases never broaden this application allowlist.
    pub allowed_algorithms: Vec<JwsAlgorithm>,
    /// Clock skew tolerance in seconds (default: 60).
    pub leeway: u64,
    /// Whether to validate `exp` claim (default: true).
    pub validate_exp: bool,
    /// Whether to validate `nbf` claim (default: true).
    pub validate_nbf: bool,
    /// Whether to reject tokens whose `iat` is in the future (default: true).
    pub validate_iat_not_future: bool,
    /// Whether to reject tokens that carry no `exp` claim (default: false).
    ///
    /// `exp` is optional in RFC 7519, so a token without it never expires.
    /// Enabling this closes that footgun by requiring the claim to be present.
    pub require_exp: bool,
    /// Whether to reject tokens that carry no `nbf` claim (default: false).
    pub require_nbf: bool,
    /// Whether to reject tokens that carry no `iat` claim (default: false).
    ///
    /// `with_max_age` enables this automatically because a max-age policy
    /// cannot be evaluated without an issued-at timestamp.
    pub require_iat: bool,
    /// Whether to reject tokens whose protected header carries no `kid`
    /// (default: false).
    ///
    /// Enable this for strict key pinning against a [`crate::jwk::JwkSet`].
    /// [`crate::jwt::decode_with_jwkset`] tries every key in the set for a
    /// kid-less token, so a token that names no key can be accepted under
    /// any key in the set. Requiring `kid` forces every token to name the
    /// key it was signed with before any verification is attempted.
    pub require_kid: bool,
}

impl Default for Validation {
    fn default() -> Self {
        Self {
            issuer: None,
            audience: None,
            subject: None,
            required_typ: None,
            max_age: None,
            allowed_algorithms: Vec::new(),
            leeway: 60,
            validate_exp: true,
            validate_nbf: true,
            validate_iat_not_future: true,
            require_exp: false,
            require_nbf: false,
            require_iat: false,
            require_kid: false,
        }
    }
}

impl Validation {
    /// Construct validation settings with secure defaults.
    pub fn new() -> Self {
        Self::default()
    }

    /// Verify signatures without checking `exp`, `nbf`, or future `iat`.
    ///
    /// This explicit opt-in accepts expired and not-yet-valid tokens. Required
    /// claims, issuer, audience, type and algorithm policy still apply when set.
    /// Defaults from [`Self::new`] continue to enforce all three time checks.
    pub fn signature_only() -> Self {
        Self::new()
            .without_exp()
            .without_nbf()
            .without_iat_future_check()
    }

    /// Disable expiration checking, accepting expired tokens. Required `exp`
    /// presence and any configured maximum age remain enforced.
    pub fn without_exp(mut self) -> Self {
        self.validate_exp = false;
        self
    }

    /// Disable not-before checking, accepting tokens before their validity window.
    pub fn without_nbf(mut self) -> Self {
        self.validate_nbf = false;
        self
    }

    /// Accept future `iat` values; any configured maximum-age policy still applies.
    pub fn without_iat_future_check(mut self) -> Self {
        self.validate_iat_not_future = false;
        self
    }

    /// Require the `iss` claim to equal `issuer`.
    pub fn with_issuer(mut self, issuer: impl Into<String>) -> Self {
        self.issuer = Some(issuer.into());
        self
    }

    /// Require the `aud` claim to contain `audience`.
    pub fn with_audience(mut self, audience: impl Into<String>) -> Self {
        self.audience = Some(audience.into());
        self
    }

    /// Require the `sub` claim to equal this value.
    pub fn with_subject(mut self, subject: impl Into<String>) -> Self {
        self.subject = Some(subject.into());
        self
    }

    /// Set the accepted clock-skew tolerance in seconds.
    pub fn with_leeway(mut self, seconds: u64) -> Self {
        self.leeway = seconds;
        self
    }

    /// Require the protected header's `typ` field to equal this string
    /// (RFC 8725 §3.11). Prevents JWT-in-different-context confusion —
    /// e.g. an OpenID ID Token being accepted where a service-to-service
    /// JWT was expected.
    pub fn with_typ(mut self, typ: impl Into<String>) -> Self {
        self.required_typ = Some(typ.into());
        self
    }

    /// Reject tokens older than `seconds` and require the `iat` claim.
    /// Bounds replay windows on long-lived tokens.
    pub fn with_max_age(mut self, seconds: u64) -> Self {
        self.max_age = Some(seconds);
        self.require_iat = true;
        self
    }

    /// Require the `exp` claim to be present. Without it, a token that omits
    /// `exp` is treated as never-expiring (RFC 7519 makes `exp` optional).
    pub fn require_exp(mut self) -> Self {
        self.require_exp = true;
        self
    }

    /// Require the `nbf` claim to be present.
    pub fn require_nbf(mut self) -> Self {
        self.require_nbf = true;
        self
    }

    /// Require the `iat` claim to be present.
    pub fn require_iat(mut self) -> Self {
        self.require_iat = true;
        self
    }

    /// Require the protected header to carry a `kid`.
    ///
    /// Use this with [`crate::jwt::decode_with_jwkset`] when the JWK Set
    /// holds keys of differing trust (multiple issuers, or a legacy key
    /// kept through a rotation window). Without it, an attacker holding
    /// any one key in the set can omit `kid` and have the token accepted
    /// under that key via the try-every-key fallback.
    pub fn require_kid(mut self) -> Self {
        self.require_kid = true;
        self
    }

    /// Restrict the set of permitted JWS algorithms. Defence in depth on
    /// top of the verifier-binding enforced at the JWS layer. An empty
    /// list means no additional restriction.
    pub fn with_allowed_algorithms(mut self, algs: Vec<JwsAlgorithm>) -> Self {
        self.allowed_algorithms = algs;
        self
    }

    /// Validate claims against this configuration.
    ///
    /// Header-bound checks (`typ`, `allowed_algorithms`) are skipped when
    /// no header is available. Callers that have the protected header
    /// should prefer [`Validation::validate_with_header`].
    pub fn validate(&self, claims: &Claims) -> Result<()> {
        self.validate_internal(claims, None)
    }

    /// Validate claims AND the protected header together. Enables the
    /// header-bound checks configured by [`Validation::with_typ`] and
    /// [`Validation::with_allowed_algorithms`].
    pub fn validate_with_header(&self, claims: &Claims, header: &JoseHeader) -> Result<()> {
        self.validate_internal(claims, Some(header))
    }

    fn validate_internal(&self, claims: &Claims, header: Option<&JoseHeader>) -> Result<()> {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_err(|_| JoseError::InvalidClaims("system clock is before UNIX_EPOCH".into()))?;
        self.validate_at(claims, header, now.into())
    }

    /// Validate using an explicit, trusted clock value with nanosecond precision.
    ///
    /// Pass the authenticated protected header to enforce header-bound policy.
    /// `None` skips header checks, like [`Self::validate`]. Do not derive `now`
    /// from untrusted token claims. Expiration is exclusive: `now >= exp +
    /// leeway` fails. Not-before and future-iat boundaries are inclusive;
    /// maximum age rejects only ages greater than the configured limit.
    ///
    /// ```
    /// use jose_rs::jwt::{Claims, Validation};
    /// let claims: Claims = serde_json::from_str(r#"{"exp":10.5}"#)?;
    /// let policy = Validation::new().with_leeway(0);
    /// policy.validate_at(&claims, None, "10.499999999".parse()?)?;
    /// assert!(policy.validate_at(&claims, None, "10.5".parse()?).is_err());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn validate_at(
        &self,
        claims: &Claims,
        header: Option<&JoseHeader>,
        now: NumericDate,
    ) -> Result<()> {
        // Header-bound checks (run first — fail fast on a mis-typed token).
        if let Some(h) = header {
            if self.require_kid && h.kid.is_none() {
                return Err(JoseError::InvalidHeader(
                    "missing required kid header".into(),
                ));
            }
            if let Some(required_typ) = &self.required_typ {
                match &h.typ {
                    Some(t) if t == required_typ => {}
                    _ => {
                        return Err(JoseError::InvalidHeader(format!(
                            "expected typ={required_typ}, got {:?}",
                            h.typ
                        )))
                    }
                }
            }
            if !self.allowed_algorithms.is_empty() {
                let alg = JwsAlgorithm::from_str(&h.alg)?;
                if !self.allowed_algorithms.contains(&alg) {
                    return Err(JoseError::UnsupportedAlgorithm(format!(
                        "alg {} is not in the caller's allow-list",
                        h.alg
                    )));
                }
            }
        }

        // A u128 holds the entire u64 seconds domain plus leeway and max age
        // in nanoseconds without either overflow or fractional rounding.
        let now = now.as_nanos();
        let leeway = u128::from(self.leeway) * 1_000_000_000;

        // Presence requirements run before value checks: a token that omits
        // a required claim is rejected outright rather than silently passing.
        if self.require_exp && claims.exp.is_none() {
            return Err(JoseError::InvalidClaims(
                "missing required exp claim".into(),
            ));
        }
        if self.require_nbf && claims.nbf.is_none() {
            return Err(JoseError::InvalidClaims(
                "missing required nbf claim".into(),
            ));
        }
        if (self.require_iat || self.max_age.is_some()) && claims.iat.is_none() {
            return Err(JoseError::InvalidClaims(
                "missing required iat claim".into(),
            ));
        }

        // RFC 7519: the current time must be strictly before expiration.
        if self.validate_exp {
            if let Some(exp) = claims.exp {
                if now >= exp.as_nanos() + leeway {
                    return Err(JoseError::Expired);
                }
            }
        }

        // Preserve fractional not-before boundaries.
        if self.validate_nbf {
            if let Some(nbf) = claims.nbf {
                if now + leeway < nbf.as_nanos() {
                    return Err(JoseError::NotYetValid);
                }
            }
        }

        // Reject future-dated iat (attacker-controlled or clock-skewed issuer).
        if self.validate_iat_not_future {
            if let Some(iat) = claims.iat {
                if iat.as_nanos() > now + leeway {
                    return Err(JoseError::InvalidClaims("iat is in the future".into()));
                }
            }
        }

        // Enforce max token age relative to iat.
        if let (Some(max_age), Some(iat)) = (self.max_age, claims.iat) {
            // now - iat > max_age + leeway → too old.
            if now > iat.as_nanos() + u128::from(max_age) * 1_000_000_000 + leeway {
                return Err(JoseError::Expired);
            }
        }

        // Check issuer
        if let Some(ref required_iss) = self.issuer {
            match &claims.iss {
                Some(iss) if iss == required_iss => {}
                _ => return Err(JoseError::InvalidIssuer),
            }
        }

        // Check audience
        if let Some(ref required_aud) = self.audience {
            match &claims.aud {
                Some(aud) if aud.contains(required_aud) => {}
                _ => return Err(JoseError::InvalidAudience),
            }
        }

        // Check subject
        if let Some(ref required_sub) = self.subject {
            match &claims.sub {
                Some(sub) if sub == required_sub => {}
                _ => return Err(JoseError::InvalidClaims("subject mismatch".into())),
            }
        }

        Ok(())
    }
}

#[cfg(test)]
#[allow(clippy::field_reassign_with_default)]
mod tests {
    use super::*;
    use std::time::{SystemTime, UNIX_EPOCH};

    fn now() -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
    }

    /// Phase 5: typ header mismatch is rejected.
    #[test]
    fn typ_mismatch_rejected() {
        let mut header = JoseHeader::new("HS256");
        header.typ = Some("JWT".into());
        let mut claims = Claims::default();
        claims.exp = Some((now() + 3600).into());

        let validation = Validation::new().with_typ("at+jwt");
        let err = validation
            .validate_with_header(&claims, &header)
            .unwrap_err()
            .to_string();
        assert!(err.contains("at+jwt"), "unexpected: {err}");
    }

    /// Phase 5: missing typ when required is rejected.
    #[test]
    fn typ_missing_when_required() {
        let header = JoseHeader::new("HS256"); // typ unset
        let mut claims = Claims::default();
        claims.exp = Some((now() + 3600).into());

        let validation = Validation::new().with_typ("JWT");
        assert!(validation.validate_with_header(&claims, &header).is_err());
    }

    /// Phase 5: typ match succeeds.
    #[test]
    fn typ_match_accepted() {
        let mut header = JoseHeader::new("HS256");
        header.typ = Some("JWT".into());
        let mut claims = Claims::default();
        claims.exp = Some((now() + 3600).into());

        let validation = Validation::new().with_typ("JWT");
        validation.validate_with_header(&claims, &header).unwrap();
    }

    /// Phase 5: allowed_algorithms rejects an unlisted alg.
    #[test]
    fn alg_allow_list_rejects_unlisted() {
        let header = JoseHeader::new("HS256");
        let mut claims = Claims::default();
        claims.exp = Some((now() + 3600).into());

        let validation = Validation::new().with_allowed_algorithms(vec![JwsAlgorithm::RS256]);
        let err = validation
            .validate_with_header(&claims, &header)
            .unwrap_err()
            .to_string();
        assert!(err.contains("allow-list"), "unexpected: {err}");
    }

    /// Phase 5: allowed_algorithms accepts a listed alg.
    #[test]
    fn alg_allow_list_accepts_listed() {
        let header = JoseHeader::new("HS256");
        let mut claims = Claims::default();
        claims.exp = Some((now() + 3600).into());

        let validation = Validation::new()
            .with_allowed_algorithms(vec![JwsAlgorithm::HS256, JwsAlgorithm::RS256]);
        validation.validate_with_header(&claims, &header).unwrap();
    }

    /// Phase 5: iat too old vs max_age is rejected.
    #[test]
    fn max_age_rejects_old_iat() {
        let mut claims = Claims::default();
        claims.iat = Some((now() - 3600).into()); // issued 1h ago

        let validation = Validation::new().with_max_age(60); // 60s cap
        let err = validation.validate(&claims).unwrap_err();
        assert!(matches!(err, JoseError::Expired));
    }

    /// Phase 5: iat within max_age is accepted.
    #[test]
    fn max_age_accepts_recent_iat() {
        let mut claims = Claims::default();
        claims.iat = Some((now() - 10).into()); // 10s ago

        let validation = Validation::new().with_max_age(60);
        validation.validate(&claims).unwrap();
    }

    /// max_age cannot be evaluated without iat, so missing iat is rejected.
    #[test]
    fn max_age_rejects_missing_iat() {
        let mut claims = Claims::default();
        claims.exp = Some((now() + 3600).into());

        let validation = Validation::new().with_max_age(60);
        let err = validation.validate(&claims).unwrap_err().to_string();
        assert!(err.contains("missing required iat"), "unexpected: {err}");
    }

    /// Phase 5: iat in the future (beyond leeway) is rejected.
    #[test]
    fn iat_in_future_rejected() {
        let mut claims = Claims::default();
        claims.iat = Some((now() + 3600).into()); // 1h in the future

        let validation = Validation::new(); // default 60s leeway
        let err = validation.validate(&claims).unwrap_err().to_string();
        assert!(err.contains("future"), "unexpected: {err}");
    }

    /// Phase 5: iat slightly in the future (within leeway) is accepted.
    #[test]
    fn iat_within_leeway_accepted() {
        let mut claims = Claims::default();
        claims.iat = Some((now() + 30).into()); // 30s in the future, within 60s leeway

        let validation = Validation::new();
        validation.validate(&claims).unwrap();
    }

    /// Phase 5: with_subject builder and subject check.
    #[test]
    fn with_subject_builder_and_check() {
        let mut claims = Claims::default();
        claims.sub = Some("alice".into());
        claims.exp = Some((now() + 3600).into());

        let v = Validation::new().with_subject("alice");
        v.validate(&claims).unwrap();

        let v_wrong = Validation::new().with_subject("bob");
        assert!(v_wrong.validate(&claims).is_err());
    }

    /// require_exp rejects a token that omits `exp`.
    #[test]
    fn require_exp_rejects_missing_exp() {
        let claims = Claims::default(); // no exp
        let validation = Validation::new().require_exp();
        let err = validation.validate(&claims).unwrap_err().to_string();
        assert!(err.contains("missing required exp"), "unexpected: {err}");
    }

    /// require_exp accepts a token that carries a (valid) `exp`.
    #[test]
    fn require_exp_accepts_present_exp() {
        let mut claims = Claims::default();
        claims.exp = Some((now() + 3600).into());
        Validation::new().require_exp().validate(&claims).unwrap();
    }

    /// require_nbf rejects a token that omits `nbf`.
    #[test]
    fn require_nbf_rejects_missing_nbf() {
        let mut claims = Claims::default();
        claims.exp = Some((now() + 3600).into());
        let err = Validation::new()
            .require_nbf()
            .validate(&claims)
            .unwrap_err()
            .to_string();
        assert!(err.contains("missing required nbf"), "unexpected: {err}");
    }

    /// require_iat rejects a token that omits `iat`.
    #[test]
    fn require_iat_rejects_missing_iat() {
        let mut claims = Claims::default();
        claims.exp = Some((now() + 3600).into());
        let err = Validation::new()
            .require_iat()
            .validate(&claims)
            .unwrap_err()
            .to_string();
        assert!(err.contains("missing required iat"), "unexpected: {err}");
    }

    /// require_iat accepts a token that carries a non-future `iat`.
    #[test]
    fn require_iat_accepts_present_iat() {
        let mut claims = Claims::default();
        claims.exp = Some((now() + 3600).into());
        claims.iat = Some((now()).into());
        Validation::new().require_iat().validate(&claims).unwrap();
    }

    /// Default validation still accepts a token with no exp (back-compat).
    #[test]
    fn default_accepts_missing_exp() {
        let claims = Claims::default();
        Validation::new().validate(&claims).unwrap();
    }

    /// J-12 regression: exp near u64::MAX with a non-zero leeway must not
    /// overflow into a small number (which would previously cause spurious
    /// Expired errors for far-future tokens).
    #[test]
    fn exp_near_u64_max_does_not_wrap() {
        let mut claims = Claims::default();
        claims.exp = Some((u64::MAX - 1).into());
        let validation = Validation::new().with_leeway(60);
        // Far-future exp must not be reported as expired.
        validation.validate(&claims).unwrap();
    }

    /// J-12 regression: nbf near u64::MAX with leeway must not overflow either.
    #[test]
    fn nbf_near_u64_max_does_not_wrap() {
        let mut claims = Claims::default();
        claims.nbf = Some((u64::MAX - 1).into());
        let validation = Validation::new().with_leeway(60);
        // nbf in the far future means not-yet-valid — expected error, not a panic.
        let err = validation.validate(&claims).unwrap_err();
        assert!(matches!(err, JoseError::NotYetValid));
    }
}