axiam-sdk 1.2.2

Official Rust client SDK for AXIAM IAM
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
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
//! Local JWKS fetch/cache/verification (D-03/D-11).
//!
//! Mirrors `crates/axiam-federation/src/oidc.rs:370-429,600-657` — the
//! server's own proven EdDSA/JWKS verification pattern — applied here by
//! the SDK to AXIAM's own tokens. This module does **not** import any
//! `axiam-*` server crate; every type below is the SDK's own plain
//! equivalent (CONTEXT.md domain boundary, 16-PATTERNS.md).
//!
//! Endpoint: `GET {base_url}/oauth2/jwks` — a single, organization-wide
//! endpoint. This is NOT the common OIDC discovery-style JWKS path some
//! other IdPs serve, and it is NOT tenant-scoped.

#[cfg(any(feature = "rest", feature = "actix"))]
use crate::time::{Duration, Instant};
#[cfg(any(feature = "rest", feature = "actix"))]
use std::sync::RwLock;

#[cfg(any(feature = "rest", feature = "actix"))]
use jsonwebtoken::jwk::JwkSet;
#[cfg(any(feature = "rest", feature = "actix"))]
use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header};
use serde::{Deserialize, Serialize};

// Unconditional: `Claims::verify_certificate_binding` (CONTRACT.md §10.1
// rule 9) returns this and is deliberately available with no features, so a
// `--no-default-features` consumer can apply the rule to a token it obtained
// through its own transport.
use crate::AxiamError;
#[cfg(any(feature = "rest", feature = "actix"))]
use crate::client::OmitBrowserCredentials;

/// The AXIAM JWKS endpoint path — organization-wide, not tenant-scoped
/// (RESEARCH.md D-11). This is the only correct path; do not substitute a
/// generic OIDC discovery-style JWKS path here.
pub const JWKS_PATH: &str = "/oauth2/jwks";

/// How long a fetched `JwkSet` is cached before a normal (non-forced)
/// refetch is attempted. Five minutes, inside the ten §34.2 P6 allows the
/// SSF key cache (contract 1.60).
#[cfg(any(feature = "rest", feature = "actix"))]
const JWKS_CACHE_TTL: Duration = Duration::from_secs(300);

/// After a failed fetch, how long a verifier built with
/// [`JwksVerifier::limiting_failed_fetches`] makes no other (§34.2 P6: a failed
/// fill, a failed refresh of an expired cache and a failed unknown-`kid`
/// refetch each count toward the once-a-minute limit, so that a JWKS outage
/// is not one fetch per SET).
#[cfg(any(feature = "rest", feature = "actix"))]
pub(crate) const FAILED_FETCH_MIN_INTERVAL: Duration = Duration::from_secs(60);

/// Minimum interval between forced refetches triggered by an unknown `kid`,
/// to avoid a hostile/rotating token stream hammering the JWKS endpoint.
#[cfg(any(feature = "rest", feature = "actix"))]
const FORCED_REFETCH_MIN_INTERVAL: Duration = Duration::from_secs(60);

/// Clock-skew leeway applied to the `exp` and `nbf` checks (CONTRACT.md
/// §10.1 rule 7).
///
/// A **named, bounded, non-configurable** constant, deliberately fixed at the
/// contract's RECOMMENDED 60 seconds: rule 7 forbids both an inline literal
/// and an operator-settable value that could be widened to something
/// unbounded. There is no setter for it anywhere in this SDK — widening the
/// window is a source change, reviewable as such.
#[cfg(any(feature = "rest", feature = "actix"))]
pub const CLOCK_SKEW_LEEWAY_SECS: u64 = 60;

/// The SDK's own plain claims struct, matching the field names AXIAM issues
/// in its access tokens (`crates/axiam-auth/src/token.rs::AccessTokenClaims`)
/// — mirrored, not imported.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Claims {
    /// Subject — user ID (UUID string).
    pub sub: String,
    /// Tenant ID (UUID string).
    pub tenant_id: String,
    /// Organization ID (UUID string).
    #[serde(default)]
    pub org_id: Option<String>,
    /// Issuer.
    pub iss: String,
    /// Issued-at (Unix timestamp).
    #[serde(default)]
    pub iat: Option<i64>,
    /// Expiration (Unix timestamp).
    pub exp: i64,
    /// Unique token ID / session id.
    #[serde(default)]
    pub jti: Option<String>,
    /// The AXIAM session this token descends from (AXIAM T-249).
    ///
    /// Present on tokens minted by the authorization-code and refresh grants;
    /// absent on a client-credentials token, an RPT or a token exchange, which
    /// have no session behind them.
    ///
    /// Read **only** by the §10.4 revocation feed, and deliberately with no
    /// fallback to [`Self::jti`]: a token with no `sid` names no session, and
    /// hashing its `jti` instead would match nothing while looking like it
    /// worked.
    #[serde(default)]
    pub sid: Option<String>,
    /// Token audience — `"axiam:user"` or `"axiam:m2m"`.
    #[serde(default)]
    pub aud: Option<String>,
    /// OAuth2 scopes (space-separated string), if any.
    #[serde(default)]
    pub scope: Option<String>,
    /// RFC 7800 / RFC 8705 §3.1 confirmation claim — present **only** on a
    /// sender-constrained token (CONTRACT.md §10.1 rule 9, contract 1.15).
    ///
    /// Its presence changes what the token *is*. A token without `cnf` is a
    /// bearer credential: whoever holds it may use it. A token with `cnf`
    /// names a key, and accepting it without proving the caller holds that key
    /// converts it back into a bearer token — discarding the whole protection
    /// the operator turned on.
    ///
    /// [`JwksVerifier::verify`] does **not** check it, because it cannot: the
    /// check needs the client certificate for *this connection*, which a
    /// claims-only API has no access to. Use
    /// [`JwksVerifier::verify_sender_constrained`], or call
    /// [`Claims::verify_certificate_binding`] yourself with the thumbprint your
    /// transport gives you.
    #[serde(default)]
    pub cnf: Option<CnfClaim>,
}

/// RFC 7800 confirmation claim.
///
/// Deliberately a struct with one optional field rather than an enum: RFC 7800
/// permits confirmation methods this SDK does not implement, and such a token
/// must still *decode* — what it must not do is validate. See
/// [`Self::certificate_thumbprint`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CnfClaim {
    /// RFC 8705 §3.1 `x5t#S256` — base64url (unpadded) SHA-256 of the DER
    /// client certificate the token was issued to.
    #[serde(rename = "x5t#S256", default, skip_serializing_if = "Option::is_none")]
    pub x5t_s256: Option<String>,
    /// RFC 9449 §6.1 `jkt` — base64url (unpadded) RFC 7638 thumbprint of the
    /// DPoP public key the token was issued to (contract 1.16).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub jkt: Option<String>,
}

impl CnfClaim {
    /// The certificate thumbprint this token is bound to, or `None` when the
    /// confirmation names some other method.
    ///
    /// A caller that gets `None` from a claim that *exists* is looking at a
    /// constraint it cannot check and MUST reject the token. It must never
    /// read that as "unconstrained".
    pub fn certificate_thumbprint(&self) -> Option<&str> {
        self.x5t_s256.as_deref()
    }

    /// The DPoP key thumbprint this token is bound to, or `None` when the
    /// confirmation does not name one (contract 1.16).
    pub fn dpop_thumbprint(&self) -> Option<&str> {
        self.jkt.as_deref()
    }

    /// Whether this confirmation names **no** method this SDK understands.
    ///
    /// A `cnf` that exists but names nothing checkable is the case rule 9 is
    /// most often got wrong: it is an *unverifiable constraint*, never *no
    /// constraint*, and it must be refused. Over gRPC it is also the shape an
    /// empty `CnfClaim` message arrives in, because proto3 cannot distinguish
    /// an absent string from an empty one (§10.3 rule 3).
    pub fn names_nothing_checkable(&self) -> bool {
        self.certificate_thumbprint().is_none() && self.dpop_thumbprint().is_none()
    }
}

/// The proofs a caller can present for a sender-constrained token
/// (contract 1.16, CONTRACT.md §10.1 rule 9).
///
/// Both fields are `Option` because a caller may hold one, both, or neither —
/// and "neither" is a legitimate thing to pass for an ordinary bearer token,
/// which is why [`Claims::verify_token_binding`] accepts it and returns `Ok`
/// when the token names no confirmation.
///
/// # Every thumbprint must come from the transport
///
/// Take the certificate thumbprint from the TLS peer certificate (or from a
/// trusted terminating proxy over a channel your application controls), and
/// the DPoP thumbprint from a proof **you have already verified** against this
/// request's method and URI. Never from a request header the caller can set:
/// a forgeable input makes the whole mechanism decorative.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PresentedProofs<'a> {
    /// RFC 8705 §3.1 `x5t#S256` of the peer certificate on this connection.
    pub certificate_thumbprint: Option<&'a str>,
    /// RFC 9449 §6.1 `jkt` of the key that signed a DPoP proof **this SDK has
    /// already verified** for this request's `htm`/`htu`.
    ///
    /// Passing a thumbprint here asserts the proof checked out. Passing the
    /// `jkt` off an unverified proof would let any captured proof authorize
    /// any request.
    pub dpop_thumbprint: Option<&'a str>,
}

