polyjose 0.1.2

Pure-Rust JOSE: JWA, JWK, JWS, JWE and JWT per the RFCs, with no OpenSSL
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
//! Claims validation against the policy: steps J4–J10 of ADR 0027 §9
//! (RFC 7519 §4.1.1–§4.1.6; RFC 8725 §3.8–§3.9; RFC 9068 §2.2, §4).

use core::cmp::Ordering;

use crate::error::{Error, Result};
use crate::json::Value;

use super::claims::REGISTERED_CLAIMS;
use super::typ::ACCESS_TOKEN_REQUIRED_CLAIMS;
use super::{Claims, NumericDate, Policy};

/// The [`Error::InvalidClaim`] detail for a missing claim whose name the
/// caller chose and that is not one polyjose knows: the detail is a
/// `&'static str`, so it cannot carry the caller's string. Details are
/// diagnostic only; the code is the contract (ADR 0027 §9).
const OTHER_REQUIRED_CLAIM: &str = "required";

/// The RFC 9068 §2.2 client identifier claim, which
/// [`Policy::access_token`] requires to be a JSON string (ADR 0052).
const CLIENT_ID: &str = "client_id";

/// Validates `c` against `p`, in the ADR 0027 §9 order; the first failing
/// step decides the error:
///
/// - J4: required-claim presence, in the order `iss, sub, aud, exp, nbf,
///   iat, jti`, then the policy's other required names in order, and
///   under [`Policy::access_token`] a JSON string `client_id`
///   (ADR 0052) → [`Error::InvalidClaim`];
/// - J5: `exp` (RFC 7519 §4.1.4) → [`Error::TokenExpired`];
/// - J6: `nbf` (RFC 7519 §4.1.5) → [`Error::TokenNotYetValid`];
/// - J7: `iat` with a maximum age (RFC 7519 §4.1.6) → `InvalidClaim`;
/// - J8–J10: `iss`, `sub`, `aud`, the last including a token `aud` with
///   no configured audience (RFC 7519 §4.1.1–§4.1.3) → `InvalidClaim`.
///
/// The clock is read (through the policy) only when a time check runs,
/// and at most once (ADR 0028). A clock that fails or is outside
/// ±(2^53 − 1) fails the first time check that runs with
/// [`Error::InvalidClaim`]`("clock")` (ADR 0028 §1); presence (J4) is
/// decided before that.
///
/// The `InvalidClaim` detail names the registered claim, or `client_id`;
/// another caller-required name is reported as `"required"`, since the
/// detail is a `&'static str`. Details are diagnostic; the codes are the
/// contract (ADR 0027 §9). No claim value is ever put in an error.
pub(crate) fn validate_claims(c: &Claims, p: &Policy<'_>) -> Result<()> {
    check_presence(c, p)?;
    let mut now = Now::new(p);
    check_exp(c, p, &mut now)?;
    check_nbf(c, p, &mut now)?;
    check_iat(c, p, &mut now)?;
    check_iss(c, p)?;
    check_sub(c, p)?;
    check_aud(c, p)
}

/// J8: with accepted issuers configured, `iss` equals one of them. Exact,
/// case-sensitive comparison with no normalization (RFC 7519 §2, §4.1.1,
/// §7.3); RFC 8725 §3.8, RFC 9068 §4; ADR 0027 §4. Without accepted
/// issuers, `iss` is not checked.
///
/// # Errors
///
/// [`Error::InvalidClaim`]`("iss")` if `iss` is missing or not accepted.
fn check_iss(c: &Claims, p: &Policy<'_>) -> Result<()> {
    let accepted = p.accepted_issuers();
    if accepted.is_empty() {
        return Ok(());
    }
    match &c.iss {
        Some(iss) if accepted.contains(iss) => Ok(()),
        _ => Err(Error::InvalidClaim("iss")),
    }
}

/// J9: with an expected subject configured, `sub` equals it exactly
/// (RFC 7519 §2, §4.1.2, §7.3; ADR 0027 §4).
///
/// # Errors
///
/// [`Error::InvalidClaim`]`("sub")` if `sub` is missing or different.
fn check_sub(c: &Claims, p: &Policy<'_>) -> Result<()> {
    match p.expected_subject() {
        Some(expected) if c.sub.as_deref() != Some(expected) => Err(Error::InvalidClaim("sub")),
        _ => Ok(()),
    }
}

/// J10: the audience (RFC 7519 §4.1.3; RFC 8725 §3.9; ADR 0027 §4).
///
/// - With accepted audiences configured, `aud` is required and at least
///   one of its values equals one of them exactly (case-sensitive,
///   RFC 7519 §7.3). An empty array matches nothing.
/// - With none configured, a token that carries `aud` (an empty array
///   included) is rejected: "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" (RFC 7519 §4.1.3). Only
///   the explicit [`ignore_audience`](Policy::ignore_audience) opt-out
///   accepts it.
///
/// # Errors
///
/// [`Error::InvalidClaim`]`("aud")`.
fn check_aud(c: &Claims, p: &Policy<'_>) -> Result<()> {
    let accepted = p.accepted_audiences();
    if accepted.is_empty() {
        // No audience configured: a present `aud` is rejected unless the
        // caller opted out (RFC 7519 §4.1.3; ADR 0027 §4).
        return aud_verdict(c.aud.is_none() || p.ignores_audience());
    }
    // Configured: `aud` is required and one value must match exactly
    // (RFC 7519 §4.1.3, §7.3); a missing `aud` matches nothing.
    aud_verdict(
        c.aud
            .as_ref()
            .is_some_and(|aud| aud.values().iter().any(|value| accepted.contains(value))),
    )
}

/// `Ok` if the J10 audience check passed, else
/// [`Error::InvalidClaim`]`("aud")` (RFC 7519 §4.1.3).
fn aud_verdict(ok: bool) -> Result<()> {
    if ok {
        Ok(())
    } else {
        Err(Error::InvalidClaim("aud"))
    }
}

/// The current time, read from the policy's clock on first use and then
/// reused: at most one read per validation, and none when no time check
/// runs (ADR 0028).
struct Now<'p, 'a> {
    policy: &'p Policy<'a>,
    secs: Option<i64>,
}

impl<'p, 'a> Now<'p, 'a> {
    fn new(policy: &'p Policy<'a>) -> Self {
        Self { policy, secs: None }
    }

