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
//! JWT Validation configuration (RFC 7519).
use crate::algorithm::JwsAlgorithm;
use crate::error::{JoseError, Result};
use crate::header::JoseHeader;
use crate::jwt::claims::Claims;
use std::time::{SystemTime, UNIX_EPOCH};
/// Validation configuration for JWT decoding.
#[derive(Debug, Clone)]
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 and `iat` is present, 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.
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,
}
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,
}
}
}
impl Validation {
pub fn new() -> Self {
Self::default()
}
pub fn with_issuer(mut self, issuer: impl Into<String>) -> Self {
self.issuer = Some(issuer.into());
self
}
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
}
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` when `iat` is present.
/// Bounds replay windows on long-lived tokens.
pub fn with_max_age(mut self, seconds: u64) -> Self {
self.max_age = Some(seconds);
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<()> {
// Header-bound checks (run first — fail fast on a mis-typed token).
if let Some(h) = header {
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
)));
}
}
}
// If the system clock is before 1970 something is very wrong — fail closed.
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|_| JoseError::InvalidClaims("system clock is before UNIX_EPOCH".into()))?
.as_secs();
// Check expiration — use saturating_add so an attacker-controlled exp
// near u64::MAX cannot wrap and falsely satisfy the comparison.
if self.validate_exp {
if let Some(exp) = claims.exp {
if now > exp.saturating_add(self.leeway) {
return Err(JoseError::Expired);
}
}
}
// Check not-before — saturating_add prevents overflow at the high end.
if self.validate_nbf {
if let Some(nbf) = claims.nbf {
if now.saturating_add(self.leeway) < nbf {
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 > now.saturating_add(self.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.
// Use saturating to handle any edge cases.
if now > iat.saturating_add(max_age).saturating_add(self.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);
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);
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);
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);
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);
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); // 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); // 10s ago
let validation = Validation::new().with_max_age(60);
validation.validate(&claims).unwrap();
}
/// 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); // 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); // 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);
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());
}
/// 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);
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);
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));
}
}