impl Claims {
    /// CONTRACT.md §10.1 rule 9 — enforce this token's sender constraint
    /// against the certificate the caller presented on **this** connection.
    ///
    /// `presented_thumbprint` is the RFC 8705 §3.1 `x5t#S256` of the peer
    /// certificate: base64url, **unpadded**, SHA-256 over the **DER** encoding.
    /// [`certificate_thumbprint_s256`] computes it from DER bytes.
    ///
    /// This is the **narrow** entry point, kept for callers whose transport can
    /// only ever produce a certificate thumbprint. It refuses a DPoP-bound
    /// token outright rather than ignoring the `jkt` it cannot check — see
    /// [`Claims::verify_token_binding`] for the full rule.
    ///
    /// # The five cases
    ///
    /// | this token's `cnf` | `presented_thumbprint` | result |
    /// |---|---|---|
    /// | absent | anything | `Ok` — an ordinary bearer token |
    /// | `x5t#S256` | equal | `Ok` |
    /// | `x5t#S256` | different, or `None` | `Err` |
    /// | names `jkt` (contract 1.16) | anything | `Err` — **this** function cannot check a DPoP proof |
    /// | present, names neither | anything | `Err` |
    ///
    /// The first row is why a guard that adopts this rule does not break
    /// existing deployments: an unbound token is still accepted whether or not
    /// a certificate is present. The last two are the ones that are easy to get
    /// wrong — a `cnf` naming a method this SDK cannot check *here* is an
    /// *unverifiable constraint*, never *no constraint*.
    ///
    /// # The thumbprint must come from the transport
    ///
    /// Take it from the TLS peer certificate, or from a value a **trusted**
    /// terminating proxy forwarded over a channel your application controls.
    /// Never from a request header the caller can set: a forgeable input makes
    /// the whole mechanism decorative.
    ///
    /// # Errors
    ///
    /// [`AxiamError::Auth`] on any of the three rejecting rows.
    pub fn verify_certificate_binding(
        &self,
        presented_thumbprint: Option<&str>,
    ) -> Result<(), AxiamError> {
        let Some(cnf) = self.cnf.as_ref() else {
            return Ok(());
        };

        let auth = |message: &str| AxiamError::Auth {
            message: message.to_owned(),
            oauth: None,
            reason: None,
            set_reason: None,
            retry_after: None,
        };

        let Some(expected) = cnf.certificate_thumbprint() else {
            // Includes the DPoP case: this function has no proof to check, so
            // a `jkt`-bound token is refused rather than silently downgraded.
            return Err(auth(
                "token carries a cnf confirmation naming a method this entry point cannot verify \
                 (CONTRACT.md §10.1 rule 9 — an unverifiable constraint is not an absent one; \
                 use verify_token_binding for DPoP)",
            ));
        };

        // A token naming BOTH methods is a conjunction (contract 1.16): this
        // function can only establish one half, so it must not answer for the
        // whole. Refusing here is what stops "check whichever we can".
        if cnf.dpop_thumbprint().is_some() {
            return Err(auth(
                "token names both a certificate and a DPoP key; both must hold \
                 (CONTRACT.md §10.1 rule 9) — use verify_token_binding",
            ));
        }

        let Some(presented) = presented_thumbprint else {
            return Err(auth(
                "token is certificate-bound but no client certificate was presented",
            ));
        };

        if constant_time_eq(expected.as_bytes(), presented.as_bytes()) {
            Ok(())
        } else {
            Err(auth(
                "token is bound to a different client certificate than the one presented",
            ))
        }
    }

    /// CONTRACT.md §10.1 rule 9 — enforce this token's sender constraint
    /// against **every** proof the caller presented (contract 1.16).
    ///
    /// This is the full rule, and the one to use unless your transport
    /// genuinely cannot produce a DPoP thumbprint.
    ///
    /// # The ten cases
    ///
    /// | this token's `cnf` | certificate | DPoP | result |
    /// |---|---|---|---|
    /// | absent | anything | anything | `Ok` — an ordinary bearer token |
    /// | `x5t#S256` | equal | ignored | `Ok` |
    /// | `x5t#S256` | different | ignored | `Err` |
    /// | `x5t#S256` | `None` | ignored | `Err` |
    /// | `jkt` | ignored | equal | `Ok` |
    /// | `jkt` | ignored | different | `Err` |
    /// | `jkt` | ignored | `None` | `Err` |
    /// | both | equal | equal | `Ok` — **conjunction** |
    /// | both | either wrong or missing | — | `Err` |
    /// | present, names neither | anything | anything | `Err` |
    ///
    /// Two rows carry the weight. **Both present is a conjunction**: an
    /// operator who turned on two constraints asked for two, and satisfying
    /// the more convenient one is not compliance. **Names neither is a
    /// refusal**: a confirmation this SDK cannot interpret is an unverifiable
    /// constraint, and reading it as "unconstrained" is the exact downgrade
    /// rule 9 exists to prevent.
    ///
    /// # The DPoP thumbprint must come from a *verified* proof
    ///
    /// This function compares thumbprints; it does not verify proofs. Supply
    /// `dpop_thumbprint` only after checking the proof's signature, `htm`,
    /// `htu`, `iat` and `jti` for **this** request. A thumbprint lifted from an
    /// unverified proof would let a proof captured from any other endpoint
    /// authorize this one.
    ///
    /// # Errors
    ///
    /// [`AxiamError::Auth`] on any rejecting row.
    pub fn verify_token_binding(&self, proofs: PresentedProofs<'_>) -> Result<(), AxiamError> {
        // The fast path, and the common one. Note it comes first: an unbound
        // token is accepted with no proofs at all, which is the property that
        // keeps existing deployments working.
        match self.cnf.as_ref() {
            None => Ok(()),
            Some(cnf) => cnf.verify(proofs),
        }
    }
}

impl CnfClaim {
    /// CONTRACT.md §10.1 rule 9 for a confirmation that is **present** — the
    /// table [`Claims::verify_token_binding`] documents, minus its first row.
    ///
    /// The one implementation of the rule. [`Claims::verify_token_binding`]
    /// applies it to a locally verified token, and the `grpc` feature's
    /// `TokenValidation::verify_possession` to the `cnf` the gRPC
    /// `TokenService` returned (§10.3 rule 1), so a local-verification caller
    /// and a gRPC-introspecting one cannot disagree about whether a token is a
    /// bearer token (§10.1 rule 9 detail 4).
    ///
    /// A confirmation naming neither member is refused — over gRPC that is an
    /// empty `CnfClaim` message, which §10.3 rule 3 says to refuse rather than
    /// read as unbound.
    ///
    /// # Errors
    ///
    /// [`AxiamError::Auth`] on any rejecting row.
    pub fn verify(&self, proofs: PresentedProofs<'_>) -> Result<(), AxiamError> {
        let cnf = self;
        let auth = |message: &str| AxiamError::Auth {
            message: message.to_owned(),
            oauth: None,
            reason: None,
            set_reason: None,
            retry_after: None,
        };

        if cnf.names_nothing_checkable() {
            return Err(auth(
                "token carries a cnf confirmation naming no method this SDK can verify \
                 (CONTRACT.md §10.1 rule 9 — an unverifiable constraint is not an absent one)",
            ));
        }

        // Each arm that applies must pass. Written as two independent checks
        // rather than a match on the pair precisely so that "both named" needs
        // no separate branch — it is simply the case where both run.
        if let Some(expected) = cnf.certificate_thumbprint() {
            let Some(presented) = proofs.certificate_thumbprint else {
                return Err(auth(
                    "token is certificate-bound but no client certificate was presented",
                ));
            };
            if !constant_time_eq(expected.as_bytes(), presented.as_bytes()) {
                return Err(auth(
                    "token is bound to a different client certificate than the one presented",
                ));
            }
        }

        if let Some(expected) = cnf.dpop_thumbprint() {
            let Some(presented) = proofs.dpop_thumbprint else {
                return Err(auth(
                    "token is DPoP-bound but no verified DPoP proof was presented",
                ));
            };
            if !constant_time_eq(expected.as_bytes(), presented.as_bytes()) {
                return Err(auth(
                    "token is bound to a different DPoP key than the one presented",
                ));
            }
        }

        Ok(())
    }
}