    /// Whole seconds since the epoch, within ±(2^53 − 1).
    ///
    /// # Errors
    ///
    /// [`Error::InvalidClaim`]`("clock")`, or the clock's own error
    /// (ADR 0028 §1).
    fn get(&mut self) -> Result<i64> {
        match self.secs {
            Some(secs) => Ok(secs),
            None => {
                let secs = self.policy.now()?;
                self.secs = Some(secs);
                Ok(secs)
            }
        }
    }
}

/// J5: a present `exp` has not passed. RFC 7519 §4.1.4: "the current
/// date/time MUST be before the expiration date/time", with "some small
/// leeway"; rejected iff `exp ≤ now − leeway` (ADR 0027 §3). Presence is
/// J4's job.
///
/// # Errors
///
/// [`Error::TokenExpired`], or a clock error.
fn check_exp(c: &Claims, p: &Policy<'_>, now: &mut Now<'_, '_>) -> Result<()> {
    match &c.exp {
        Some(exp) if exp.is_expired(now.get()?, p.leeway_secs()) => Err(Error::TokenExpired),
        _ => Ok(()),
    }
}

/// J6: a present `nbf` has been reached. RFC 7519 §4.1.5: "the current
/// date/time MUST be after or equal to the not-before date/time", with
/// "some small leeway"; rejected iff `nbf > now + leeway` (ADR 0027 §3).
///
/// # Errors
///
/// [`Error::TokenNotYetValid`], or a clock error.
fn check_nbf(c: &Claims, p: &Policy<'_>, now: &mut Now<'_, '_>) -> Result<()> {
    match &c.nbf {
        Some(nbf) if nbf.is_not_yet_valid(now.get()?, p.leeway_secs()) => {
            Err(Error::TokenNotYetValid)
        }
        _ => Ok(()),
    }
}

/// J7: with a maximum age set, `iat` lies within
/// `[now − max_age − leeway, now + leeway]` (ADR 0027 §3). RFC 7519
/// §4.1.6 "can be used to determine the age of the JWT" but sets no rule
/// of its own, so without a maximum age `iat` is not time-checked and a
/// future `iat` is accepted (reported erratum 7720).
///
/// # Errors
///
/// [`Error::InvalidClaim`]`("iat")`, or a clock error.
fn check_iat(c: &Claims, p: &Policy<'_>, now: &mut Now<'_, '_>) -> Result<()> {
    let Some(max_age) = p.max_age_secs() else {
        return Ok(());
    };
    // J4 made `iat` required with a maximum age; checked again so this
    // step never depends on that.
    let iat = c.iat.as_ref().ok_or(Error::InvalidClaim("iat"))?;
    if iat_outside_window(iat, now.get()?, max_age, p.leeway_secs()) {
        return Err(Error::InvalidClaim("iat"));
    }
    Ok(())
}

/// Whether `iat` was issued in the future (`iat > now + leeway`) or too
/// long ago (`iat < now − max_age − leeway`), ADR 0027 §3.
///
/// Exact for every `i64` `now` and `u32` setting, with no overflow: the
/// bounds are computed with saturating `i64` arithmetic and compared
/// without rounding by [`NumericDate::cmp_secs`]. A bound that saturates
/// lies beyond `i64`'s range, so beyond every NumericDate (at most
/// 2^53 − 1 in magnitude), and the saturated value orders the same way
/// against every NumericDate. Both bounds move in one direction only, so
/// saturating twice clamps the same way as once.
fn iat_outside_window(iat: &NumericDate, now: i64, max_age: u32, leeway: u32) -> bool {
    let leeway = i64::from(leeway);
    let latest = now.saturating_add(leeway);
    let earliest = now
        .saturating_sub(i64::from(max_age))
        .saturating_sub(leeway);
    iat.cmp_secs(latest) == Ordering::Greater || iat.cmp_secs(earliest) == Ordering::Less
}

/// J4 (ADR 0027 §9): every required claim is present, with any value,
/// except `client_id` under [`Policy::access_token`], which must be a
/// JSON string (ADR 0052).
///
/// A registered claim is required when the policy names it in
/// [`require`](Policy::require) or implies it (ADR 0027 §3–§4):
///
/// - `iss` once an issuer is accepted (RFC 8725 §3.8, RFC 9068 §4);
/// - `sub` once a subject is expected;
/// - `aud` once an audience is accepted (RFC 7519 §4.1.3, RFC 8725 §3.9);
/// - `exp` unless [`allow_missing_exp`](Policy::allow_missing_exp)
///   (ADR 0007);
/// - `iat` once a maximum age is set (RFC 7519 §4.1.6).
///
/// The registered claims are checked in the order `iss, sub, aud, exp,
/// nbf, iat, jti`, then the other required names in the order given. Any
/// JSON value counts as present (ADR 0027 §4), with one exception
/// (ADR 0052, superseding ADR 0027 §4 for this claim): under
/// [`Policy::access_token`], `client_id` must be a JSON string, `""`
/// included. RFC 9068 §2.2 defines it by RFC 8693 §4.3 as the client
/// identifier of RFC 6749 §2.2, "a unique string". A non-string
/// `client_id` fails at the same position as a missing one. Plain
/// [`require`](Policy::require)`("client_id")` keeps any JSON type. An
/// empty `aud` array is present; it then fails J10.
///
/// # Errors
///
/// [`Error::InvalidClaim`] naming the first missing claim.
fn check_presence(c: &Claims, p: &Policy<'_>) -> Result<()> {
    let required = p.required_claims();
    let present = [
        c.iss.is_some(),
        c.sub.is_some(),
        c.aud.is_some(),
        c.exp.is_some(),
        c.nbf.is_some(),
        c.iat.is_some(),
        c.jti.is_some(),
    ];
    let implied = [
        !p.accepted_issuers().is_empty(),
        p.expected_subject().is_some(),
        !p.accepted_audiences().is_empty(),
        p.requires_exp(),
        false,
        p.max_age_secs().is_some(),
        false,
    ];
    for ((name, present), implied) in REGISTERED_CLAIMS.into_iter().zip(present).zip(implied) {
        if !present && (implied || required.iter().any(|r| r == name)) {
            return Err(Error::InvalidClaim(name));
        }
    }
    for name in required {
        if !REGISTERED_CLAIMS.contains(&name.as_str()) && !satisfies(c.get(name), name, p) {
            return Err(Error::InvalidClaim(detail(name)));
        }
    }
    Ok(())
}

/// Whether `value`, the claim `name` in the token, meets J4: present,
/// and a JSON string when `name` is `client_id` under
/// [`Policy::access_token`] (ADR 0052; RFC 9068 §2.2, RFC 6749 §2.2).
fn satisfies(value: Option<&Value>, name: &str, p: &Policy<'_>) -> bool {
    match value {
        None => false,
        Some(Value::String(_)) => true,
        Some(_) => !(name == CLIENT_ID && p.requires_string_client_id()),
    }
}