/// Constant-time byte comparison, hand-rolled so that
/// [`Claims::verify_certificate_binding`] stays available with **no features
/// enabled**.
///
/// `subtle` would be the natural choice, but it is an optional dependency of
/// this crate gated behind `rest`/`amqp`/`actix`, and rule 9 is pure claim
/// logic that a `--no-default-features` consumer must be able to apply to a
/// token it obtained some other way. Fifteen lines here beats making a
/// normative rule conditional on a feature flag.
///
/// The thumbprint is usually public — it derives from a certificate sent in
/// the clear during the handshake — so this is defence in depth. It matters
/// most for a self-signed client, where the registered thumbprint is the whole
/// credential.
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    // Length inequality short-circuits, leaking only the length. Both operands
    // are fixed-length base64url SHA-256 digests whenever either is well-formed.
    if a.len() != b.len() {
        return false;
    }
    let mut diff = 0u8;
    for (x, y) in a.iter().zip(b.iter()) {
        diff |= x ^ y;
    }
    diff == 0
}

/// Compute the RFC 8705 §3.1 `x5t#S256` thumbprint of a DER client
/// certificate: base64url-encoded SHA-256, **without** padding.
///
/// Unpadded is not a style choice — RFC 7515 §2 defines base64url in JOSE as
/// omitting `=`, and a padded value will not compare equal to what AXIAM put
/// in the token.
///
/// Feature-gated because it needs `sha2` and `base64`, which are optional here.
/// [`Claims::verify_certificate_binding`] deliberately is **not** gated: a
/// consumer that already has the thumbprint from its TLS stack (most do —
/// rustls, OpenSSL and Go's `crypto/tls` all expose the peer certificate) can
/// apply the rule without pulling either crate in.
#[cfg(any(feature = "rest", feature = "actix"))]
pub fn certificate_thumbprint_s256(der: &[u8]) -> String {
    use base64::Engine as _;
    use sha2::{Digest, Sha256};
    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(Sha256::digest(der))
}

#[cfg(any(feature = "rest", feature = "actix"))]
struct CachedJwks {
    jwks: JwkSet,
    fetched_at: Instant,
    last_forced_refetch: Option<Instant>,
}

/// Fetches, caches, and verifies AXIAM access tokens locally against the
/// organization-wide EdDSA JWKS.
///
/// **Feature gating note:** this type owns a `reqwest::Client` to perform
/// the JWKS fetch, so it is gated behind `any(feature = "rest", feature =
/// "actix")` to preserve 16-01's `cargo build --no-default-features`
/// invariant while also being available to 16-05's Actix `FromRequest`
/// extractor (which declares `actix = ["dep:actix-web", "rest"]`, so `rest`
/// is always active whenever `actix` is — this `any(...)` gate is kept for
/// clarity/documentation of the two call sites rather than strict
/// necessity).
///
/// ## CONTRACT.md §10.1 — minimum local-verification set
///
/// [`Self::verify`] is the SDK's **documented guard entry point** and applies
/// every rule of §10.1: EdDSA `alg` pinned before key lookup, a REQUIRED
/// numeric `exp`, `nbf` honoured when present, `tenant_id` asserted against
/// the tenant configured with [`Self::expect_tenant_id`] (failing closed when
/// either is absent), and `iss`/`aud` checked when — and only when —
/// [`Self::expect_issuer`]/[`Self::expect_audience`] were configured. A
/// verifier used as a §10 route guard **must** be given an expected tenant;
/// without one, `verify` rejects every token rather than accepting a token
/// minted for a sibling tenant under the same organization-wide JWKS.
///
/// [`Self::verify_signature_only_unchecked`] is the §10.1 "raw signature-only
/// primitive" escape hatch. It is deliberately *not* the guard entry point.
#[cfg(any(feature = "rest", feature = "actix"))]
pub struct JwksVerifier {
    http_client: reqwest::Client,
    jwks_url: url::Url,
    cache: RwLock<Option<CachedJwks>>,
    /// Serializes concurrent fetchers so a burst of cache-miss callers (e.g.
    /// an invalid-`kid` storm) collapses to exactly one network fetch
    /// (D-08/D-09). Guards ONLY the fetch — a coalescing wrapper, never the
    /// cryptographic verify path.
    fetch_lock: tokio::sync::Mutex<()>,
    /// §34.2 P6: whether a failed fetch counts toward the once-a-minute limit.
    /// Set for the SSF receiver only; the §10 guard and §12 ID-token paths
    /// retry a failed fetch on their next call, as they always have.
    limit_failed_fetches: bool,
    /// When the last fetch failed, while [`Self::limit_failed_fetches`] holds.
    last_failed_fetch: std::sync::Mutex<Option<Instant>>,
    /// §10.1 rule 4: the tenant every verified token MUST be scoped to.
    /// `None` means "not configured", which makes [`Self::verify`] fail
    /// closed — never "no tenant constraint".
    expected_tenant_id: Option<uuid::Uuid>,
    /// §10.1 rule 5: expected `iss`. `None` means the check is not performed
    /// (the rule is explicitly conditional on configuration).
    expected_issuer: Option<String>,
    /// §10.1 rule 6: expected `aud`. `None` means the check is not performed.
    expected_audience: Option<String>,
    /// §10.4 (contract 1.44): the optional revocation feed.
    ///
    /// `None` — the default — means the guard behaves exactly as it did before
    /// contract 1.44: a revoked session's access token verifies locally until
    /// it expires, which is the §10.2 posture this narrows rather than
    /// replaces.
    revocation_feed: Option<crate::token::revocation::RevocationFeed>,
    /// §28.5: the MCP resource-server metadata URL, when configured via
    /// [`Self::with_resource_metadata_url`]. `None` — the default — means
    /// §28 is off: [`crate::middleware::AxiamUser`] behaves byte-for-byte as
    /// it did before §28 existed (§28.5 rule 1).
    #[cfg(feature = "actix")]
    resource_metadata_url: Option<String>,
    /// The §28.4 challenge values precomputed by
    /// [`Self::with_resource_metadata_url`] — built once, at construction,
    /// so an invalid configuration is a startup failure rather than a
    /// surprise on the 401 path.
    #[cfg(feature = "actix")]
    mcp_challenges: Option<crate::middleware::mcp::McpChallenges>,
}

#[cfg(any(feature = "rest", feature = "actix"))]
impl JwksVerifier {
    /// Construct a verifier that will fetch `{base_url}/oauth2/jwks` lazily
    /// on first use.
    pub fn new(http_client: reqwest::Client, base_url: &url::Url) -> Result<Self, AxiamError> {
        let jwks_url = base_url.join(JWKS_PATH).map_err(|e| AxiamError::Network {
            message: format!("invalid JWKS URL: {e}"),
            source: None,
        })?;
        Ok(Self {
            http_client,
            jwks_url,
            cache: RwLock::new(None),
            fetch_lock: tokio::sync::Mutex::new(()),
            limit_failed_fetches: false,
            last_failed_fetch: std::sync::Mutex::new(None),
            expected_tenant_id: None,
            expected_issuer: None,
            expected_audience: None,
            revocation_feed: None,
            #[cfg(feature = "actix")]
            resource_metadata_url: None,
            #[cfg(feature = "actix")]
            mcp_challenges: None,
        })
    }

    /// Configure the tenant every token accepted by [`Self::verify`] must be
    /// scoped to (CONTRACT.md §10.1 rule 4) — **required** for any verifier
    /// used as a §10 route guard.
    ///
    /// The `/oauth2/jwks` trust anchor is organization-wide, so a valid
    /// signature says only "some tenant in this organization", never "this
    /// tenant". Without this call [`Self::verify`] fails closed on every
    /// token.
    ///
    /// ```no_run
    /// # use axiam_sdk::token::JwksVerifier;
    /// # fn demo(http: reqwest::Client, base: url::Url, tenant: uuid::Uuid)
    /// #     -> Result<(), axiam_sdk::AxiamError> {
    /// let verifier = JwksVerifier::new(http, &base)?.expect_tenant_id(tenant);
    /// # let _ = verifier;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn expect_tenant_id(mut self, tenant_id: uuid::Uuid) -> Self {
        self.expected_tenant_id = Some(tenant_id);
        self
    }

    /// Configure the expected `iss` claim (CONTRACT.md §10.1 rule 5).
    ///
    /// Optional and unset by default — the rule is conditional, and this SDK
    /// never hardcodes an issuer. When set, a token whose `iss` differs is
    /// rejected by [`Self::verify`].
    #[must_use]
    pub fn expect_issuer(mut self, issuer: impl Into<String>) -> Self {
        self.expected_issuer = Some(issuer.into());
        self
    }

    /// Configure the expected `aud` claim (CONTRACT.md §10.1 rule 6).
    ///
    /// Optional and unset by default. A resource server guarding user-facing
    /// routes SHOULD set `"axiam:user"`; a machine-to-machine one
    /// `"axiam:m2m"`. When set, a token whose `aud` does not match is
    /// rejected by [`Self::verify`].
    #[must_use]
    pub fn expect_audience(mut self, audience: impl Into<String>) -> Self {
        self.expected_audience = Some(audience.into());
        self
    }

    /// The expected `aud` claim configured via [`Self::expect_audience`], if
    /// any.
    pub fn expected_audience(&self) -> Option<&str> {
        self.expected_audience.as_deref()
    }

    /// Turn on the CONTRACT.md §28 MCP resource-server challenge: every
    /// `WWW-Authenticate`-bearing 401 [`crate::middleware::AxiamUser`] emits
    /// (and, via
    /// [`crate::middleware::RequireAccess::with_resource_metadata_url`], the
    /// one class of 403 §28.5 rule 5 names) carries the RFC 6750 challenge
    /// pointing at `url`. Off by default; with this unset, every guard built
    /// from this verifier behaves byte-for-byte as it did before §28
    /// existed (§28.5 rule 1) — no `WWW-Authenticate` header on any
    /// response, no status changed, no body changed.
    ///
    /// **Call [`Self::expect_audience`] first.** §28.5 rule 2: a resource
    /// server that publishes "tokens for me carry this `aud`" and then does
    /// not check `aud` has published a claim it does not honour, and a
    /// token minted for a *different* resource server opens it — so this
    /// call refuses rather than merely warns when no expected audience is
    /// already configured. §28.5 rule 6: this is the *only* audience option
    /// §28 reads; there is no second one to set.
    ///
    /// `url` is ordinarily
    /// [`ProtectedResourceMetadata::metadata_url`](crate::middleware::ProtectedResourceMetadata::metadata_url),
    /// fed from the same
    /// [`protected_resource_metadata`](crate::middleware::protected_resource_metadata)
    /// call that builds the document this verifier's audience must match —
    /// [`crate::middleware::serve_protected_resource_metadata`] cross-checks
    /// the two when given this verifier.
    ///
    /// # Errors
    ///
    /// [`AxiamError::Network`] (carrying a
    /// [`ValidationError`](crate::management::ValidationError) source,
    /// CONTRACT.md §2 — §28 adds no new error type) naming both
    /// `resource_metadata_url` and `expect_audience` when no expected
    /// audience is configured yet, or when `url` is not a syntactically
    /// valid `WWW-Authenticate` `resource_metadata` value (CONTRACT.md
    /// §28.2 rules 1–2, §28.4).
    #[cfg(feature = "actix")]
    pub fn with_resource_metadata_url(
        mut self,
        url: impl Into<String>,
    ) -> Result<Self, AxiamError> {
        let url = url.into();
        if self.expected_audience.is_none() {
            return Err(crate::middleware::mcp::refuse(
                "with_resource_metadata_url",
                "resource_metadata_url",
                "requires expect_audience(...) to be called first (CONTRACT.md §28.5 rule 2) — announcing a resource identifier obliges this server to check that an inbound token's `aud` is that identifier, and a resource server that announces itself without checking is opened by a token minted for somebody else",
            ));
        }
        let challenges = crate::middleware::mcp::McpChallenges::build(&url)?;
        self.resource_metadata_url = Some(url);
        self.mcp_challenges = Some(challenges);
        Ok(self)
    }

    /// The URL configured via [`Self::with_resource_metadata_url`], if any.
    #[cfg(feature = "actix")]
    pub fn resource_metadata_url(&self) -> Option<&str> {
        self.resource_metadata_url.as_deref()
    }

    /// The precomputed §28.4 challenge values, when §28 is configured.
    #[cfg(feature = "actix")]
    pub(crate) fn mcp_challenges(&self) -> Option<&crate::middleware::mcp::McpChallenges> {
        self.mcp_challenges.as_ref()
    }

    /// Construct a verifier against an **already-absolute** JWKS URL
    /// (CONTRACT.md §12.3 rule 6: "SDKs MUST read `jwks_uri` from the
    /// document rather than hardcoding `/oauth2/jwks`"). Used by
    /// `crate::oidc` to verify ID tokens against the `jwks_uri` the OIDC
    /// discovery document advertises, which is not necessarily
    /// `{base_url}/oauth2/jwks` (e.g. behind a proxy).
    ///
    /// The caller owns the X-2 scheme check. `jwks_url` here is remote input,
    /// unlike [`Self::new`]'s `base_url`, which
    /// `AxiamClientBuilder::base_url` already validated. The sole caller,
    /// `AxiamClient::oidc_verifier_for`, runs
    /// [`crate::url_guard::ensure_secure_scheme`] before constructing — keep
    /// it that way if a second caller ever appears, or the SDK will fetch its
    /// signing keys over cleartext.
    pub(crate) fn for_jwks_url(http_client: reqwest::Client, jwks_url: url::Url) -> Self {
        Self {
            http_client,
            jwks_url,
            cache: RwLock::new(None),
            fetch_lock: tokio::sync::Mutex::new(()),
            limit_failed_fetches: false,
            last_failed_fetch: std::sync::Mutex::new(None),
            expected_tenant_id: None,
            expected_issuer: None,
            expected_audience: None,
            revocation_feed: None,
            #[cfg(feature = "actix")]
            resource_metadata_url: None,
            #[cfg(feature = "actix")]
            mcp_challenges: None,
        }
    }

    /// Count a failed fetch toward the once-a-minute limit (§34.2 P6, the SSF
    /// receiver's key cache): within a minute of a failed fetch no fetch is
    /// made, and a lookup that needs one fails with [`AxiamError::Network`].
    pub(crate) fn limiting_failed_fetches(mut self) -> Self {
        self.limit_failed_fetches = true;
        self
    }

    /// The refusal a lookup gets inside the minute after a failed fetch, when
    /// failed fetches are limited.
    fn failed_fetch_cooldown(&self) -> Result<(), AxiamError> {
        if !self.limit_failed_fetches {
            return Ok(());
        }
        let last = *self
            .last_failed_fetch
            .lock()
            .unwrap_or_else(|p| p.into_inner());
        match last {
            Some(at) if at.elapsed() < FAILED_FETCH_MIN_INTERVAL => Err(AxiamError::network(
                "the JWKS fetch failed less than a minute ago; no fetch was made \
                 (CONTRACT.md §34.2 P6)",
            )),
            _ => Ok(()),
        }
    }

    /// Verify an arbitrary JWT's EdDSA signature against the cached JWKS,
    /// returning the decoded claims — CONTRACT.md §12.4 rules 1–2 (`alg`
    /// allowlist, `kid` lookup with a single forced re-fetch on miss,
    /// Ed25519 signature verification).
    ///
    /// Reuses the SAME fetch/cache/single-flight/forced-refetch machinery as
    /// [`Self::verify`] (`get_or_fetch`/`force_refetch_if_allowed`) — §12
    /// forbids forking the JWKS verifier — but performs NO issuer/audience/
    /// time/nonce checks (rules 3–6) and tags every failure with the
    /// CONTRACT.md §12.3 rule 3 reason code, via
    /// [`AxiamError::id_token_invalid`], rather than [`Self::verify`]'s plain
    /// message.
    ///
    /// **Divergence from [`Self::verify`], required by §12.4 rule 2:** a
    /// missing `kid` is rejected outright, with no single-key fallback. The
    /// access-token path's [`find_jwk`] intentionally falls back to a lone
    /// published key when `kid` is absent (D-11, AXIAM's own tokens may omit
    /// it); an ID token from a third-party-shaped flow gets no such
    /// convenience — CONTRACT.md §12.4 rule 2 says plainly "a token with no
    /// `kid` … MUST be rejected".
    pub(crate) async fn verify_id_token_signature<T>(&self, token: &str) -> Result<T, AxiamError>
    where
        T: serde::de::DeserializeOwned,
    {
        use crate::error::IdTokenFailureReason;

        let header = decode_header(token).map_err(|e| {
            AxiamError::id_token_invalid(
                IdTokenFailureReason::InvalidAlg,
                format!("malformed token: {e}"),
            )
        })?;

        if header.alg != Algorithm::EdDSA {
            return Err(AxiamError::id_token_invalid(
                IdTokenFailureReason::InvalidAlg,
                format!(
                    "expected alg \"{}\", got {:?}",
                    crate::oidc::id_token::ID_TOKEN_ALG,
                    header.alg
                ),
            ));
        }

        let kid = header.kid.as_deref().ok_or_else(|| {
            AxiamError::id_token_invalid(
                IdTokenFailureReason::UnknownKid,
                "token has no kid header",
            )
        })?;

        let jwks = self.get_or_fetch().await?;
        let jwk = match find_jwk_by_kid(&jwks, kid) {
            Some(jwk) => jwk,
            None => {
                let refreshed = self.force_refetch_if_allowed().await?;
                find_jwk_by_kid(&refreshed, kid).ok_or_else(|| {
                    AxiamError::id_token_invalid(
                        IdTokenFailureReason::UnknownKid,
                        "unknown kid after JWKS refetch",
                    )
                })?
            }
        };

        let decoding_key = DecodingKey::from_jwk(&jwk).map_err(|_| {
            AxiamError::id_token_invalid(
                IdTokenFailureReason::InvalidSignature,
                "unable to build decoding key from JWK",
            )
        })?;

        let mut validation = Validation::new(Algorithm::EdDSA);
        // Rules 3-6 (issuer/audience/time/nonce) are applied by the caller
        // (`crate::oidc::id_token`) over the returned claims, with its own
        // configurable clock skew — disable jsonwebtoken's own exp/nbf/aud
        // checks and required-claims gate so they cannot fight the SDK's own
        // checklist or double-report a single failure under two different
        // reason codes.
        validation.required_spec_claims.clear();
        validation.validate_exp = false;
        validation.validate_nbf = false;
        validation.validate_aud = false;
        validation.leeway = 0;

        let data = decode::<T>(token, &decoding_key, &validation).map_err(|e| {
            use jsonwebtoken::errors::ErrorKind;
            match e.kind() {
                ErrorKind::InvalidSignature => AxiamError::id_token_invalid(
                    IdTokenFailureReason::InvalidSignature,
                    "signature invalid",
                ),
                _ => AxiamError::id_token_invalid(
                    IdTokenFailureReason::InvalidSignature,
                    format!("claim decode failed: {e}"),
                ),
            }
        })?;

        Ok(data.claims)
    }

    /// The key `kid` names, fetching the JWKS if needed and, on a miss, forcing
    /// **one** refetch — rate-limited to once per minute
    /// (`FORCED_REFETCH_MIN_INTERVAL`) — before giving up with `Ok(None)`.
    ///
    /// The shared machinery behind the §32.7 SET verifier, which maps its
    /// own reason codes and so needs the lookup without
    /// [`Self::verify_id_token_signature`]'s §12.3 ones.
    pub(crate) async fn key_for_kid(
        &self,
        kid: &str,
    ) -> Result<Option<jsonwebtoken::jwk::Jwk>, AxiamError> {
        let jwks = self.get_or_fetch().await?;
        if let Some(jwk) = find_jwk_by_kid(&jwks, kid) {
            return Ok(Some(jwk));
        }
        let refreshed = self.force_refetch_if_allowed().await?;
        Ok(find_jwk_by_kid(&refreshed, kid))
    }

    /// Verify an inbound AXIAM access token against the **complete**
    /// CONTRACT.md §10.1 minimum local-verification set. This is the SDK's
    /// documented guard entry point — the §10 [`AxiamUser`] extractor and the
    /// §11 `require_*` macros (which inject that extractor) both land here.
    ///
    /// | § | rule | how it is enforced |
    /// |---|---|---|
    /// | 1 | signature | `alg` read from the header and pinned to `EdDSA` **before** the JWKS is consulted, so `alg: none` and an HS-signed token bearing an EdDSA `kid` are rejected without a key lookup; the Ed25519 signature is then checked against the org JWKS. |
    /// | 2 | `exp` | REQUIRED: `exp` is in `required_spec_claims` *and* a non-`Option` field of [`Claims`], so an absent or non-numeric `exp` is rejected. |
    /// | 3 | `nbf` | `validate_nbf` enabled — a future `nbf` is rejected, an absent one is fine. |
    /// | 4 | `tenant_id` | asserted against [`Self::expect_tenant_id`]; **fails closed** when the claim is absent/not a UUID, and when no expected tenant was configured at all. |
    /// | 5 | `iss` | checked only when [`Self::expect_issuer`] was called. |
    /// | 6 | `aud` | checked only when [`Self::expect_audience`] was called. |
    /// | 7 | clock skew | [`CLOCK_SKEW_LEEWAY_SECS`] — a named, bounded, non-configurable 60 s. |
    /// | 9 | `cnf` | this entry point has **no** transport evidence, so a token carrying `cnf` is **refused**, whatever it names; an unbound token is unaffected. |
    ///
    /// # Rule 9, and which entry point to call
    ///
    /// A token with `cnf` is not a bearer token (§10.1 rule 9): it may be used
    /// only by a presenter that proves possession of the key it names. This
    /// method is handed a token and nothing else, so it cannot see that proof,
    /// and it fails closed — the "a different certificate, or none" row of the
    /// rule's table. Until contract 1.51 it accepted such a token as a bearer
    /// token, which is exactly the downgrade rule 9 exists to forbid, and the
    /// §6.1 device login now mints bound tokens by default.
    ///
    /// To **accept** bound tokens, give the verifier the evidence your
    /// transport holds: [`Self::verify_sender_constrained`] for a TLS client
    /// certificate, [`Self::verify_with_proofs`] when a verified DPoP proof may
    /// be present too. The [`AxiamUser`] extractor does this itself when the
    /// server records the peer certificate (see
    /// [`PeerCertificate`](crate::middleware::PeerCertificate)).
    ///
    /// # Errors
    ///
    /// [`AxiamError::Auth`] on any failed rule (the SDK never distinguishes
    /// "no `tenant_id` to check" from "wrong `tenant_id`" — both reject), or
    /// [`AxiamError::Network`] if the JWKS itself is unreachable.
    ///
    /// [`AxiamUser`]: crate::middleware::AxiamUser
    pub async fn verify(&self, token: &str) -> Result<Claims, AxiamError> {
        self.verify_with_proofs(token, PresentedProofs::default())
            .await
    }

    /// The complete §10.1 set — rules 1–8, then rule 9 against `proofs` — for
    /// a resource server that may receive **certificate-bound or DPoP-bound**
    /// tokens.
    ///
    /// `proofs` must come from the transport: the thumbprint of the peer
    /// certificate the TLS layer verified for this connection, and the `jkt`
    /// returned by [`crate::token::verify_dpop_proof`] for a proof checked
    /// against this request — never a value a caller supplied in a header.
    /// [`PresentedProofs::default()`] (no evidence) is exactly [`Self::verify`].
    /// An unbound token is accepted with or without proofs.
    ///
    /// # Errors
    ///
    /// Everything [`Self::verify`] returns; rule 9 refusals are listed on
    /// [`Claims::verify_token_binding`].
    pub async fn verify_with_proofs(
        &self,
        token: &str,
        proofs: PresentedProofs<'_>,
    ) -> Result<Claims, AxiamError> {
        let claims = self.verify_rules_one_to_eight(token).await?;
        claims.verify_token_binding(proofs)?;
        Ok(claims)
    }

    /// Rules 1–8 and the §10.4 feed — everything but the sender constraint,
    /// which every public entry point then applies with the evidence it has.
    /// Private on purpose: no caller may stop here.
    async fn verify_rules_one_to_eight(&self, token: &str) -> Result<Claims, AxiamError> {
        let claims = self.verify_claims(token).await?;
        self.assert_tenant(&claims)?;
        self.assert_not_revoked(&claims).await?;
        Ok(claims)
    }

    /// Attach a §10.4 revocation feed (contract 1.44).
    ///
    /// Off by default and opt-in per caller. With one attached, a token whose
    /// `sid` the feed lists is rejected within one poll interval instead of
    /// within one access-token lifetime.
    ///
    /// It never makes this verifier stricter in any other way. Every §10.1
    /// rule runs first and still decides; the feed can only turn an accept
    /// into a reject, and a feed that cannot be read turns nothing at all —
    /// see [`crate::token::revocation`] for why that is a rule and not a
    /// convenience.
    #[must_use]
    pub fn with_revocation_feed(mut self, feed: crate::token::revocation::RevocationFeed) -> Self {
        self.revocation_feed = Some(feed);
        self
    }

    /// §10.4 rules 4 and 6.
    ///
    /// A token with no `sid` is never matched against the feed: there is no
    /// session behind it. Everything else is a lookup in a cached set — no
    /// network work on this path, ever.
    async fn assert_not_revoked(&self, claims: &Claims) -> Result<(), AxiamError> {
        let Some(feed) = &self.revocation_feed else {
            return Ok(());
        };
        let Some(sid) = claims.sid.as_deref() else {
            return Ok(());
        };
        if feed.is_revoked(sid).await {
            return Err(AxiamError::Auth {
                message: "the session behind this access token has been revoked \
                          (CONTRACT.md §10.4)"
                    .into(),
                oauth: None,
                reason: None,
                set_reason: None,
                retry_after: None,
            });
        }
        Ok(())
    }

    /// [`Self::verify`] plus CONTRACT.md §10.1 **rule 9** — the sender
    /// constraint (RFC 8705 §3, contract 1.15).
    ///
    /// This is the guard entry point for a resource server that accepts
    /// **certificate-bound** access tokens. Pass the `x5t#S256` thumbprint of
    /// the client certificate on the current connection, or `None` if there is
    /// none; [`certificate_thumbprint_s256`] computes it from DER bytes.
    ///
    /// It is a separate method rather than a parameter on [`Self::verify`]
    /// because the two have different *inputs*: `verify` needs only a token,
    /// and a great many integrations have no transport-level certificate to
    /// offer. Folding the thumbprint into `verify` would have forced every
    /// caller to thread an `Option<&str>` they do not have, and the usual
    /// result of that is `None` everywhere — which reads as "no certificate"
    /// and rejects every bound token.
    ///
    /// **An unbound token is still accepted** here, with or without a
    /// certificate. Rule 9 constrains tokens that claim a constraint; it does
    /// not make certificates mandatory.
    ///
    /// # Errors
    ///
    /// Everything [`Self::verify`] returns, plus [`AxiamError::Auth`] when the
    /// token's `cnf` does not match what was presented — see
    /// [`Claims::verify_certificate_binding`] for the exact table.
    pub async fn verify_sender_constrained(
        &self,
        token: &str,
        presented_thumbprint: Option<&str>,
    ) -> Result<Claims, AxiamError> {
        let claims = self.verify_rules_one_to_eight(token).await?;
        claims.verify_certificate_binding(presented_thumbprint)?;
        Ok(claims)
    }

    /// Verify **only** the EdDSA signature of `token` against the org JWKS —
    /// CONTRACT.md §10.1's "raw signature-only primitive".
    ///
    /// # This is not a guard
    ///
    /// It performs **no** `exp`, `nbf`, `tenant_id`, `iss` or `aud` check
    /// whatsoever. An expired token, a not-yet-valid token, and a token
    /// minted for a *different tenant* in the same organization all pass. It
    /// exists purely for integrators deliberately implementing their own
    /// policy on top of the signature; the `_unchecked` suffix is there to
    /// make that omission obvious at the call site. Anything guarding a route
    /// MUST call [`Self::verify`] instead.
    ///
    /// (`exp` must still be *present and numeric* simply because [`Claims`]
    /// declares it as a non-`Option` `i64`; nothing checks whether it has
    /// passed.)
    ///
    /// # Errors
    ///
    /// [`AxiamError::Auth`] if the `alg` is not EdDSA, the `kid` is unknown,
    /// the signature does not verify, or the payload is not shaped like
    /// [`Claims`]; [`AxiamError::Network`] if the JWKS is unreachable.
    pub async fn verify_signature_only_unchecked(&self, token: &str) -> Result<Claims, AxiamError> {
        let decoding_key = self.decoding_key_for(token).await?;

        let mut validation = Validation::new(Algorithm::EdDSA);
        validation.required_spec_claims.clear();
        validation.validate_exp = false;
        validation.validate_nbf = false;
        validation.validate_aud = false;
        validation.leeway = 0;

        decode_claims(token, &decoding_key, &validation)
    }

    /// The client's own freshly-issued session token, decoded to learn the
    /// identity the server just handed us (`login`/`verify_mfa`/`refresh`/
    /// `logout`).
    ///
    /// **Not a §10 guard, and deliberately not `verify`.** §10.1 governs
    /// relying-party verification of a token that arrived from an untrusted
    /// caller; this path decodes a token this very client just received in
    /// the TLS response of its own authenticated request to the configured
    /// `base_url`. Rule 4 cannot apply here in either direction: the
    /// `tenant_id` claim is what the client is *learning* (a client built
    /// with a `tenant_slug` has no tenant UUID to compare against yet), so
    /// asserting it would be circular. Every other rule — alg pinning,
    /// required numeric `exp`, `nbf`, the configured-only `iss`/`aud`, and
    /// the shared [`CLOCK_SKEW_LEEWAY_SECS`] — is applied exactly as in
    /// [`Self::verify`].
    pub(crate) async fn verify_session_token(&self, token: &str) -> Result<Claims, AxiamError> {
        self.verify_claims(token).await
    }

    /// Everything in §10.1 except rule 4 (the tenant assertion), shared by
    /// [`Self::verify`] and [`Self::verify_session_token`].
    async fn verify_claims(&self, token: &str) -> Result<Claims, AxiamError> {
        let decoding_key = self.decoding_key_for(token).await?;

        let mut validation = Validation::new(Algorithm::EdDSA);
        // Rule 7: one named, bounded, non-operator-settable leeway for both
        // the `exp` and the `nbf` comparison.
        validation.leeway = CLOCK_SKEW_LEEWAY_SECS;
        // Rule 2: `exp` is REQUIRED, not "checked if present". Two
        // independent gates enforce it, and either is sufficient:
        // `Claims::exp` is a non-`Option` `i64`, so serde rejects an absent
        // or non-numeric `exp` while deserializing (jsonwebtoken decodes `T`
        // before it validates, so in practice this is the one that trips);
        // and `required_spec_claims` covers the same ground at the
        // validation layer. jsonwebtoken already defaults the latter to
        // `{"exp"}` — setting it explicitly keeps the guarantee from
        // silently changing under a dependency bump.
        validation.set_required_spec_claims(&["exp"]);
        validation.validate_exp = true;
        // Rule 3: honour `nbf` when present (jsonwebtoken defaults this to
        // `false`, i.e. a future-dated token would otherwise be accepted).
        // An absent `nbf` stays valid — it is not in `required_spec_claims`.
        validation.validate_nbf = true;

        // Rules 5 and 6 are CONDITIONAL: only checked when this verifier was
        // configured with an expected value. Note that leaving
        // `validate_aud` at jsonwebtoken's `true` default while
        // `validation.aud` is `None` rejects every token that merely *has* an
        // `aud` — i.e. every real AXIAM access token — so it is switched off
        // unless an expectation was actually configured.
        //
        // Configuring an expectation also makes the corresponding claim
        // REQUIRED: jsonwebtoken only compares a claim it can see, so an
        // absent `aud` against a configured expectation would otherwise slip
        // through ("the claim was missing so there was nothing to check" —
        // the SEC-080 shape). A token whose `aud` does not contain the
        // expected value is rejected, and an absent `aud` does not contain
        // it.
        match self.expected_issuer.as_deref() {
            Some(iss) => {
                validation.set_issuer(&[iss]);
                validation.required_spec_claims.insert("iss".to_string());
            }
            None => validation.iss = None,
        }
        match self.expected_audience.as_deref() {
            Some(aud) => {
                validation.validate_aud = true;
                validation.set_audience(&[aud]);
                validation.required_spec_claims.insert("aud".to_string());
            }
            None => {
                validation.validate_aud = false;
                validation.aud = None;
            }
        }

        decode_claims(token, &decoding_key, &validation)
    }

    /// §10.1 rule 1's first half: pin `alg` to EdDSA from the header
    /// **before** any JWKS lookup, then resolve the `kid` to a decoding key.
    async fn decoding_key_for(&self, token: &str) -> Result<DecodingKey, AxiamError> {
        let header = decode_header(token).map_err(|e| AxiamError::Auth {
            message: format!("invalid token header: {e}"),
            oauth: None,
            reason: None,
            set_reason: None,
            retry_after: None,
        })?;

        // Rule 1: rejected WITHOUT consulting a key — `alg: none` and every
        // HS-family confusion attempt dies here, before `get_or_fetch`.
        if header.alg != Algorithm::EdDSA {
            return Err(AxiamError::Auth {
                message: "unexpected alg: only EdDSA is accepted".into(),
                oauth: None,
                reason: None,
                set_reason: None,
                retry_after: None,
            });
        }

        let jwks = self.get_or_fetch().await?;
        let jwk = find_jwk(&jwks, header.kid.as_deref());

        let jwk = match jwk {
            Some(j) => j,
            None => {
                // Unknown kid → forced refetch (rate-limited), matching the
                // server's own kid-rotation handling (D-11).
                let refreshed = self.force_refetch_if_allowed().await?;
                find_jwk(&refreshed, header.kid.as_deref()).ok_or_else(|| AxiamError::Auth {
                    message: "unknown kid after JWKS refetch".into(),
                    oauth: None,
                    reason: None,
                    set_reason: None,
                    retry_after: None,
                })?
            }
        };

        DecodingKey::from_jwk(&jwk).map_err(|_| AxiamError::Auth {
            message: "unable to build decoding key from JWK".into(),
            oauth: None,
            reason: None,
            set_reason: None,
            retry_after: None,
        })
    }

    /// §10.1 rule 4 — the `tenant_id` claim MUST equal the configured tenant.
    ///
    /// Fails closed on all three ways this can go wrong: no configured
    /// tenant, an unparseable/absent claim, and a mismatch. "There was no
    /// tenant to compare against, so there was nothing to check" is the
    /// `SEC-080` defect, not a pass.
    fn assert_tenant(&self, claims: &Claims) -> Result<(), AxiamError> {
        let expected = self.expected_tenant_id.ok_or_else(|| AxiamError::Auth {
            message: "JWKS verifier has no expected tenant configured; refusing to accept a \
                      token (CONTRACT.md §10.1 rule 4 — call \
                      JwksVerifier::expect_tenant_id before using it as a route guard)"
                .into(),
            oauth: None,
            reason: None,
            set_reason: None,
            retry_after: None,
        })?;

        let actual =
            uuid::Uuid::parse_str(claims.tenant_id.trim()).map_err(|_| AxiamError::Auth {
                message: "token tenant_id claim is absent or not a UUID".into(),
                oauth: None,
                reason: None,
                set_reason: None,
                retry_after: None,
            })?;

        if actual != expected {
            return Err(AxiamError::Auth {
                message: "token tenant_id does not match the configured tenant".into(),
                oauth: None,
                reason: None,
                set_reason: None,
                retry_after: None,
            });
        }

        Ok(())
    }

    async fn get_or_fetch(&self) -> Result<JwkSet, AxiamError> {
        if let Some(jwks) = self.cached_if_fresh() {
            return Ok(jwks);
        }
        // Serialize concurrent fetchers on a cold/stale cache (D-08/D-09):
        // acquire the fetch guard, then double-check under it — a
        // concurrent caller may have already refreshed while we waited.
        let _guard = self.fetch_lock.lock().await;
        if let Some(jwks) = self.cached_if_fresh() {
            return Ok(jwks);
        }
        self.failed_fetch_cooldown()?;
        self.fetch_and_cache(false).await
    }

    fn cached_if_fresh(&self) -> Option<JwkSet> {
        let cache = self.cache.read().ok()?;
        let entry = cache.as_ref()?;
        if entry.fetched_at.elapsed() < JWKS_CACHE_TTL {
            Some(entry.jwks.clone())
        } else {
            None
        }
    }

    /// Force a refetch, but rate-limited to at most once per
    /// `FORCED_REFETCH_MIN_INTERVAL` to avoid a rotating/hostile `kid`
    /// stream hammering the JWKS endpoint.
    async fn force_refetch_if_allowed(&self) -> Result<JwkSet, AxiamError> {
        // Same fetch_lock as get_or_fetch — a rotating/hostile-kid burst
        // that reaches this forced-refetch path must ALSO serialize on the
        // single fetch guard so concurrent callers collapse to one fetch
        // (D-08/D-09), rather than each racing the cooldown check
        // independently (the pre-existing TOCTOU this plan closes).
        let _guard = self.fetch_lock.lock().await;
        self.failed_fetch_cooldown()?;

        let allowed = {
            let cache = self.cache.read().ok();
            match cache.as_ref().and_then(|c| c.as_ref()) {
                Some(entry) => match entry.last_forced_refetch {
                    Some(last) => last.elapsed() >= FORCED_REFETCH_MIN_INTERVAL,
                    None => true,
                },
                None => true,
            }
        };

        if allowed {
            self.fetch_and_cache(true).await
        } else if let Some(jwks) = self
            .cache
            .read()
            .ok()
            .and_then(|c| c.as_ref().map(|e| e.jwks.clone()))
        {
            Ok(jwks)
        } else {
            self.fetch_and_cache(true).await
        }
    }

    async fn fetch_and_cache(&self, is_forced: bool) -> Result<JwkSet, AxiamError> {
        let outcome = self.fetch_and_cache_once(is_forced).await;
        if self.limit_failed_fetches {
            *self
                .last_failed_fetch
                .lock()
                .unwrap_or_else(|p| p.into_inner()) = outcome.is_err().then(Instant::now);
        }
        outcome
    }

    async fn fetch_and_cache_once(&self, is_forced: bool) -> Result<JwkSet, AxiamError> {
        let response = self
            .http_client
            .get(self.jwks_url.clone())
            .omit_browser_credentials()
            .send()
            .await
            .map_err(|e| AxiamError::Network {
                message: format!("JWKS fetch failed: {e}"),
                source: Some(Box::new(e)),
            })?;

        if !response.status().is_success() {
            return Err(AxiamError::from_http_status(
                response.status().as_u16(),
                "JWKS endpoint returned a non-success status".to_string(),
            ));
        }

        let jwks: JwkSet = response.json().await.map_err(|e| AxiamError::Network {
            message: format!("JWKS response parse failed: {e}"),
            source: Some(Box::new(e)),
        })?;

        let now = Instant::now();
        if let Ok(mut cache) = self.cache.write() {
            *cache = Some(CachedJwks {
                jwks: jwks.clone(),
                fetched_at: now,
                last_forced_refetch: if is_forced { Some(now) } else { None },
            });
        }

        Ok(jwks)
    }
}