/// The `InvalidClaim` detail naming `name`: the name itself when it is an
/// RFC 9068 §2.2 claim, else [`OTHER_REQUIRED_CLAIM`]. Never echoes the
/// caller's string, and never a claim value.
fn detail(name: &str) -> &'static str {
    ACCESS_TOKEN_REQUIRED_CLAIMS
        .into_iter()
        .find(|known| *known == name)
        .unwrap_or(OTHER_REQUIRED_CLAIM)
}

#[cfg(test)]
mod tests {
    use super::*;
    use core::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};

    use crate::json::{MAX_SAFE_INTEGER, Number};
    use crate::json::{Object, Value};
    use crate::jwa::SigningAlg;
    use crate::jwt::{Audience, Clock, FixedClock, NumericDate};

    const ES256: &[SigningAlg] = &[SigningAlg::ES256];

    /// A clock that must not be read: passed wherever no time check runs,
    /// to prove validation reads the time only when it needs it
    /// (ADR 0028).
    struct PanicClock;

    impl Clock for PanicClock {
        fn now(&self) -> Result<i64> {
            panic!("the clock was read although no time check runs");
        }
    }

    /// A policy over [`PanicClock`].
    fn untimed() -> Policy<'static> {
        Policy::new(&PanicClock, ES256).unwrap()
    }

    fn date(secs: i64) -> Option<NumericDate> {
        NumericDate::from_secs(secs)
    }

    #[test]
    fn missing_exp_is_rejected_by_default_without_reading_the_clock() {
        // ADR 0007, ADR 0027 §3: `exp` is required unless explicitly
        // waived; presence (J4) runs before any time check.
        assert_eq!(
            validate_claims(&Claims::new(), &untimed()),
            Err(Error::InvalidClaim("exp"))
        );
    }

    #[test]
    fn allow_missing_exp_accepts_a_token_without_exp_or_a_clock_read() {
        // ADR 0027 §3: the explicit opt-out. Nothing to compare with the
        // time, so the clock is not read (ADR 0028).
        let p = untimed().allow_missing_exp();
        assert_eq!(validate_claims(&Claims::new(), &p), Ok(()));
        // A future `iat` without `max_age` is not checked either
        // (reported erratum 7720 on RFC 7519 §4.1.6).
        let mut c = Claims::new();
        c.iat = date(i64::from(u32::MAX));
        c.jti = Some("id".into());
        assert_eq!(validate_claims(&c, &p), Ok(()));
    }

    #[test]
    fn configured_issuer_subject_audience_and_max_age_imply_presence() {
        // ADR 0027 §3–§4: each makes its claim required, checked in the
        // J4 order iss, sub, aud, exp, nbf, iat, jti.
        let p = untimed()
            .issuer("https://a")
            .subject("alice")
            .audience("api")
            .max_age(300);
        let mut c = Claims::new();
        assert_eq!(validate_claims(&c, &p), Err(Error::InvalidClaim("iss")));
        c.iss = Some("https://a".into());
        assert_eq!(validate_claims(&c, &p), Err(Error::InvalidClaim("sub")));
        c.sub = Some("alice".into());
        assert_eq!(validate_claims(&c, &p), Err(Error::InvalidClaim("aud")));
        c.aud = Some(Audience::One("api".into()));
        assert_eq!(validate_claims(&c, &p), Err(Error::InvalidClaim("exp")));
        let p = p.allow_missing_exp();
        assert_eq!(validate_claims(&c, &p), Err(Error::InvalidClaim("iat")));
    }

    #[test]
    fn required_claim_may_hold_any_json_type() {
        // ADR 0027 §4: "must be present (any JSON type)".
        let p = untimed().allow_missing_exp().require("client_id");
        let mut c = Claims::new();
        assert_eq!(
            validate_claims(&c, &p),
            Err(Error::InvalidClaim("client_id"))
        );
        // A claim of another name does not count.
        c.insert("client", "s6BhdRkqt3").unwrap();
        assert_eq!(
            validate_claims(&c, &p),
            Err(Error::InvalidClaim("client_id"))
        );
        let mut object = Object::new();
        object.insert("id", "s6BhdRkqt3");
        for value in [
            Value::from("s6BhdRkqt3"),
            Value::Number(Number::from_i64(42).unwrap()),
            Value::from(object),
            Value::Null,
            Value::Bool(false),
            Value::from(Vec::new()),
        ] {
            c.insert("client_id", value.clone()).unwrap();
            assert_eq!(validate_claims(&c, &p), Ok(()), "{value:?}");
        }
    }

    #[test]
    fn required_names_follow_the_registered_order_then_the_callers() {
        // ADR 0027 §9 J4: registered claims first, whatever order they
        // were required in, then the other names in the order given.
        // The detail of a caller-chosen name is "required" (the detail is
        // a `&'static str`), except for the RFC 9068 §2.2 names, so
        // `client_id` against `x-tenant` shows the caller's order.
        let clock = FixedClock(0);
        let first_tenant = Policy::new(&clock, ES256)
            .unwrap()
            .allow_missing_exp()
            .require("x-tenant")
            .require("jti")
            .require("client_id")
            .require("nbf");
        let first_client = Policy::new(&clock, ES256)
            .unwrap()
            .allow_missing_exp()
            .require("client_id")
            .require("nbf")
            .require("x-tenant")
            .require("jti");
        let mut c = Claims::new();
        for p in [&first_tenant, &first_client] {
            assert_eq!(validate_claims(&c, p), Err(Error::InvalidClaim("nbf")));
        }
        c.nbf = date(-100);
        for p in [&first_tenant, &first_client] {
            assert_eq!(validate_claims(&c, p), Err(Error::InvalidClaim("jti")));
        }
        c.jti = Some("id".into());
        assert_eq!(
            validate_claims(&c, &first_tenant),
            Err(Error::InvalidClaim("required"))
        );
        assert_eq!(
            validate_claims(&c, &first_client),
            Err(Error::InvalidClaim("client_id"))
        );
        c.insert("x-tenant", "t1").unwrap();
        for p in [&first_tenant, &first_client] {
            assert_eq!(
                validate_claims(&c, p),
                Err(Error::InvalidClaim("client_id"))
            );
        }
        c.insert("client_id", Value::Null).unwrap();
        for p in [&first_tenant, &first_client] {
            assert_eq!(validate_claims(&c, p), Ok(()));
        }
    }

    #[test]
    fn require_exp_still_applies_after_allow_missing_exp() {
        // policy.rs: "a require("exp") still applies".
        let p = untimed().allow_missing_exp().require("exp");
        assert_eq!(
            validate_claims(&Claims::new(), &p),
            Err(Error::InvalidClaim("exp"))
        );
    }

    /// A policy over `clock` with `leeway` seconds of skew.
    fn timed(clock: &FixedClock, leeway: u32) -> Policy<'_> {
        Policy::new(clock, ES256).unwrap().leeway(leeway).unwrap()
    }

    /// A clock that counts its reads.
    struct CountingClock(i64, AtomicUsize);

    impl Clock for CountingClock {
        fn now(&self) -> Result<i64> {
            self.1.fetch_add(1, AtomicOrdering::Relaxed);
            Ok(self.0)
        }
    }

    #[test]
    fn exp_boundaries_of_adr_0027_section_3() {
        // RFC 7519 §4.1.4: rejected iff exp ≤ now − leeway (ADR 0027 §3).
        for (exp, leeway, now, expected) in [
            (1000.0, 60, 1059, Ok(())),
            (1000.0, 60, 1060, Err(Error::TokenExpired)),
            (1000.0, 0, 999, Ok(())),
            (1000.0, 0, 1000, Err(Error::TokenExpired)),
            (1000.5, 0, 1000, Ok(())),
            (1000.5, 0, 1001, Err(Error::TokenExpired)),
            // A negative date is simply in the past (ADR 0027 §2).
            (-1.0, 0, 0, Err(Error::TokenExpired)),
            (-1.0, 60, 0, Ok(())),
            (-61.0, 60, 0, Err(Error::TokenExpired)),
        ] {
            let clock = FixedClock(now);
            let mut c = Claims::new();
            c.exp = NumericDate::from_f64(exp);
            assert_eq!(
                validate_claims(&c, &timed(&clock, leeway)),
                expected,
                "exp {exp}, leeway {leeway}, now {now}"
            );
        }
    }

    #[test]
    fn nbf_boundaries_of_adr_0027_section_3() {
        // RFC 7519 §4.1.5: rejected iff nbf > now + leeway (ADR 0027 §3).
        for (nbf, leeway, now, expected) in [
            (Some(1000.0), 60, 940, Ok(())),
            (Some(1000.0), 60, 939, Err(Error::TokenNotYetValid)),
            (Some(1000.0), 0, 1000, Ok(())),
            (Some(1000.0), 0, 999, Err(Error::TokenNotYetValid)),
            (Some(1000.5), 0, 1000, Err(Error::TokenNotYetValid)),
            (Some(1000.5), 0, 1001, Ok(())),
            (Some(-100.0), 60, 0, Ok(())),
            (Some(-100.0), 0, -100, Ok(())),
            (None, 0, 0, Ok(())),
        ] {
            let clock = FixedClock(now);
            let mut c = Claims::new();
            c.nbf = nbf.and_then(NumericDate::from_f64);
            let p = timed(&clock, leeway).allow_missing_exp();
            assert_eq!(
                validate_claims(&c, &p),
                expected,
                "nbf {nbf:?}, leeway {leeway}, now {now}"
            );
        }
    }

    #[test]
    fn future_iat_is_accepted_without_max_age() {
        // Reported erratum 7720 on RFC 7519 §4.1.6 (ADR 0027 §3).
        let now = 1_300_819_380;
        let clock = FixedClock(now);
        let mut c = Claims::new();
        c.exp = date(now + 7200);
        c.iat = date(now + 3600);
        assert_eq!(validate_claims(&c, &timed(&clock, 60)), Ok(()));
        assert_eq!(validate_claims(&c, &timed(&clock, 0)), Ok(()));
    }

    #[test]
    fn iat_window_with_max_age() {
        // ADR 0027 §3: rejected iff iat > now + leeway or
        // iat < now − max_age − leeway (RFC 7519 §4.1.6).
        let now = 1_300_819_380;
        let clock = FixedClock(now);
        let p = timed(&clock, 60).max_age(300);
        let mut c = Claims::new();
        c.exp = date(now + 7200);
        assert_eq!(validate_claims(&c, &p), Err(Error::InvalidClaim("iat")));
        for (offset, expected) in [
            (61.0, Err(Error::InvalidClaim("iat"))),
            (60.5, Err(Error::InvalidClaim("iat"))),
            (60.0, Ok(())),
            (0.0, Ok(())),
            (-360.0, Ok(())),
            (-360.5, Err(Error::InvalidClaim("iat"))),
            (-361.0, Err(Error::InvalidClaim("iat"))),
        ] {
            c.iat = NumericDate::from_f64(now as f64 + offset);
            assert_eq!(validate_claims(&c, &p), expected, "iat now{offset:+}");
        }
    }

    #[test]
    fn iat_window_is_exact_for_any_now_and_bound() {
        // No overflow, no panic and no rounding for every i64 time and u32
        // setting (ADR 0027 §3). The policy's clock is bounded to
        // ±(2^53 − 1), but the arithmetic does not rely on it.
        let max = NumericDate::from_secs(MAX_SAFE_INTEGER).unwrap();
        let min = NumericDate::from_secs(-MAX_SAFE_INTEGER).unwrap();
        let half = NumericDate::from_f64(0.5).unwrap();
        for (iat, now, max_age, leeway, outside) in [
            // i64 extremes: now ± max_age ± leeway leaves the i64 range.
            (max, i64::MAX, u32::MAX, u32::MAX, true),
            (min, i64::MAX, u32::MAX, u32::MAX, true),
            (max, i64::MAX, 0, u32::MAX, true),
            (max, i64::MIN, u32::MAX, u32::MAX, true),
            (min, i64::MIN, u32::MAX, u32::MAX, true),
            (min, i64::MIN + 1, 0, 0, true),
            // Exact at the edges of the NumericDate range, where
            // now ± leeway is beyond 2^53 and not exact as a double.
            (max, MAX_SAFE_INTEGER, 0, 0, false),
            (max, MAX_SAFE_INTEGER - 1, 0, 0, true),
            (max, MAX_SAFE_INTEGER + 1, 0, 0, true),
            (max, MAX_SAFE_INTEGER + 1, 1, 0, false),
            (max, MAX_SAFE_INTEGER + 600, 0, 600, false),
            (max, MAX_SAFE_INTEGER + 601, 0, 600, true),
            (min, -MAX_SAFE_INTEGER, 0, 0, false),
            (min, -MAX_SAFE_INTEGER + 1, 0, 0, true),
            (min, -MAX_SAFE_INTEGER - 1, 0, 0, true),
            (min, -MAX_SAFE_INTEGER - 1, 0, 1, false),
            // Fractions lie strictly between their integers.
            (half, 0, 0, 0, true),
            (half, 1, 0, 0, true),
            (half, 1, 1, 0, false),
            (half, 0, 0, 1, false),
        ] {
            assert_eq!(
                iat_outside_window(&iat, now, max_age, leeway),
                outside,
                "iat {}, now {now}, max_age {max_age}, leeway {leeway}",
                iat.as_f64()
            );
        }
    }

    #[test]
    fn the_clock_is_read_once_and_only_for_a_time_check() {
        // ADR 0028: no read without a time check (PanicClock above), and
        // one read however many checks run.
        let clock = CountingClock(1000, AtomicUsize::new(0));
        let p = Policy::new(&clock, ES256).unwrap().max_age(300);
        let mut c = Claims::new();
        c.exp = date(2000);
        c.nbf = date(900);
        c.iat = date(950);
        assert_eq!(validate_claims(&c, &p), Ok(()));
        assert_eq!(clock.1.load(AtomicOrdering::Relaxed), 1);

        // Each time claim alone needs one read.
        for claim in ["exp", "nbf", "iat"] {
            let clock = CountingClock(1000, AtomicUsize::new(0));
            let p = Policy::new(&clock, ES256).unwrap().allow_missing_exp();
            let mut c = Claims::new();
            let p = match claim {
                "exp" => {
                    c.exp = date(2000);
                    p
                }
                "nbf" => {
                    c.nbf = date(900);
                    p
                }
                _ => {
                    c.iat = date(950);
                    p.max_age(300)
                }
            };
            assert_eq!(validate_claims(&c, &p), Ok(()), "{claim}");
            assert_eq!(clock.1.load(AtomicOrdering::Relaxed), 1, "{claim}");
        }
    }

    #[test]
    fn a_clock_out_of_range_fails_the_first_time_check() {
        // ADR 0028 §1: InvalidClaim("clock"), never a panic.
        let clock = FixedClock(MAX_SAFE_INTEGER + 1);
        let p = Policy::new(&clock, ES256).unwrap();
        let mut c = Claims::new();
        c.exp = date(1000);
        assert_eq!(validate_claims(&c, &p), Err(Error::InvalidClaim("clock")));

        let p = Policy::new(&clock, ES256).unwrap().allow_missing_exp();
        let mut c = Claims::new();
        c.nbf = date(1000);
        assert_eq!(validate_claims(&c, &p), Err(Error::InvalidClaim("clock")));

        let p = p.max_age(300);
        let mut c = Claims::new();
        c.iat = date(1000);
        assert_eq!(validate_claims(&c, &p), Err(Error::InvalidClaim("clock")));

        // Presence (J4) runs first; without a time check the clock is not
        // read at all.
        let p = Policy::new(&clock, ES256).unwrap();
        assert_eq!(
            validate_claims(&Claims::new(), &p),
            Err(Error::InvalidClaim("exp"))
        );
        let p = p.allow_missing_exp();
        assert_eq!(validate_claims(&Claims::new(), &p), Ok(()));
    }

    fn many(values: &[&str]) -> Option<Audience> {
        Some(Audience::Many(
            values.iter().map(|v| (*v).to_owned()).collect(),
        ))
    }

    fn one(value: &str) -> Option<Audience> {
        Some(Audience::One(value.to_owned()))
    }

    #[test]
    fn iss_must_equal_an_accepted_issuer_exactly() {
        // RFC 7519 §4.1.1, §7.3 (case-sensitive, no normalization);
        // RFC 8725 §3.8; ADR 0027 §4. No time claim: the clock is unread.
        let p = untimed()
            .allow_missing_exp()
            .issuers(&["https://a", "https://b"]);
        for (iss, expected) in [
            (Some("https://b"), Ok(())),
            (Some("https://a"), Ok(())),
            (Some("https://B"), Err(Error::InvalidClaim("iss"))),
            (Some("https://b/"), Err(Error::InvalidClaim("iss"))),
            (Some("https://c"), Err(Error::InvalidClaim("iss"))),
            (Some(""), Err(Error::InvalidClaim("iss"))),
            (None, Err(Error::InvalidClaim("iss"))),
        ] {
            let mut c = Claims::new();
            c.iss = iss.map(str::to_owned);
            assert_eq!(validate_claims(&c, &p), expected, "{iss:?}");
        }
        // No accepted issuer: `iss` is not checked.
        let p = untimed().allow_missing_exp();
        for iss in [Some("https://anyone"), None] {
            let mut c = Claims::new();
            c.iss = iss.map(str::to_owned);
            assert_eq!(validate_claims(&c, &p), Ok(()), "{iss:?}");
        }
    }

    #[test]
    fn sub_must_equal_the_expected_subject_exactly() {
        // RFC 7519 §4.1.2, §7.3; ADR 0027 §4.
        let p = untimed().allow_missing_exp().subject("alice");
        for (sub, expected) in [
            (Some("alice"), Ok(())),
            (Some("Alice"), Err(Error::InvalidClaim("sub"))),
            (Some("alice "), Err(Error::InvalidClaim("sub"))),
            (None, Err(Error::InvalidClaim("sub"))),
        ] {
            let mut c = Claims::new();
            c.sub = sub.map(str::to_owned);
            assert_eq!(validate_claims(&c, &p), expected, "{sub:?}");
        }
        let mut c = Claims::new();
        c.sub = Some("bob".into());
        assert_eq!(validate_claims(&c, &untimed().allow_missing_exp()), Ok(()));
    }

    #[test]
    fn aud_must_contain_an_accepted_audience() {
        // RFC 7519 §4.1.3: string or array, any-of, case-sensitive; an
        // empty array matches nothing (ADR 0027 §4).
        const BAD: Result<()> = Err(Error::InvalidClaim("aud"));
        let api = untimed().allow_missing_exp().audience("api");
        let api_web = untimed().allow_missing_exp().audiences(&["api", "web"]);
        for (p, aud, expected) in [
            (&api, one("api"), Ok(())),
            (&api, many(&["x", "api"]), Ok(())),
            (&api, many(&["api"]), Ok(())),
            (&api, many(&["x"]), BAD),
            (&api, many(&[]), BAD),
            (&api, None, BAD),
            (&api, one("API"), BAD),
            (&api, one("x"), BAD),
            (&api, many(&["API", "ap"]), BAD),
            (&api_web, many(&["web"]), Ok(())),
            (&api_web, one("web"), Ok(())),
            (&api_web, many(&["x", "y"]), BAD),
        ] {
            let mut c = Claims::new();
            c.aud = aud.clone();
            assert_eq!(validate_claims(&c, p), expected, "{aud:?}");
        }
    }

    #[test]
    fn aud_without_a_configured_audience() {
        // RFC 7519 §4.1.3: "the JWT MUST be rejected" when the recipient
        // does not identify itself with a present `aud`, unless the caller
        // explicitly opts out (ADR 0027 §4, RFC 8725 §3.9).
        let strict = untimed().allow_missing_exp();
        let ignoring = untimed().allow_missing_exp().ignore_audience();
        for (aud, strict_expected) in [
            (None, Ok(())),
            (one("api"), Err(Error::InvalidClaim("aud"))),
            (many(&[]), Err(Error::InvalidClaim("aud"))),
            (many(&["api", "web"]), Err(Error::InvalidClaim("aud"))),
        ] {
            let mut c = Claims::new();
            c.aud = aud.clone();
            assert_eq!(validate_claims(&c, &strict), strict_expected, "{aud:?}");
            assert_eq!(validate_claims(&c, &ignoring), Ok(()), "{aud:?}");
        }
        // `ignore_audience` has no effect once an audience is configured.
        let configured = untimed()
            .allow_missing_exp()
            .ignore_audience()
            .audience("api");
        for aud in [one("x"), many(&[]), None] {
            let mut c = Claims::new();
            c.aud = aud.clone();
            assert_eq!(
                validate_claims(&c, &configured),
                Err(Error::InvalidClaim("aud")),
                "{aud:?}"
            );
        }
    }

    #[test]
    fn access_token_policy_requires_the_rfc_9068_claims() {
        // RFC 9068 §2.2: iss, exp, aud, sub, client_id, iat, jti REQUIRED;
        // §4: iss and aud checked.
        let now = 1_300_819_380;
        let clock = FixedClock(now);
        let p = Policy::access_token(&clock, ES256, &["https://as"], &["https://rs"]).unwrap();
        let mut c = Claims::new();
        c.iss = Some("https://as".into());
        c.exp = date(now + 300);
        c.aud = one("https://rs");
        c.sub = Some("5ba552d67".into());
        c.iat = date(now - 10);
        c.insert("client_id", "s6BhdRkqt3").unwrap();
        assert_eq!(validate_claims(&c, &p), Err(Error::InvalidClaim("jti")));
        c.jti = Some("dbe39bf3a3ba4238a513f51d6e1691c4".into());
        assert_eq!(validate_claims(&c, &p), Ok(()));
        // Each of the seven missing in turn is InvalidClaim.
        for name in ["iss", "exp", "aud", "sub", "iat", "jti"] {
            let mut missing = c.clone();
            match name {
                "iss" => missing.iss = None,
                "exp" => missing.exp = None,
                "aud" => missing.aud = None,
                "sub" => missing.sub = None,
                "iat" => missing.iat = None,
                _ => missing.jti = None,
            }
            assert_eq!(
                validate_claims(&missing, &p),
                Err(Error::InvalidClaim(name)),
                "{name}"
            );
        }
        let mut without_client = Claims::new();
        without_client.iss = c.iss.clone();
        without_client.exp = c.exp;
        without_client.aud = c.aud.clone();
        without_client.sub = c.sub.clone();
        without_client.iat = c.iat;
        without_client.jti = c.jti.clone();
        assert_eq!(
            validate_claims(&without_client, &p),
            Err(Error::InvalidClaim("client_id"))
        );
        // The issuer and audience are checked, not only present.
        let mut wrong = c.clone();
        wrong.iss = Some("https://other".into());
        assert_eq!(validate_claims(&wrong, &p), Err(Error::InvalidClaim("iss")));
        let mut wrong = c;
        wrong.aud = one("https://other");
        assert_eq!(validate_claims(&wrong, &p), Err(Error::InvalidClaim("aud")));
    }

    /// Every RFC 9068 §2.2 claim, valid for
    /// `Policy::access_token(.., &["https://as"], &["https://rs"])` at
    /// `now`, with `client_id` set to `client_id`.
    fn access_token_claims(now: i64, client_id: Value) -> Claims {
        let mut c = Claims::new();
        c.iss = Some("https://as".into());
        c.exp = date(now + 300);
        c.aud = one("https://rs");
        c.sub = Some("5ba552d67".into());
        c.iat = date(now - 10);
        c.jti = Some("dbe39bf3a3ba4238a513f51d6e1691c4".into());
        c.insert("client_id", client_id).unwrap();
        c
    }

    /// The JSON values that are not strings, one per RFC 8259 §3 type.
    fn non_strings() -> [Value; 5] {
        let mut object = Object::new();
        object.insert("id", "s6BhdRkqt3");
        [
            Value::Null,
            Value::Number(Number::from_i64(5).unwrap()),
            Value::Bool(true),
            Value::from(vec![Value::from("a")]),
            Value::from(object),
        ]
    }

    #[test]
    fn access_token_policy_requires_client_id_to_be_a_string() {
        // ADR 0052 §1: RFC 9068 §2.2 → RFC 8693 §4.3 → RFC 6749 §2.2 (the
        // client identifier is "a unique string"). Any string passes,
        // the empty one included; every other JSON type fails.
        let now = 1_300_819_380;
        let clock = FixedClock(now);
        let p = Policy::access_token(&clock, ES256, &["https://as"], &["https://rs"]).unwrap();
        for id in ["s6BhdRkqt3", ""] {
            assert_eq!(
                validate_claims(&access_token_claims(now, Value::from(id)), &p),
                Ok(()),
                "{id:?}"
            );
        }
        for value in non_strings() {
            assert_eq!(
                validate_claims(&access_token_claims(now, value.clone()), &p),
                Err(Error::InvalidClaim("client_id")),
                "{value:?}"
            );
        }
    }

    #[test]
    fn non_string_client_id_fails_at_its_j4_position() {
        // ADR 0052 §2, ADR 0027 §9: the string check is part of J4,
        // after the registered claims and before every later step, so
        // the clock is never read for it (ADR 0028).
        let now = ORDER_NOW;
        let p = Policy::access_token(&PanicClock, ES256, &["https://as"], &["https://rs"]).unwrap();
        for value in non_strings() {
            // A registered claim missing too: it is reported first.
            let mut c = access_token_claims(now, value.clone());
            c.jti = None;
            assert_eq!(
                validate_claims(&c, &p),
                Err(Error::InvalidClaim("jti")),
                "{value:?}"
            );
            // Expired, not yet valid, wrong issuer, subject and audience
            // as well: J4 still decides, before any clock read.
            let mut c = access_token_claims(now, value.clone());
            c.exp = date(now - 3600);
            c.nbf = date(now + 3600);
            c.iss = Some("https://evil".into());
            c.aud = one("https://other");
            assert_eq!(
                validate_claims(&c, &p),
                Err(Error::InvalidClaim("client_id")),
                "{value:?}"
            );
        }
        // Among the caller's other names, `client_id` keeps its place:
        // first required, so checked before a later `x-tenant`.
        let p = p.require("x-tenant");
        let c = access_token_claims(now, Value::Null);
        assert_eq!(
            validate_claims(&c, &p),
            Err(Error::InvalidClaim("client_id"))
        );
    }

    #[test]
    fn builder_calls_after_the_profile_keep_the_string_rule() {
        // ADR 0052 §4: no opt-out.
        let now = 1_300_819_380;
        let clock = FixedClock(now);
        let p = Policy::access_token(&clock, ES256, &["https://as"], &["https://rs"])
            .unwrap()
            .require("client_id")
            .any_typ()
            .leeway(0)
            .unwrap();
        assert_eq!(
            validate_claims(&access_token_claims(now, Value::Null), &p),
            Err(Error::InvalidClaim("client_id"))
        );
    }

    #[test]
    fn plain_require_client_id_keeps_any_json_type() {
        // ADR 0052 §3: the string rule belongs to the profile, not the
        // name; a `Policy::new` policy with the same claims and
        // requirements accepts every type (ADR 0027 §4).
        let now = 1_300_819_380;
        let clock = FixedClock(now);
        let p = Policy::new(&clock, ES256)
            .unwrap()
            .issuer("https://as")
            .audience("https://rs")
            .expect_typ("at+jwt");
        let p = ACCESS_TOKEN_REQUIRED_CLAIMS
            .iter()
            .fold(p, |p, claim| p.require(claim));
        for value in non_strings() {
            assert_eq!(
                validate_claims(&access_token_claims(now, value.clone()), &p),
                Ok(()),
                "{value:?}"
            );
        }
    }

    /// The time of the ordering tests.
    const ORDER_NOW: i64 = 1_300_819_380;

    /// A policy that configures every J4–J10 check.
    fn order_policy(clock: &dyn Clock) -> Policy<'_> {
        Policy::new(clock, ES256)
            .unwrap()
            .issuer("https://as")
            .subject("alice")
            .audience("api")
            .max_age(300)
            .require("client_id")
    }

    /// The J4–J10 steps, each with a mutation that makes only that step
    /// fail under [`order_policy`], and the error it then reports.
    const STEPS: [(&str, Error); 7] = [
        ("J4", Error::InvalidClaim("client_id")),
        ("J5", Error::TokenExpired),
        ("J6", Error::TokenNotYetValid),
        ("J7", Error::InvalidClaim("iat")),
        ("J8", Error::InvalidClaim("iss")),
        ("J9", Error::InvalidClaim("sub")),
        ("J10", Error::InvalidClaim("aud")),
    ];

    /// A claim set passing [`order_policy`] at [`ORDER_NOW`], except for
    /// the steps whose bit is set in `broken` (bit i is `STEPS[i]`).
    fn order_claims(broken: u8) -> Claims {
        let fails = |step: usize| broken & (1 << step) != 0;
        let now = ORDER_NOW;
        let mut c = Claims::new();
        if !fails(0) {
            c.insert("client_id", "s6BhdRkqt3").unwrap();
        }
        c.exp = date(if fails(1) { now - 120 } else { now + 300 });
        c.nbf = date(if fails(2) { now + 120 } else { now - 10 });
        c.iat = date(if fails(3) { now - 1000 } else { now - 10 });
        c.iss = Some(
            if fails(4) {
                "https://evil"
            } else {
                "https://as"
            }
            .into(),
        );
        c.sub = Some(if fails(5) { "mallory" } else { "alice" }.into());
        c.aud = one(if fails(6) { "other" } else { "api" });
        c
    }

    #[test]
    fn the_first_failing_step_decides_for_every_combination() {
        // ADR 0027 §9: J4 → J10 in order, the first failure decides. Every
        // subset of the seven steps, so every pair (asserted to be 21) and
        // every larger combination.
        let clock = FixedClock(ORDER_NOW);
        let p = order_policy(&clock);
        let mut pairs = 0;
        for broken in 0..(1_u8 << STEPS.len()) {
            let expected = STEPS
                .iter()
                .enumerate()
                .find(|(i, _)| broken & (1 << i) != 0)
                .map(|(_, (_, error))| error.clone());
            let names: Vec<&str> = STEPS
                .iter()
                .enumerate()
                .filter(|(i, _)| broken & (1 << i) != 0)
                .map(|(_, (name, _))| *name)
                .collect();
            assert_eq!(
                validate_claims(&order_claims(broken), &p).err(),
                expected,
                "failing steps {names:?}"
            );
            if names.len() == 2 {
                pairs += 1;
            }
            // Presence (J4) never needs the time.
            if broken & 1 != 0 {
                assert_eq!(
                    validate_claims(&order_claims(broken), &order_policy(&PanicClock)).err(),
                    expected,
                    "failing steps {names:?}, unread clock"
                );
            }
        }
        assert_eq!(pairs, 21);
    }

    #[test]
    fn named_ordering_cases_of_adr_0027_section_9() {
        let clock = FixedClock(ORDER_NOW);
        let p = Policy::new(&clock, ES256)
            .unwrap()
            .issuer("https://as")
            .audience("api");

        // Expired, wrong issuer and wrong audience → the time check wins.
        let mut c = Claims::new();
        c.exp = date(ORDER_NOW - 3600);
        c.iss = Some("https://evil".into());
        c.aud = one("other");
        assert_eq!(validate_claims(&c, &p), Err(Error::TokenExpired));

        // Not yet valid and wrong audience → TokenNotYetValid.
        let mut c = Claims::new();
        c.exp = date(ORDER_NOW + 3600);
        c.nbf = date(ORDER_NOW + 600);
        c.iss = Some("https://as".into());
        c.aud = many(&["other"]);
        assert_eq!(validate_claims(&c, &p), Err(Error::TokenNotYetValid));

        // Missing `exp` and an `nbf` that would fail → presence first,
        // before the clock is read.
        let mut c = Claims::new();
        c.nbf = date(ORDER_NOW + 600);
        c.iss = Some("https://as".into());
        c.aud = one("api");
        assert_eq!(validate_claims(&c, &p), Err(Error::InvalidClaim("exp")));
        let untimed = untimed().issuer("https://as").audience("api");
        assert_eq!(
            validate_claims(&c, &untimed),
            Err(Error::InvalidClaim("exp"))
        );

        // An unconfigured `aud` is the last check: an expired token that
        // also carries one is TokenExpired.
        let p = Policy::new(&clock, ES256).unwrap();
        let mut c = Claims::new();
        c.exp = date(ORDER_NOW - 3600);
        c.aud = one("api");
        assert_eq!(validate_claims(&c, &p), Err(Error::TokenExpired));
        c.exp = date(ORDER_NOW + 3600);
        assert_eq!(validate_claims(&c, &p), Err(Error::InvalidClaim("aud")));
    }

    #[test]
    fn extreme_clock_and_settings_never_overflow_or_panic() {
        // ADR 0027 §3, ADR 0028 §1: at now = ±(2^53 − 1), with the largest
        // leeway and max_age u32::MAX, each bound is exact.
        for now in [MAX_SAFE_INTEGER, -MAX_SAFE_INTEGER] {
            let clock = FixedClock(now);
            let p = timed(&clock, Policy::MAX_LEEWAY).max_age(u32::MAX);
            let mut c = Claims::new();
            c.exp = date(MAX_SAFE_INTEGER);
            c.nbf = date(-MAX_SAFE_INTEGER);
            // The window is [now − u32::MAX − 600, now + 600]; the
            // date range's own edges decide.
            for (iat, expected) in [
                (now, Ok(())),
                (now + 600, Ok(())),
                (now - i64::from(u32::MAX) - 600, Ok(())),
                (now + 601, Err(Error::InvalidClaim("iat"))),
                (
                    now - i64::from(u32::MAX) - 601,
                    Err(Error::InvalidClaim("iat")),
                ),
            ] {
                c.iat = date(iat);
                let expected = match (iat.abs() > MAX_SAFE_INTEGER, expected) {
                    // Not a NumericDate: `date` gave None, so `iat` is absent.
                    (true, _) => Err(Error::InvalidClaim("iat")),
                    (false, e) => e,
                };
                let got = validate_claims(&c, &p);
                assert_eq!(got, expected, "now {now}, iat {iat}");
            }
        }
        // A fraction just beyond the leeway.
        let clock = FixedClock(1_000_000);
        let p = timed(&clock, 60).max_age(u32::MAX);
        let mut c = Claims::new();
        c.exp = date(2_000_000);
        c.iat = NumericDate::from_f64(1_000_060.5);
        assert_eq!(validate_claims(&c, &p), Err(Error::InvalidClaim("iat")));
        c.iat = NumericDate::from_f64(1_000_060.0);
        assert_eq!(validate_claims(&c, &p), Ok(()));
        // exp/nbf at the edges of the clock range.
        let clock = FixedClock(MAX_SAFE_INTEGER);
        let p = timed(&clock, 0);
        let mut c = Claims::new();
        c.exp = date(MAX_SAFE_INTEGER);
        assert_eq!(validate_claims(&c, &p), Err(Error::TokenExpired));
        let clock = FixedClock(-MAX_SAFE_INTEGER);
        let p = timed(&clock, 0).allow_missing_exp();
        let mut c = Claims::new();
        c.nbf = date(-MAX_SAFE_INTEGER);
        assert_eq!(validate_claims(&c, &p), Ok(()));
        c.nbf = date(-MAX_SAFE_INTEGER + 1);
        assert_eq!(validate_claims(&c, &p), Err(Error::TokenNotYetValid));
        let clock = FixedClock(-MAX_SAFE_INTEGER - 1);
        let p = timed(&clock, 0).allow_missing_exp();
        assert_eq!(validate_claims(&c, &p), Err(Error::InvalidClaim("clock")));
    }

    #[test]
    fn duplicate_audiences_change_nothing() {
        // RFC 7519 §4.1.3: any-of. Duplicates in the token or the policy
        // neither help nor hurt.
        let policy_twice = untimed()
            .allow_missing_exp()
            .audience("api")
            .audience("api");
        let policy_once = untimed().allow_missing_exp().audience("api");
        for (aud, expected) in [
            (many(&["api", "api"]), Ok(())),
            (many(&["x", "x"]), Err(Error::InvalidClaim("aud"))),
            (one("api"), Ok(())),
            (one("x"), Err(Error::InvalidClaim("aud"))),
        ] {
            let mut c = Claims::new();
            c.aud = aud.clone();
            assert_eq!(validate_claims(&c, &policy_twice), expected, "{aud:?}");
            assert_eq!(validate_claims(&c, &policy_once), expected, "{aud:?}");
        }
    }

    #[test]
    fn error_details_never_echo_claim_values_or_caller_names() {
        // ADR 0027 §9: details name a claim, never a value.
        let clock = FixedClock(ORDER_NOW);
        let secret = "SECRET-VALUE-9f3a";
        let mut c = Claims::new();
        c.iss = Some(secret.into());
        c.sub = Some(secret.into());
        c.aud = one(secret);
        c.exp = date(ORDER_NOW + 100);
        c.insert("x-custom", secret).unwrap();
        let policies = [
            timed(&clock, 0).issuer("https://as"),
            timed(&clock, 0).subject("alice"),
            timed(&clock, 0).audience("api"),
            timed(&clock, 0),
            timed(&clock, 0).require("SECRET-NAME-77"),
            timed(&clock, 0).require("jti"),
        ];
        let mut failed = 0;
        for p in &policies {
            if let Err(e) = validate_claims(&c, p) {
                failed += 1;
                for text in [format!("{e}"), format!("{e:?}")] {
                    assert!(!text.contains("SECRET"), "{text}");
                }
            }
        }
        assert_eq!(failed, 6);
        // Expired / not yet valid carry nothing at all.
        c.exp = date(ORDER_NOW - 100);
        let e = validate_claims(&c, &timed(&clock, 0)).unwrap_err();
        assert_eq!(e, Error::TokenExpired);
    }

    #[test]
    fn required_exp_wins_over_allow_missing_exp_in_either_order() {
        // Recorded behaviour: an explicit require("exp") is not undone by
        // allow_missing_exp (policy.rs docs), whichever is called first.
        let a = untimed().require("exp").allow_missing_exp();
        let b = untimed().allow_missing_exp().require("exp");
        for p in [&a, &b] {
            assert_eq!(
                validate_claims(&Claims::new(), p),
                Err(Error::InvalidClaim("exp"))
            );
        }
    }
}