/// Decode `token` into [`Claims`] under `validation`, translating
/// `jsonwebtoken`'s error kinds into the SDK's [`AxiamError::Auth`] messages.
///
/// Every failure mode — bad signature, expired, not-yet-valid, missing or
/// mistyped `exp`, wrong issuer/audience, a payload that is not shaped like
/// [`Claims`] — funnels through here and is a rejection. There is no branch
/// that turns a claim it could not evaluate into success.
#[cfg(any(feature = "rest", feature = "actix"))]
fn decode_claims(
    token: &str,
    decoding_key: &DecodingKey,
    validation: &Validation,
) -> Result<Claims, AxiamError> {
    let data = decode::<Claims>(token, decoding_key, validation).map_err(|e| {
        use jsonwebtoken::errors::ErrorKind;
        let message = match e.kind() {
            ErrorKind::InvalidSignature => "token signature invalid".to_string(),
            ErrorKind::ExpiredSignature => "token expired".to_string(),
            ErrorKind::ImmatureSignature => "token is not valid yet (nbf is in the future)".into(),
            ErrorKind::MissingRequiredClaim(claim) => {
                format!("token is missing the required {claim} claim")
            }
            ErrorKind::InvalidClaimFormat(claim) => {
                format!("token {claim} claim is not a number")
            }
            ErrorKind::InvalidIssuer => "token issuer does not match the expected issuer".into(),
            ErrorKind::InvalidAudience => {
                "token audience does not match the expected audience".into()
            }
            _ => format!("token claim validation failed: {e}"),
        };
        AxiamError::Auth {
            message,
            oauth: None,
            reason: None,
            set_reason: None,
            retry_after: None,
        }
    })?;

    Ok(data.claims)
}

/// Find a JWK by `kid` in a JWK set. If `kid` is `None` and the set has
/// exactly one key, returns that key as a best-effort match — AXIAM's
/// `/oauth2/jwks` serves exactly one org-wide Ed25519 key (D-11).
///
/// Mirrors `crates/axiam-federation/src/oidc.rs::find_jwk` exactly.
#[cfg(any(feature = "rest", feature = "actix"))]
fn find_jwk(jwks: &JwkSet, kid: Option<&str>) -> Option<jsonwebtoken::jwk::Jwk> {
    match kid {
        Some(k) => jwks
            .keys
            .iter()
            .find(|j| j.common.key_id.as_deref() == Some(k))
            .cloned(),
        None if jwks.keys.len() == 1 => jwks.keys.first().cloned(),
        None => None,
    }
}

/// Find a JWK by an EXPLICIT `kid` only — no single-key fallback. Used by
/// [`JwksVerifier::verify_id_token_signature`] (CONTRACT.md §12.4 rule 2),
/// which requires a `kid` header to be present at all; callers with no
/// `kid` never reach this function (see its doc comment for why the
/// access-token path's fallback in [`find_jwk`] does not apply here).
#[cfg(any(feature = "rest", feature = "actix"))]
fn find_jwk_by_kid(jwks: &JwkSet, kid: &str) -> Option<jsonwebtoken::jwk::Jwk> {
    jwks.keys
        .iter()
        .find(|j| j.common.key_id.as_deref() == Some(kid))
        .cloned()
}

#[cfg(all(test, any(feature = "rest", feature = "actix")))]
mod tests {
    use super::*;
    use jsonwebtoken::{EncodingKey, Header, jwk::*};

    /// A fixed, valid Ed25519 public key `x` coordinate (base64url, no
    /// padding) used only to exercise `find_jwk`'s selection logic in these
    /// tests. `find_jwk` never verifies a signature itself, so an arbitrary
    /// (but well-formed) OKP key is sufficient here — no signing key or
    /// extra crypto dependency needed.
    const TEST_PUBLIC_X: &str = "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo";

    fn ed25519_test_jwk(kid: Option<&str>) -> Jwk {
        Jwk {
            common: CommonParameters {
                key_algorithm: Some(jsonwebtoken::jwk::KeyAlgorithm::EdDSA),
                key_id: kid.map(str::to_string),
                ..Default::default()
            },
            algorithm: AlgorithmParameters::OctetKeyPair(OctetKeyPairParameters {
                key_type: OctetKeyPairType::OctetKeyPair,
                curve: EllipticCurve::Ed25519,
                x: TEST_PUBLIC_X.to_string(),
            }),
        }
    }

    #[test]
    fn rejects_non_eddsa_alg_header() {
        // A well-formed HS256 token header must be rejected before any
        // signature/JWK lookup happens.
        let claims = Claims {
            sub: "u".into(),
            tenant_id: "t".into(),
            org_id: None,
            iss: "axiam".into(),
            iat: None,
            exp: 9_999_999_999,
            jti: None,
            sid: None,
            aud: None,
            scope: None,
            cnf: None,
        };
        let token = jsonwebtoken::encode(
            &Header::new(Algorithm::HS256),
            &claims,
            &EncodingKey::from_secret(b"irrelevant"),
        )
        .expect("encode HS256 test token");

        let header = decode_header(&token).expect("decode header");
        assert_ne!(header.alg, Algorithm::EdDSA);
    }

    #[test]
    fn find_jwk_single_key_fallback_when_kid_absent() {
        let jwk = ed25519_test_jwk(Some("test-kid"));
        let jwks = JwkSet { keys: vec![jwk] };
        let found = find_jwk(&jwks, None);
        assert!(
            found.is_some(),
            "single-key fallback must match on kid=None"
        );
    }

    #[test]
    fn find_jwk_no_fallback_with_multiple_keys() {
        let jwk1 = ed25519_test_jwk(Some("kid-1"));
        let jwk2 = ed25519_test_jwk(Some("kid-2"));
        let jwks = JwkSet {
            keys: vec![jwk1, jwk2],
        };
        let found = find_jwk(&jwks, None);
        assert!(
            found.is_none(),
            "must not fall back to a key when multiple keys exist and kid is absent"
        );
    }

    #[test]
    fn find_jwk_matches_by_kid() {
        let jwk1 = ed25519_test_jwk(Some("kid-1"));
        let jwk2 = ed25519_test_jwk(Some("kid-2"));
        let jwks = JwkSet {
            keys: vec![jwk1, jwk2],
        };
        let found = find_jwk(&jwks, Some("kid-2"));
        assert_eq!(found.unwrap().common.key_id.as_deref(), Some("kid-2"));
    }

    // ── §34.2 P6 (contract 1.60): the key cache expires, and a failed fetch
    //    counts toward the once-a-minute limit ──

    /// A JWKS endpoint answering `statuses` in turn (the last one repeats),
    /// and the number of fetches it saw.
    async fn jwks_endpoint(
        statuses: Vec<u16>,
    ) -> (
        wiremock::MockServer,
        std::sync::Arc<std::sync::atomic::AtomicUsize>,
    ) {
        use std::sync::atomic::{AtomicUsize, Ordering};
        let server = wiremock::MockServer::start().await;
        let hits = std::sync::Arc::new(AtomicUsize::new(0));
        let seen = std::sync::Arc::clone(&hits);
        let body = serde_json::json!({ "keys": [ed25519_test_jwk(Some("kid-1"))] });
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .respond_with(move |_: &wiremock::Request| {
                let n = seen.fetch_add(1, Ordering::SeqCst);
                let status = statuses[n.min(statuses.len() - 1)];
                wiremock::ResponseTemplate::new(status).set_body_json(body.clone())
            })
            .mount(&server)
            .await;
        (server, hits)
    }

    fn ssf_verifier(server: &wiremock::MockServer) -> JwksVerifier {
        let url = url::Url::parse(&format!("{}/oauth2/jwks", server.uri())).unwrap();
        JwksVerifier::for_jwks_url(reqwest::Client::new(), url).limiting_failed_fetches()
    }

    fn backdate(verifier: &JwksVerifier, field: &str, by: Duration) {
        let past = Instant::now()
            .checked_sub(by)
            .expect("a monotonic clock that far back");
        match field {
            "fetched_at" => verifier.cache.write().unwrap().as_mut().unwrap().fetched_at = past,
            _ => *verifier.last_failed_fetch.lock().unwrap() = Some(past),
        }
    }

    #[test]
    fn the_key_cache_lifetime_is_within_ten_minutes() {
        assert!(JWKS_CACHE_TTL <= Duration::from_secs(600));
    }

    #[tokio::test]
    async fn the_key_cache_expires_and_the_next_lookup_fetches_again() {
        use std::sync::atomic::Ordering;
        let (server, hits) = jwks_endpoint(vec![200]).await;
        let verifier = ssf_verifier(&server);
        assert!(verifier.key_for_kid("kid-1").await.unwrap().is_some());
        assert!(verifier.key_for_kid("kid-1").await.unwrap().is_some());
        assert_eq!(hits.load(Ordering::SeqCst), 1, "served from the cache");

        backdate(&verifier, "fetched_at", JWKS_CACHE_TTL);
        assert!(verifier.key_for_kid("kid-1").await.unwrap().is_some());
        assert_eq!(
            hits.load(Ordering::SeqCst),
            2,
            "an expired cache fetches again"
        );
        // A successful refresh is not counted: the unknown-kid refetch runs.
        assert!(verifier.key_for_kid("kid-9").await.unwrap().is_none());
        assert_eq!(hits.load(Ordering::SeqCst), 3);
    }

    #[tokio::test]
    async fn a_failed_fill_counts_and_the_next_lookup_inside_the_minute_makes_no_fetch() {
        use std::sync::atomic::Ordering;
        let (server, hits) = jwks_endpoint(vec![503, 200]).await;
        let verifier = ssf_verifier(&server);
        let e = verifier.key_for_kid("kid-1").await.unwrap_err();
        assert!(matches!(e, AxiamError::Network { .. }), "{e}");
        let e = verifier.key_for_kid("kid-1").await.unwrap_err();
        assert!(matches!(e, AxiamError::Network { .. }), "no verdict: {e}");
        assert_eq!(hits.load(Ordering::SeqCst), 1, "no fetch inside the minute");

        backdate(&verifier, "last_failed_fetch", FAILED_FETCH_MIN_INTERVAL);
        assert!(verifier.key_for_kid("kid-1").await.unwrap().is_some());
        assert_eq!(hits.load(Ordering::SeqCst), 2, "the minute is over");
    }

    #[tokio::test]
    async fn a_failed_expiry_refresh_and_a_failed_refetch_each_count() {
        use std::sync::atomic::Ordering;
        let (server, hits) = jwks_endpoint(vec![200, 503]).await;
        let verifier = ssf_verifier(&server);
        assert!(verifier.key_for_kid("kid-1").await.unwrap().is_some());

        // An unknown kid's refetch fails: a second unknown kid inside the
        // minute makes no fetch and is no verdict, while a known one still
        // verifies from the cache.
        assert!(verifier.key_for_kid("kid-9").await.is_err());
        assert_eq!(hits.load(Ordering::SeqCst), 2);
        let e = verifier.key_for_kid("kid-8").await.unwrap_err();
        assert!(matches!(e, AxiamError::Network { .. }), "{e}");
        assert!(verifier.key_for_kid("kid-1").await.unwrap().is_some());
        assert_eq!(hits.load(Ordering::SeqCst), 2);

        // The cache expires and its refresh fails: counted the same way.
        backdate(&verifier, "last_failed_fetch", FAILED_FETCH_MIN_INTERVAL);
        backdate(&verifier, "fetched_at", JWKS_CACHE_TTL);
        assert!(verifier.key_for_kid("kid-1").await.is_err());
        assert_eq!(hits.load(Ordering::SeqCst), 3);
        assert!(verifier.key_for_kid("kid-1").await.is_err());
        assert_eq!(hits.load(Ordering::SeqCst), 3, "no fetch inside the minute");
    }

    #[tokio::test]
    async fn without_the_limit_a_failed_fetch_is_retried_on_the_next_lookup() {
        use std::sync::atomic::Ordering;
        let (server, hits) = jwks_endpoint(vec![503, 200]).await;
        let url = url::Url::parse(&format!("{}/oauth2/jwks", server.uri())).unwrap();
        let verifier = JwksVerifier::for_jwks_url(reqwest::Client::new(), url);
        assert!(verifier.key_for_kid("kid-1").await.is_err());
        assert!(verifier.key_for_kid("kid-1").await.unwrap().is_some());
        assert_eq!(
            hits.load(Ordering::SeqCst),
            2,
            "the §10 / §12 paths are unchanged"
        );
    }
}