skyauth 0.3.4

High-assurance, formally verified OAuth 2.1 and RFC 9449 DPoP authentication engine for the AT Protocol (Bluesky)
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
//! Access token validation abstractions, JWT validation, and DPoP binding enforcement.
//!
//! Provides:
//! - [`AccessTokenValidator`]: Asynchronous trait for validating access tokens and enforcing RFC 9449 `cnf.jkt` binding.
//! - [`JwtAccessTokenValidator`]: Production-grade RFC 9068 / RFC 9449 cryptographic JWT access token validator.
//! - [`InMemoryTokenValidator`]: In-memory token registry for stateful token validation and testing.
//! - [`JwtAccessTokenClaims`]: Strongly typed RFC 9068 / AT Protocol JWT access token claims.
//! - [`CnfClaim`]: RFC 7800 / RFC 9449 confirmation claim (`cnf.jkt`).

use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use p256::ecdsa::VerifyingKey;
use parking_lot::RwLock;
use rand::RngCore;
use serde::{Deserialize, Serialize};

use super::AuthenticatedUser;
use crate::crypto::{
    base64url_decode, base64url_encode, constant_time_eq, sha256_digest, sign_p256_raw,
    verify_p256_raw,
};
use crate::error::{CryptoError, IntegrationError, TokenError};
use crate::session::OAuthSession;

/// RFC 7800 / RFC 9449 Confirmation claim (`cnf`) containing the JWK thumbprint (`jkt`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CnfClaim {
    /// RFC 7638 SHA-256 JWK Thumbprint (`jkt`) of the bound DPoP public key.
    pub jkt: String,
}

impl CnfClaim {
    /// Creates a new `CnfClaim` with the given JWK thumbprint.
    #[must_use]
    pub fn new(jkt: impl Into<String>) -> Self {
        Self { jkt: jkt.into() }
    }

    /// Returns a reference to the JWK thumbprint string.
    #[must_use]
    pub fn jkt(&self) -> &str {
        &self.jkt
    }
}

/// Standard claims extracted from an RFC 9068 / AT Protocol JWT Access Token.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct JwtAccessTokenClaims {
    /// Issuer URL of the Authorization Server (`iss`).
    pub iss: String,
    /// Subject Decentralized Identifier (`sub`), e.g. `did:plc:...` or `did:web:...`.
    pub sub: String,
    /// Client identifier of the OAuth client the token was issued to
    /// (RFC 9068 § 2.2 mandatory `client_id`; review M5).
    pub client_id: String,
    /// Target audience / Resource Server identifier (`aud`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub aud: Option<serde_json::Value>,
    /// Expiration timestamp in seconds since epoch (`exp`).
    pub exp: u64,
    /// Not-before timestamp in seconds since epoch (`nbf`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nbf: Option<u64>,
    /// Issued-at timestamp in seconds since epoch (`iat`) — RFC 9068 § 2.2
    /// mandatory (review M5).
    pub iat: u64,
    /// Unique token identifier (`jti`) — RFC 9068 § 2.2 mandatory (review M5).
    pub jti: String,
    /// Granted OAuth scopes (`scope`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scope: Option<String>,
    /// Confirmation claim binding this token to a DPoP key (`cnf`).
    pub cnf: CnfClaim,
}

impl JwtAccessTokenClaims {
    /// Creates a new `JwtAccessTokenClaims` with the RFC 9068 § 2.2 mandatory
    /// claims (`iss`, `sub`, `exp`, `client_id`, `iat`, `jti`) and the DPoP
    /// binding; optional claims default to `None`.
    ///
    /// `iat`/`jti` default to the current time and a random identifier —
    /// wire-level validation (via [`JwtAccessTokenValidator`]) enforces their
    /// presence in the presented token regardless of how the claims object was
    /// constructed.
    #[must_use]
    pub fn new(
        iss: impl Into<String>,
        sub: impl Into<String>,
        exp: u64,
        dpop_thumbprint: impl Into<String>,
    ) -> Self {
        let iat = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        let mut raw = [0u8; 16];
        rand::thread_rng().fill_bytes(&mut raw);
        Self {
            iss: iss.into(),
            sub: sub.into(),
            client_id: "https://app.example.com/client-metadata.json".to_string(),
            aud: None,
            exp,
            nbf: None,
            iat,
            jti: crate::crypto::base64url_encode(&raw),
            scope: None,
            cnf: CnfClaim::new(dpop_thumbprint),
        }
    }

    /// Sets the audience claim (`aud`).
    #[must_use]
    pub fn with_audience(mut self, aud: impl Into<String>) -> Self {
        self.aud = Some(serde_json::Value::String(aud.into()));
        self
    }

    /// Sets the scope claim (`scope`).
    #[must_use]
    pub fn with_scope(mut self, scope: impl Into<String>) -> Self {
        self.scope = Some(scope.into());
        self
    }

    /// Sets the not-before claim (`nbf`).
    #[must_use]
    pub fn with_nbf(mut self, nbf: u64) -> Self {
        self.nbf = Some(nbf);
        self
    }

    /// Signs this claims payload with an ECDSA P-256 [`p256::ecdsa::SigningKey`] to produce a compact JWT access token.
    ///
    /// # Errors
    ///
    /// Returns [`CryptoError`] if serialization or signing fails.
    pub fn sign_jwt(
        &self,
        signing_key: &p256::ecdsa::SigningKey,
        kid: Option<&str>,
    ) -> Result<String, CryptoError> {
        let mut header_map = serde_json::Map::new();
        header_map.insert(
            "alg".to_string(),
            serde_json::Value::String("ES256".to_string()),
        );
        header_map.insert(
            "typ".to_string(),
            serde_json::Value::String("at+jwt".to_string()),
        );
        if let Some(k) = kid {
            header_map.insert("kid".to_string(), serde_json::Value::String(k.to_string()));
        }

        let header_str = serde_json::to_string(&serde_json::Value::Object(header_map))
            .map_err(|e| CryptoError::Json(e.to_string()))?;
        let payload_str =
            serde_json::to_string(self).map_err(|e| CryptoError::Json(e.to_string()))?;

        let header_b64 = base64url_encode(header_str.as_bytes());
        let payload_b64 = base64url_encode(payload_str.as_bytes());

        let signing_input = format!("{header_b64}.{payload_b64}");
        let signature_bytes = sign_p256_raw(signing_key, signing_input.as_bytes())?;
        let sig_b64 = base64url_encode(&signature_bytes);

        Ok(format!("{signing_input}.{sig_b64}"))
    }
}

/// Asynchronous trait for validating access tokens and enforcing DPoP cryptographic binding.
pub trait AccessTokenValidator: Send + Sync + 'static {
    /// Validates the presented access token against the DPoP public key thumbprint.
    ///
    /// # Arguments
    ///
    /// - `token`: The raw access token string presented in `Authorization: DPoP <token>`.
    /// - `dpop_thumbprint`: The RFC 7638 SHA-256 JWK thumbprint (`jkt`) of the public key extracted
    ///   from the verified DPoP proof.
    ///
    /// # Returns
    ///
    /// Returns the authenticated user session details [`AuthenticatedUser`] on success.
    ///
    /// # Errors
    ///
    /// Returns [`IntegrationError`] if the token is invalid, expired, untrusted,
    /// or if its `cnf.jkt` binding does not match `dpop_thumbprint`.
    fn validate_access_token(
        &self,
        token: &str,
        dpop_thumbprint: &str,
    ) -> Pin<Box<dyn Future<Output = Result<AuthenticatedUser, IntegrationError>> + Send>>;
}

impl<T: AccessTokenValidator + ?Sized> AccessTokenValidator for Arc<T> {
    fn validate_access_token(
        &self,
        token: &str,
        dpop_thumbprint: &str,
    ) -> Pin<Box<dyn Future<Output = Result<AuthenticatedUser, IntegrationError>> + Send>> {
        (**self).validate_access_token(token, dpop_thumbprint)
    }
}

/// Production-grade JWT access token validator enforcing RFC 9068, RFC 9449, and AT Protocol token binding.
///
/// # Fail-Closed Configuration Contract
///
/// [`JwtAccessTokenValidator::verify_token_sync`] **refuses every token** until both
/// [`JwtAccessTokenValidator::with_expected_issuer`] and
/// [`JwtAccessTokenValidator::with_expected_audience`] have been configured. This is
/// deliberate: an issuer/audience check that is present-but-optional silently degrades
/// to "accept tokens minted by any trusted key for any audience", which is exactly the
/// cross-authorization-server and cross-resource-server confusion RFC 9068 § 4 exists
/// to prevent.
#[derive(Debug, Clone)]
pub struct JwtAccessTokenValidator {
    trusted_keys: HashMap<String, VerifyingKey>,
    default_key: Option<VerifyingKey>,
    expected_issuer: Option<String>,
    expected_audience: Option<String>,
    expected_subject: Option<String>,
    required_scopes: Vec<String>,
    clock_skew_leeway: Duration,
}

impl Default for JwtAccessTokenValidator {
    fn default() -> Self {
        Self::new()
    }
}

impl JwtAccessTokenValidator {
    /// Creates a new `JwtAccessTokenValidator` with default clock skew tolerance (60 seconds).
    #[must_use]
    pub fn new() -> Self {
        Self {
            trusted_keys: HashMap::new(),
            default_key: None,
            expected_issuer: None,
            expected_audience: None,
            expected_subject: None,
            required_scopes: Vec::new(),
            clock_skew_leeway: Duration::from_secs(60),
        }
    }

    /// Adds a trusted verifying key associated with a specific key ID (`kid`).
    #[must_use]
    pub fn with_trusted_key(mut self, kid: impl Into<String>, key: VerifyingKey) -> Self {
        self.trusted_keys.insert(kid.into(), key);
        self
    }

    /// Sets the default verifying key used when tokens omit a `kid` header or when a single key is configured.
    #[must_use]
    pub fn with_verifying_key(mut self, key: VerifyingKey) -> Self {
        self.default_key = Some(key);
        self
    }

    /// Sets the expected authorization server issuer URL (`iss`).
    ///
    /// **Mandatory**: token validation fails closed with [`IntegrationError::AuthFailed`]
    /// until an expected issuer is configured, and the token's `iss` must match it
    /// (compared after trimming and trailing-slash normalization) per RFC 9449 § 7.2.
    #[must_use]
    pub fn with_expected_issuer(mut self, issuer: impl Into<String>) -> Self {
        self.expected_issuer = Some(issuer.into());
        self
    }

    /// Sets the expected target resource server audience (`aud`).
    ///
    /// **Mandatory**: token validation fails closed with [`IntegrationError::AuthFailed`]
    /// until an expected audience is configured, and the token's `aud` must contain it
    /// per RFC 9068 § 4 (one AS signing key commonly mints tokens for several resource
    /// servers; without audience matching, resource server A would accept tokens minted
    /// for resource server B).
    #[must_use]
    pub fn with_expected_audience(mut self, audience: impl Into<String>) -> Self {
        self.expected_audience = Some(audience.into());
        self
    }

    /// Sets the expected subject DID (`sub`).
    #[must_use]
    pub fn with_expected_subject(mut self, subject: impl Into<String>) -> Self {
        self.expected_subject = Some(subject.into());
        self
    }

    /// Adds a required OAuth scope that must be present in the token's `scope` claim.
    #[must_use]
    pub fn with_required_scope(mut self, scope: impl Into<String>) -> Self {
        self.required_scopes.push(scope.into());
        self
    }

    /// Configures the allowable clock skew leeway.
    #[must_use]
    pub fn with_clock_skew(mut self, leeway: Duration) -> Self {
        self.clock_skew_leeway = leeway;
        self
    }

    /// Synchronously verifies and decodes a JWT access token against the given DPoP thumbprint.
    ///
    /// # Errors
    ///
    /// Returns [`IntegrationError`] or [`TokenError`] if token verification fails.
    pub fn verify_token_sync(
        &self,
        token: &str,
        dpop_thumbprint: &str,
    ) -> Result<AuthenticatedUser, IntegrationError> {
        let parts: Vec<&str> = token.trim().split('.').collect();
        if parts.len() != 3 {
            return Err(IntegrationError::Token(TokenError::MalformedToken(
                format!("Expected 3 parts in compact JWT, got {}", parts.len()),
            )));
        }

        let header_bytes = base64url_decode(parts[0])
            .map_err(|e| IntegrationError::Token(TokenError::MalformedToken(e.to_string())))?;
        let payload_bytes = base64url_decode(parts[1])
            .map_err(|e| IntegrationError::Token(TokenError::MalformedToken(e.to_string())))?;
        let signature_bytes = base64url_decode(parts[2])
            .map_err(|e| IntegrationError::Token(TokenError::MalformedToken(e.to_string())))?;

        let header_val: serde_json::Value = serde_json::from_slice(&header_bytes)
            .map_err(|e| IntegrationError::Token(TokenError::MalformedToken(e.to_string())))?;

        let alg = header_val
            .get("alg")
            .and_then(|v| v.as_str())
            .ok_or_else(|| {
                IntegrationError::Token(TokenError::MalformedToken(
                    "Missing alg header".to_string(),
                ))
            })?;

        if alg != "ES256" {
            return Err(IntegrationError::Token(TokenError::MalformedToken(
                format!("Unsupported alg in access token: expected 'ES256', got '{alg}'"),
            )));
        }

        let typ = header_val.get("typ").and_then(|v| v.as_str());
        if !typ
            .map(|t| {
                t.eq_ignore_ascii_case("at+jwt") || t.eq_ignore_ascii_case("application/at+jwt")
            })
            .unwrap_or(false)
        {
            return Err(IntegrationError::Token(TokenError::MalformedToken(
                format!(
                    "Unsupported typ in access token: expected 'at+jwt', got {:?}",
                    typ
                ),
            )));
        }

        let kid = header_val.get("kid").and_then(|v| v.as_str());

        let verifying_key = if let Some(k) = kid {
            match self.trusted_keys.get(k) {
                Some(key) => Some(key),
                None if self.trusted_keys.is_empty() => self.default_key.as_ref(),
                None => None,
            }
        } else if let Some(ref default_k) = self.default_key {
            Some(default_k)
        } else if self.trusted_keys.len() == 1 {
            self.trusted_keys.values().next()
        } else {
            None
        }
        .ok_or_else(|| {
            IntegrationError::AuthFailed(
                "No matching trusted verifying key found for access token".to_string(),
            )
        })?;

        let signing_input = format!("{}.{}", parts[0], parts[1]);
        verify_p256_raw(verifying_key, signing_input.as_bytes(), &signature_bytes)
            .map_err(|_| IntegrationError::Token(TokenError::InvalidSignature))?;

        let claims: JwtAccessTokenClaims = serde_json::from_slice(&payload_bytes)
            .map_err(|e| IntegrationError::Token(TokenError::MalformedToken(e.to_string())))?;

        let now_secs = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_err(|e| IntegrationError::Internal(e.to_string()))?
            .as_secs();
        let leeway_secs = self.clock_skew_leeway.as_secs();

        // RFC 9068 § 4 / RFC 7519 § 4.1.4: `exp` is the instant AFTER which the
        // token must not be accepted — a token at exactly `now == exp` (plus
        // configured leeway) is expired (review M5; previously `now > exp` accepted
        // the boundary instant).
        if now_secs.saturating_add(leeway_secs) >= claims.exp {
            return Err(IntegrationError::Token(TokenError::Expired {
                exp: claims.exp,
                now: now_secs,
            }));
        }

        if let Some(nbf) = claims.nbf {
            if nbf > now_secs.saturating_add(leeway_secs) {
                return Err(IntegrationError::Token(TokenError::NotYetValid {
                    nbf,
                    now: now_secs,
                }));
            }
        }

        // RFC 9449 § 7.2: issuer is attacker-controlled; a presence check alone would let an unrelated trusted AS's token through, hence the fail-closed gate below.
        if claims.iss.trim().is_empty() {
            return Err(IntegrationError::Token(TokenError::MissingIssuer));
        }
        let Some(ref exp_iss) = self.expected_issuer else {
            return Err(IntegrationError::AuthFailed(
                "Validator misconfigured: an expected issuer is required before any \
                 access token can be accepted (RFC 9068 § 4 / RFC 9449 § 7.2)"
                    .to_string(),
            ));
        };
        // RFC 9068 § 4 (review M5): the `iss` comparison is EXACT — normalizing
        // trailing slashes would accept an issuer that differs from the one the
        // resource server pinned.
        if claims.iss != *exp_iss {
            return Err(IntegrationError::Token(TokenError::IssuerMismatch {
                expected: exp_iss.clone(),
                actual: claims.iss.clone(),
            }));
        }

        // RFC 9068 § 4: audience must identify this resource server — one AS key mints tokens for several resource servers, so accepting any audience opens cross-RS token-confusion attacks.
        if claims.aud.is_none() {
            return Err(IntegrationError::Token(TokenError::MissingAudience));
        }
        let Some(ref exp_aud) = self.expected_audience else {
            return Err(IntegrationError::AuthFailed(
                "Validator misconfigured: an expected audience is required before any \
                 access token can be accepted (RFC 9068 § 4)"
                    .to_string(),
            ));
        };
        {
            let matches_aud = match &claims.aud {
                Some(serde_json::Value::String(s)) => s == exp_aud,
                Some(serde_json::Value::Array(arr)) => arr
                    .iter()
                    .any(|item| item.as_str().map(|s| s == exp_aud).unwrap_or(false)),
                _ => false,
            };
            if !matches_aud {
                return Err(IntegrationError::Token(TokenError::AudienceMismatch {
                    expected: exp_aud.clone(),
                    actual: claims
                        .aud
                        .as_ref()
                        .map(ToString::to_string)
                        .unwrap_or_else(|| "none".to_string()),
                }));
            }
        }

        if claims.sub.trim().is_empty() {
            return Err(IntegrationError::Token(TokenError::MissingDid));
        }

        if let Some(ref exp_sub) = self.expected_subject {
            if &claims.sub != exp_sub {
                return Err(IntegrationError::Token(TokenError::SubMismatch {
                    expected: exp_sub.clone(),
                    actual: claims.sub.clone(),
                }));
            }
        }

        if !self.required_scopes.is_empty() {
            let granted_scopes: Vec<&str> = claims
                .scope
                .as_deref()
                .unwrap_or("")
                .split_whitespace()
                .collect();
            for required in &self.required_scopes {
                if !granted_scopes.contains(&required.as_str()) {
                    return Err(IntegrationError::Token(TokenError::MissingAtprotoScope(
                        claims.scope.unwrap_or_default(),
                    )));
                }
            }
        }

        if !constant_time_eq(claims.cnf.jkt.as_bytes(), dpop_thumbprint.as_bytes()) {
            return Err(IntegrationError::Token(TokenError::CnfThumbprintMismatch {
                expected_jkt: claims.cnf.jkt,
                actual_jkt: dpop_thumbprint.to_string(),
            }));
        }

        Ok(AuthenticatedUser {
            did: claims.sub,
            access_token: token.to_string(),
            dpop_thumbprint: dpop_thumbprint.to_string(),
            scope: claims.scope,
        })
    }
}

impl AccessTokenValidator for JwtAccessTokenValidator {
    fn validate_access_token(
        &self,
        token: &str,
        dpop_thumbprint: &str,
    ) -> Pin<Box<dyn Future<Output = Result<AuthenticatedUser, IntegrationError>> + Send>> {
        let res = self.verify_token_sync(token, dpop_thumbprint);
        Box::pin(std::future::ready(res))
    }
}

/// In-memory registry for active access tokens and sessions with DPoP binding enforcement.
#[derive(Debug, Clone, Default)]
pub struct InMemoryTokenValidator {
    tokens: Arc<RwLock<HashMap<[u8; 32], RegisteredToken>>>,
}

/// Metadata for a registered access token in [`InMemoryTokenValidator`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RegisteredToken {
    /// Subject DID (e.g. `did:plc:...`).
    pub did: String,
    /// Bound DPoP public key JWK thumbprint (`jkt`).
    pub dpop_thumbprint: String,
    /// Granted scopes.
    pub scope: Option<String>,
    /// Optional expiration timestamp.
    pub expires_at: Option<SystemTime>,
}

impl InMemoryTokenValidator {
    /// Creates a new empty `InMemoryTokenValidator`.
    #[must_use]
    pub fn new() -> Self {
        Self {
            tokens: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Registers an active token along with its subject DID and bound DPoP key thumbprint.
    pub fn register_token(
        &self,
        token: impl AsRef<[u8]>,
        did: impl Into<String>,
        dpop_thumbprint: impl Into<String>,
        scope: Option<String>,
        expires_at: Option<SystemTime>,
    ) {
        let digest = sha256_digest(token.as_ref());
        let mut guard = self.tokens.write();
        guard.insert(
            digest,
            RegisteredToken {
                did: did.into(),
                dpop_thumbprint: dpop_thumbprint.into(),
                scope,
                expires_at,
            },
        );
    }

    /// Registers a token directly from an [`OAuthSession`].
    pub fn register_session(&self, session: &OAuthSession) {
        self.register_token(
            &session.access_token,
            &session.sub,
            session.dpop_key.jwk_thumbprint(),
            session.scope.clone(),
            session.expires_at,
        );
    }

    /// Revokes/removes a registered token.
    pub fn revoke_token(&self, token: &str) {
        let digest = sha256_digest(token.as_bytes());
        let mut guard = self.tokens.write();
        guard.remove(&digest);
    }

    /// Prunes all expired token records from the registry.
    ///
    /// Expired tokens are rejected at validation time regardless; this sweep reclaims
    /// the memory of a long-running process that registers a session per login.
    /// Returns the number of evicted records.
    pub fn prune_expired(&self) -> usize {
        let now = SystemTime::now();
        let mut guard = self.tokens.write();
        let before = guard.len();
        guard.retain(|_, entry| match entry.expires_at {
            Some(exp) => exp > now,
            None => true,
        });
        before - guard.len()
    }

    /// Returns the total number of registered token records (including expired, unpruned ones).
    #[must_use]
    pub fn len(&self) -> usize {
        self.tokens.read().len()
    }

    /// Returns `true` if the registry holds no records.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Validates a presented token synchronously.
    ///
    /// # Errors
    ///
    /// Returns [`IntegrationError`] if the token is not found, expired, or bound to a different key.
    pub fn validate_sync(
        &self,
        token: &str,
        dpop_thumbprint: &str,
    ) -> Result<AuthenticatedUser, IntegrationError> {
        let digest = sha256_digest(token.as_bytes());
        let guard = self.tokens.read();
        let entry = guard.get(&digest).ok_or_else(|| {
            IntegrationError::Token(TokenError::MalformedToken(
                "Access token is not registered or has been revoked".to_string(),
            ))
        })?;

        if let Some(exp) = entry.expires_at {
            let now = SystemTime::now();
            if now > exp {
                let exp_secs = exp
                    .duration_since(UNIX_EPOCH)
                    .map(|d| d.as_secs())
                    .unwrap_or(0);
                let now_secs = now
                    .duration_since(UNIX_EPOCH)
                    .map(|d| d.as_secs())
                    .unwrap_or(0);
                return Err(IntegrationError::Token(TokenError::Expired {
                    exp: exp_secs,
                    now: now_secs,
                }));
            }
        }

        if !constant_time_eq(entry.dpop_thumbprint.as_bytes(), dpop_thumbprint.as_bytes()) {
            return Err(IntegrationError::Token(TokenError::CnfThumbprintMismatch {
                expected_jkt: entry.dpop_thumbprint.clone(),
                actual_jkt: dpop_thumbprint.to_string(),
            }));
        }

        Ok(AuthenticatedUser {
            did: entry.did.clone(),
            access_token: token.to_string(),
            dpop_thumbprint: dpop_thumbprint.to_string(),
            scope: entry.scope.clone(),
        })
    }
}

impl AccessTokenValidator for InMemoryTokenValidator {
    fn validate_access_token(
        &self,
        token: &str,
        dpop_thumbprint: &str,
    ) -> Pin<Box<dyn Future<Output = Result<AuthenticatedUser, IntegrationError>> + Send>> {
        let res = self.validate_sync(token, dpop_thumbprint);
        Box::pin(std::future::ready(res))
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, missing_docs)]
mod tests {
    use super::*;
    use crate::dpop::DPoPKey;
    use p256::ecdsa::SigningKey;
    use rand::thread_rng;
    #[test]
    fn test_jwt_access_token_signing_and_validation_roundtrip() {
        let auth_key = SigningKey::random(&mut thread_rng());
        let auth_verifying_key = *auth_key.verifying_key();

        let client_dpop_key = DPoPKey::generate();
        let client_jkt = client_dpop_key.jwk_thumbprint();

        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let claims = JwtAccessTokenClaims::new(
            "https://auth.example.com",
            "did:plc:alice123",
            now + 3600,
            &client_jkt,
        )
        .with_audience("https://pds.example.com")
        .with_scope("atproto transition:generic");

        let jwt = claims.sign_jwt(&auth_key, None).unwrap();

        let validator = JwtAccessTokenValidator::new()
            .with_verifying_key(auth_verifying_key)
            .with_expected_issuer("https://auth.example.com")
            .with_expected_audience("https://pds.example.com")
            .with_required_scope("atproto");

        let user = validator.verify_token_sync(&jwt, &client_jkt).unwrap();
        assert_eq!(user.did, "did:plc:alice123");
        assert_eq!(user.access_token, jwt);
        assert_eq!(user.dpop_thumbprint, client_jkt);
        assert_eq!(user.scope.as_deref(), Some("atproto transition:generic"));
    }

    #[test]
    fn test_jwt_access_token_cnf_jkt_mismatch_fails() {
        let auth_key = SigningKey::random(&mut thread_rng());
        let auth_verifying_key = *auth_key.verifying_key();

        let alice_dpop_key = DPoPKey::generate();
        let attacker_dpop_key = DPoPKey::generate();

        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let claims = JwtAccessTokenClaims::new(
            "https://auth.example.com",
            "did:plc:alice123",
            now + 3600,
            alice_dpop_key.jwk_thumbprint(),
        )
        .with_audience("https://pds.example.com");

        let jwt = claims.sign_jwt(&auth_key, None).unwrap();

        let validator = JwtAccessTokenValidator::new()
            .with_verifying_key(auth_verifying_key)
            .with_expected_issuer("https://auth.example.com")
            .with_expected_audience("https://pds.example.com");

        let err = validator
            .verify_token_sync(&jwt, &attacker_dpop_key.jwk_thumbprint())
            .unwrap_err();

        assert!(matches!(
            err,
            IntegrationError::Token(TokenError::CnfThumbprintMismatch { .. })
        ));
    }

    #[test]
    fn test_jwt_access_token_expired_fails() {
        let auth_key = SigningKey::random(&mut thread_rng());
        let auth_verifying_key = *auth_key.verifying_key();
        let client_dpop_key = DPoPKey::generate();
        let jkt = client_dpop_key.jwk_thumbprint();

        let claims =
            JwtAccessTokenClaims::new("https://auth.example.com", "did:plc:alice123", 1000, &jkt)
                .with_audience("https://pds.example.com");

        let jwt = claims.sign_jwt(&auth_key, None).unwrap();
        let validator = JwtAccessTokenValidator::new()
            .with_verifying_key(auth_verifying_key)
            .with_expected_issuer("https://auth.example.com")
            .with_expected_audience("https://pds.example.com")
            .with_clock_skew(Duration::ZERO);

        let err = validator.verify_token_sync(&jwt, &jkt).unwrap_err();
        assert!(matches!(
            err,
            IntegrationError::Token(TokenError::Expired { .. })
        ));
    }

    #[test]
    fn test_jwt_access_token_issuer_mismatch_fails() {
        let auth_key = SigningKey::random(&mut thread_rng());
        let auth_verifying_key = *auth_key.verifying_key();
        let client_dpop_key = DPoPKey::generate();
        let jkt = client_dpop_key.jwk_thumbprint();

        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let claims = JwtAccessTokenClaims::new(
            "https://malicious-issuer.example.com",
            "did:plc:alice123",
            now + 3600,
            &jkt,
        )
        .with_audience("https://pds.example.com");

        let jwt = claims.sign_jwt(&auth_key, None).unwrap();
        let validator = JwtAccessTokenValidator::new()
            .with_verifying_key(auth_verifying_key)
            .with_expected_issuer("https://auth.example.com")
            .with_expected_audience("https://pds.example.com");

        let err = validator.verify_token_sync(&jwt, &jkt).unwrap_err();
        assert!(matches!(
            err,
            IntegrationError::Token(TokenError::IssuerMismatch { .. })
        ));
    }

    #[test]
    fn test_jwt_access_token_audience_mismatch_fails() {
        let auth_key = SigningKey::random(&mut thread_rng());
        let auth_verifying_key = *auth_key.verifying_key();
        let client_dpop_key = DPoPKey::generate();
        let jkt = client_dpop_key.jwk_thumbprint();

        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let claims = JwtAccessTokenClaims::new(
            "https://auth.example.com",
            "did:plc:alice123",
            now + 3600,
            &jkt,
        )
        .with_audience("https://other-resource.example.com");

        let jwt = claims.sign_jwt(&auth_key, None).unwrap();
        let validator = JwtAccessTokenValidator::new()
            .with_verifying_key(auth_verifying_key)
            .with_expected_issuer("https://auth.example.com")
            .with_expected_audience("https://pds.example.com");

        let err = validator.verify_token_sync(&jwt, &jkt).unwrap_err();
        assert!(matches!(
            err,
            IntegrationError::Token(TokenError::AudienceMismatch { .. })
        ));
    }

    #[test]
    fn test_in_memory_token_validator_lifecycle() {
        let validator = InMemoryTokenValidator::new();
        let token = "active_session_token_xyz";
        let did = "did:plc:carol789";
        let dpop_key = DPoPKey::generate();
        let jkt = dpop_key.jwk_thumbprint();

        validator.register_token(token, did, &jkt, Some("atproto".to_string()), None);

        let user = validator.validate_sync(token, &jkt).unwrap();
        assert_eq!(user.did, did);
        assert_eq!(user.dpop_thumbprint, jkt);

        let wrong_key = DPoPKey::generate();
        let err = validator
            .validate_sync(token, &wrong_key.jwk_thumbprint())
            .unwrap_err();
        assert!(matches!(
            err,
            IntegrationError::Token(TokenError::CnfThumbprintMismatch { .. })
        ));

        validator.revoke_token(token);
        let err_revoked = validator.validate_sync(token, &jkt).unwrap_err();
        assert!(matches!(
            err_revoked,
            IntegrationError::Token(TokenError::MalformedToken(_))
        ));
    }

    #[test]
    fn test_jwt_access_token_wrong_typ_rejected() {
        // RFC 9068 § 4: a well-signed generic JWT (typ 'JWT' or none) from the same key must be rejected to prevent confusion attacks across token types.
        let auth_key = SigningKey::random(&mut thread_rng());
        let client_jkt = DPoPKey::generate().jwk_thumbprint();
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let claims = JwtAccessTokenClaims::new(
            "https://auth.example.com",
            "did:plc:typ-test",
            now + 3600,
            &client_jkt,
        )
        .with_audience("https://pds.example.com");

        let payload_str = serde_json::to_string(&claims).unwrap();
        let header_typ_jwt = r#"{"alg":"ES256","typ":"JWT"}"#;
        let header_b64 = base64url_encode(header_typ_jwt.as_bytes());
        let payload_b64 = base64url_encode(payload_str.as_bytes());
        let signing_input = format!("{header_b64}.{payload_b64}");
        let sig = sign_p256_raw(&auth_key, signing_input.as_bytes()).unwrap();
        let jwt_wrong_typ = format!("{signing_input}.{}", base64url_encode(&sig));

        let validator = JwtAccessTokenValidator::new()
            .with_verifying_key(*auth_key.verifying_key())
            .with_expected_issuer("https://auth.example.com")
            .with_expected_audience("https://pds.example.com");

        let err = validator
            .verify_token_sync(&jwt_wrong_typ, &client_jkt)
            .unwrap_err();
        assert!(matches!(
            err,
            IntegrationError::Token(TokenError::MalformedToken(ref msg))
                if msg.contains("typ") || msg.contains("at+jwt")
        ));
    }

    #[test]
    fn test_jwt_access_token_unknown_kid_fail_closed() {
        // Fail-closed kid resolution: kid is attacker-controlled, so a well-signed token naming an unknown kid must be rejected, not verified against the registered trusted key.
        let auth_key = SigningKey::random(&mut thread_rng());
        let client_jkt = DPoPKey::generate().jwk_thumbprint();
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let claims = JwtAccessTokenClaims::new(
            "https://auth.example.com",
            "did:plc:kid-test",
            now + 3600,
            &client_jkt,
        )
        .with_audience("https://pds.example.com");

        let payload_str = serde_json::to_string(&claims).unwrap();
        let header_unknown_kid = r#"{"alg":"ES256","typ":"at+jwt","kid":"key-1999"}"#;
        let header_b64 = base64url_encode(header_unknown_kid.as_bytes());
        let payload_b64 = base64url_encode(payload_str.as_bytes());
        let signing_input = format!("{header_b64}.{payload_b64}");
        let sig = sign_p256_raw(&auth_key, signing_input.as_bytes()).unwrap();
        let jwt = format!("{signing_input}.{}", base64url_encode(&sig));

        let validator = JwtAccessTokenValidator::new()
            .with_trusted_key("key-2024", *auth_key.verifying_key())
            .with_expected_issuer("https://auth.example.com")
            .with_expected_audience("https://pds.example.com");

        let err = validator.verify_token_sync(&jwt, &client_jkt).unwrap_err();
        assert!(matches!(err, IntegrationError::AuthFailed(_)));
    }

    #[test]
    fn test_jwt_access_token_missing_audience_rejected() {
        // Fail-closed presence check: aud absence is rejected before expected-audience matching runs.
        let auth_key = SigningKey::random(&mut thread_rng());
        let client_jkt = DPoPKey::generate().jwk_thumbprint();
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let claims_no_aud = JwtAccessTokenClaims::new(
            "https://auth.example.com",
            "did:plc:aud-test",
            now + 3600,
            &client_jkt,
        );
        let jwt_no_aud = claims_no_aud.sign_jwt(&auth_key, None).unwrap();

        let validator = JwtAccessTokenValidator::new()
            .with_verifying_key(*auth_key.verifying_key())
            .with_expected_issuer("https://auth.example.com")
            .with_expected_audience("https://pds.example.com");

        let err = validator
            .verify_token_sync(&jwt_no_aud, &client_jkt)
            .unwrap_err();
        assert!(matches!(
            err,
            IntegrationError::Token(TokenError::MissingAudience)
        ));
    }

    #[test]
    fn test_jwt_access_token_unconfigured_audience_fails_closed() {
        // RFC 9068 § 4 fail-closed gate: without a configured expected audience, every token must be refused rather than any audience accepted (cross-RS confusion).
        let auth_key = SigningKey::random(&mut thread_rng());
        let client_jkt = DPoPKey::generate().jwk_thumbprint();
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let claims = JwtAccessTokenClaims::new(
            "https://auth.example.com",
            "did:plc:aud-closed-test",
            now + 3600,
            &client_jkt,
        )
        .with_audience("https://some-other-resource.example.com");
        let jwt = claims.sign_jwt(&auth_key, None).unwrap();

        let validator = JwtAccessTokenValidator::new()
            .with_verifying_key(*auth_key.verifying_key())
            .with_expected_issuer("https://auth.example.com");

        let err = validator.verify_token_sync(&jwt, &client_jkt).unwrap_err();
        assert!(
            matches!(err, IntegrationError::AuthFailed(ref msg) if msg.contains("audience")),
            "expected misconfiguration (missing expected audience) rejection, got {err:?}"
        );
    }

    #[test]
    fn test_jwt_access_token_unconfigured_issuer_fails_closed() {
        // RFC 9449 § 7.2 fail-closed gate: without a configured expected issuer, every token must be refused rather than any issuer accepted.
        let auth_key = SigningKey::random(&mut thread_rng());
        let client_jkt = DPoPKey::generate().jwk_thumbprint();
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let claims = JwtAccessTokenClaims::new(
            "https://auth.example.com",
            "did:plc:iss-closed-test",
            now + 3600,
            &client_jkt,
        )
        .with_audience("https://pds.example.com");
        let jwt = claims.sign_jwt(&auth_key, None).unwrap();

        let validator = JwtAccessTokenValidator::new()
            .with_verifying_key(*auth_key.verifying_key())
            .with_expected_audience("https://pds.example.com");

        let err = validator.verify_token_sync(&jwt, &client_jkt).unwrap_err();
        assert!(
            matches!(err, IntegrationError::AuthFailed(ref msg) if msg.contains("issuer")),
            "expected misconfiguration (missing expected issuer) rejection, got {err:?}"
        );
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, missing_docs)]
mod m5_enforcement_tests {
    use super::*;
    use p256::ecdsa::SigningKey;
    use rand::thread_rng;

    fn signed_token(claims: &JwtAccessTokenClaims, key: &SigningKey) -> String {
        claims.sign_jwt(key, None).unwrap()
    }

    #[test]
    fn test_m5_exp_boundary_is_exact() {
        // Review M5: a token at exactly `now == exp` (zero leeway) is expired —
        // the previous `now > exp` comparison accepted the boundary instant.
        let key = SigningKey::random(&mut thread_rng());
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();
        let claims = JwtAccessTokenClaims::new(
            "https://auth.example.com",
            "did:plc:alice123",
            now, // exp == now
            "dpop_jkt",
        );
        let token = signed_token(&claims, &key);

        let validator = JwtAccessTokenValidator::new()
            .with_verifying_key(*key.verifying_key())
            .with_expected_issuer("https://auth.example.com")
            .with_expected_audience("https://pds.example.com");
        let res = validator.verify_token_sync(&token, "dpop_jkt");
        assert!(
            matches!(
                res,
                Err(IntegrationError::Token(TokenError::Expired { .. }))
            ),
            "token at the exp boundary must be expired"
        );
    }

    #[test]
    fn test_m5_issuer_comparison_is_exact() {
        // Review M5: trailing-slash normalization previously accepted an issuer
        // differing from the pinned one by a slash.
        let key = SigningKey::random(&mut thread_rng());
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();
        let claims = JwtAccessTokenClaims::new(
            "https://auth.example.com/", // trailing slash vs pinned value
            "did:plc:alice123",
            now + 3600,
            "dpop_jkt",
        );
        let token = signed_token(&claims, &key);

        let validator = JwtAccessTokenValidator::new()
            .with_verifying_key(*key.verifying_key())
            .with_expected_issuer("https://auth.example.com")
            .with_expected_audience("https://pds.example.com");
        let res = validator.verify_token_sync(&token, "dpop_jkt");
        assert!(
            matches!(
                res,
                Err(IntegrationError::Token(TokenError::IssuerMismatch { .. }))
            ),
            "issuer comparison must be exact"
        );
    }

    #[test]
    fn test_m5_wire_rejects_missing_mandatory_claims() {
        // Review M5: RFC 9068 § 2.2 mandates client_id, iat, jti. A token
        // payload missing them must be rejected at deserialization.
        let raw_without_mandatory = r#"{
            "iss": "https://auth.example.com",
            "sub": "did:plc:alice123",
            "exp": 9999999999,
            "scope": "atproto",
            "cnf": {"jkt": "dpop_jkt"}
        }"#;
        let claims: Result<JwtAccessTokenClaims, _> = serde_json::from_str(raw_without_mandatory);
        assert!(
            claims.is_err(),
            "missing client_id/iat/jti must fail deserialization (RFC 9068 § 2.2 mandatory claims)"
        );
    }
}

/// Mutation-killer regression tests (2026-09-07 mutation sweep: the
/// integrations shard, once its config was fixed, measured a 33.3% kill rate
/// with 86 survivors in this file). Each test pins a behavior a surviving
/// mutant had silently broken.
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, missing_docs)]
mod mutation_killer_tests {
    use super::*;
    use crate::dpop::DPoPKey;
    use p256::ecdsa::SigningKey;
    use rand::thread_rng;

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

    fn minted_validator(now: u64) -> (JwtAccessTokenValidator, String, String) {
        let auth_key = SigningKey::random(&mut thread_rng());
        let auth_verifying_key = *auth_key.verifying_key();
        let client_jkt = DPoPKey::generate().jwk_thumbprint();
        let claims = JwtAccessTokenClaims::new(
            "https://auth.example.com",
            "did:plc:alice123",
            now + 3600,
            &client_jkt,
        )
        .with_audience("https://pds.example.com")
        .with_scope("atproto transition:generic");
        let jwt = claims.sign_jwt(&auth_key, None).unwrap();
        let validator = JwtAccessTokenValidator::new()
            .with_verifying_key(auth_verifying_key)
            .with_expected_issuer("https://auth.example.com")
            .with_expected_audience("https://pds.example.com")
            .with_required_scope("atproto");
        (validator, jwt, client_jkt)
    }

    // ---- CnfClaim::jkt() accessor (survivor at line 46) ----

    #[test]
    fn killer_cnf_claim_jkt_accessor() {
        let cnf = CnfClaim::new("thumbprint-abc");
        assert_eq!(
            cnf.jkt(),
            "thumbprint-abc",
            "jkt() must return the stored value"
        );
        assert_ne!(cnf.jkt(), "");
        // Round-trip through serde preserves the accessor's value.
        let round: CnfClaim = serde_json::from_str(&serde_json::to_string(&cnf).unwrap()).unwrap();
        assert_eq!(round.jkt(), "thumbprint-abc");
    }

    // ---- with_trusted_key / with_expected_subject builder effects ----
    // (survivors at lines 257/295: Default::default() mutants)

    #[test]
    fn killer_with_expected_subject_is_enforced() {
        let now = now_secs();
        let (validator, jwt, jkt) = minted_validator(now);
        // Matching subject passes.
        let ok = validator.clone().with_expected_subject("did:plc:alice123");
        assert!(ok.verify_token_sync(&jwt, &jkt).is_ok());
        // Mismatched subject is rejected — the builder must have taken effect.
        let wrong = validator.with_expected_subject("did:plc:bob");
        assert!(
            wrong.verify_token_sync(&jwt, &jkt).is_err(),
            "with_expected_subject must reject a different subject"
        );
    }

    #[test]
    fn killer_with_trusted_key_kid_routing() {
        let now = now_secs();
        let auth_key = SigningKey::random(&mut thread_rng());
        let verifying = *auth_key.verifying_key();
        let jkt = DPoPKey::generate().jwk_thumbprint();
        let claims = JwtAccessTokenClaims::new(
            "https://auth.example.com",
            "did:plc:alice123",
            now + 3600,
            &jkt,
        )
        .with_audience("https://pds.example.com");
        let jwt = claims.sign_jwt(&auth_key, Some("key-2026")).unwrap();

        // Registered kid resolves and validates.
        let validator = JwtAccessTokenValidator::new()
            .with_trusted_key("key-2026", verifying)
            .with_expected_issuer("https://auth.example.com")
            .with_expected_audience("https://pds.example.com");
        assert!(validator.verify_token_sync(&jwt, &jkt).is_ok());

        // A kid the validator does NOT know, while other trusted keys exist,
        // must fail — not silently fall back to the default key.
        let validator2 = JwtAccessTokenValidator::new()
            .with_trusted_key("other-kid", verifying)
            .with_expected_issuer("https://auth.example.com")
            .with_expected_audience("https://pds.example.com");
        assert!(
            validator2.verify_token_sync(&jwt, &jkt).is_err(),
            "unknown kid with non-empty trusted_keys must not fall back"
        );
    }

    // ---- verify_token_sync boundaries (survivors 375/380/416/459/461/481/489) ----

    #[test]
    fn killer_nbf_and_exp_boundaries_are_strict() {
        let auth_key = SigningKey::random(&mut thread_rng());
        let verifying = *auth_key.verifying_key();
        let jkt = DPoPKey::generate().jwk_thumbprint();
        let now = now_secs();

        // nbf in the future beyond leeway: rejected. At now: accepted.
        let future_nbf = JwtAccessTokenClaims::new(
            "https://auth.example.com",
            "did:plc:alice123",
            now + 3600,
            &jkt,
        )
        .with_audience("https://pds.example.com")
        .with_nbf(now + 3600);
        let jwt_future = future_nbf.sign_jwt(&auth_key, None).unwrap();
        let validator = JwtAccessTokenValidator::new()
            .with_verifying_key(verifying)
            .with_expected_issuer("https://auth.example.com")
            .with_expected_audience("https://pds.example.com");
        assert!(
            validator.verify_token_sync(&jwt_future, &jkt).is_err(),
            "nbf far in the future must be rejected"
        );

        // exp boundary: exp == now (leeway 0) is already expired; exp > now
        // is accepted.
        let zero_leeway = validator.with_clock_skew(Duration::ZERO);
        let exp_now =
            JwtAccessTokenClaims::new("https://auth.example.com", "did:plc:alice123", now, &jkt)
                .with_audience("https://pds.example.com");
        let jwt_exp_now = exp_now.sign_jwt(&auth_key, None).unwrap();
        assert!(
            zero_leeway.verify_token_sync(&jwt_exp_now, &jkt).is_err(),
            "exp == now with zero leeway must be expired"
        );

        let live = minted_validator(now);
        assert!(
            live.0.verify_token_sync(&live.1, &live.2).is_ok(),
            "exp > now must validate"
        );
    }

    #[test]
    fn killer_audience_must_match_exactly() {
        let now = now_secs();
        let auth_key = SigningKey::random(&mut thread_rng());
        let verifying = *auth_key.verifying_key();
        let jkt = DPoPKey::generate().jwk_thumbprint();

        // Array-audience containing the expected value: accepted.
        let mut claims = JwtAccessTokenClaims::new(
            "https://auth.example.com",
            "did:plc:alice123",
            now + 3600,
            &jkt,
        );
        claims.aud = Some(serde_json::Value::Array(vec![
            serde_json::Value::String("https://other.example.com".to_string()),
            serde_json::Value::String("https://pds.example.com".to_string()),
        ]));
        let jwt_arr = claims.sign_jwt(&auth_key, None).unwrap();
        let validator = JwtAccessTokenValidator::new()
            .with_verifying_key(verifying)
            .with_expected_issuer("https://auth.example.com")
            .with_expected_audience("https://pds.example.com");
        assert!(
            validator.verify_token_sync(&jwt_arr, &jkt).is_ok(),
            "array audience containing the RS must be accepted"
        );

        // Array audience NOT containing the RS: rejected (the `.any` match
        // arm must be exercised in both directions).
        let mut wrong_claims = JwtAccessTokenClaims::new(
            "https://auth.example.com",
            "did:plc:alice123",
            now + 3600,
            &jkt,
        );
        wrong_claims.aud = Some(serde_json::Value::Array(vec![serde_json::Value::String(
            "https://elsewhere.example.com".to_string(),
        )]));
        let jwt_wrong = wrong_claims.sign_jwt(&auth_key, None).unwrap();
        assert!(
            validator.verify_token_sync(&jwt_wrong, &jkt).is_err(),
            "array audience without the RS must be rejected"
        );

        // Non-string audience value: rejected (unwrap_or(false) arm).
        let mut num_claims = JwtAccessTokenClaims::new(
            "https://auth.example.com",
            "did:plc:alice123",
            now + 3600,
            &jkt,
        );
        num_claims.aud = Some(serde_json::Value::Array(vec![serde_json::Value::from(
            42u64,
        )]));
        let jwt_num = num_claims.sign_jwt(&auth_key, None).unwrap();
        assert!(
            validator.verify_token_sync(&jwt_num, &jkt).is_err(),
            "non-string audience entries must never match"
        );
    }

    #[test]
    fn killer_required_scope_must_be_present() {
        let now = now_secs();
        let auth_key = SigningKey::random(&mut thread_rng());
        let verifying = *auth_key.verifying_key();
        let jkt = DPoPKey::generate().jwk_thumbprint();

        // No scope claim at all + required scope: rejected.
        let claims = JwtAccessTokenClaims::new(
            "https://auth.example.com",
            "did:plc:alice123",
            now + 3600,
            &jkt,
        )
        .with_audience("https://pds.example.com");
        let jwt = claims.sign_jwt(&auth_key, None).unwrap();
        let validator = JwtAccessTokenValidator::new()
            .with_verifying_key(verifying)
            .with_expected_issuer("https://auth.example.com")
            .with_expected_audience("https://pds.example.com")
            .with_required_scope("atproto");
        assert!(
            validator.verify_token_sync(&jwt, &jkt).is_err(),
            "token without scope claim must fail a required-scope check"
        );
    }

    #[test]
    fn kid_routing_none_when_multiple_trusted_keys_and_no_default() {
        // With >1 trusted keys, no default key, and a kid-less token: there is
        // no unambiguous key — validation must fail (not pick one at random).
        let now = now_secs();
        let auth_key = SigningKey::random(&mut thread_rng());
        let verifying = *auth_key.verifying_key();
        let other_key = *SigningKey::random(&mut thread_rng()).verifying_key();
        let jkt = DPoPKey::generate().jwk_thumbprint();
        let claims = JwtAccessTokenClaims::new(
            "https://auth.example.com",
            "did:plc:alice123",
            now + 3600,
            &jkt,
        )
        .with_audience("https://pds.example.com");
        let jwt = claims.sign_jwt(&auth_key, None).unwrap();
        let validator = JwtAccessTokenValidator::new()
            .with_trusted_key("kid-a", verifying)
            .with_trusted_key("kid-b", other_key)
            .with_expected_issuer("https://auth.example.com")
            .with_expected_audience("https://pds.example.com");
        assert!(
            validator.verify_token_sync(&jwt, &jkt).is_err(),
            "kid-less token with multiple trusted keys and no default must fail"
        );
    }

    // ---- InMemoryTokenValidator lifecycle (survivors 584-648) ----

    #[test]
    fn killer_in_memory_validator_full_lifecycle() {
        let store = InMemoryTokenValidator::new();
        assert!(store.is_empty(), "fresh store must be empty");
        assert_eq!(store.len(), 0, "fresh store len must be 0");

        // register_token + validate_sync happy path.
        store.register_token(
            "token-a",
            "did:plc:alice123",
            "jkt-a",
            Some("atproto".to_string()),
            Some(SystemTime::now() + Duration::from_secs(3600)),
        );
        assert_eq!(store.len(), 1, "len must count registered tokens");
        assert!(!store.is_empty());
        let user = store.validate_sync("token-a", "jkt-a").unwrap();
        assert_eq!(user.did, "did:plc:alice123");
        assert_eq!(user.access_token, "token-a");
        assert_eq!(user.dpop_thumbprint, "jkt-a");
        assert_eq!(user.scope.as_deref(), Some("atproto"));

        // Wrong thumbprint: rejected.
        assert!(
            store.validate_sync("token-a", "jkt-b").is_err(),
            "mismatched thumbprint must be rejected"
        );
        // Unknown token: rejected.
        assert!(
            store.validate_sync("never-registered", "jkt-a").is_err(),
            "unknown token must be rejected"
        );

        // revoke_token removes exactly the target.
        store.register_token(
            "token-b",
            "did:plc:bob",
            "jkt-b",
            None,
            Some(SystemTime::now() + Duration::from_secs(3600)),
        );
        assert_eq!(store.len(), 2);
        store.revoke_token("token-a");
        assert_eq!(store.len(), 1, "revoke must remove exactly one entry");
        assert!(store.validate_sync("token-a", "jkt-a").is_err());
        assert!(store.validate_sync("token-b", "jkt-b").is_ok());

        // prune_expired evicts only expired entries; count is exact.
        store.register_token(
            "token-expired",
            "did:plc:expired",
            "jkt-e",
            None,
            Some(SystemTime::now() - Duration::from_secs(1)),
        );
        assert_eq!(store.len(), 2);
        let pruned = store.prune_expired();
        assert_eq!(
            pruned, 1,
            "prune_expired must evict exactly the expired entry"
        );
        assert_eq!(store.len(), 1);
        assert!(store.validate_sync("token-expired", "jkt-e").is_err());
        assert!(store.validate_sync("token-b", "jkt-b").is_ok());

        // Expired tokens are rejected at validation time with the exact
        // boundary: expires_at == now is already expired (strict >).
        store.register_token(
            "token-now",
            "did:plc:now",
            "jkt-n",
            None,
            Some(SystemTime::now()),
        );
        assert!(
            store.validate_sync("token-now", "jkt-n").is_err(),
            "expires_at == now must be expired"
        );
    }

    #[test]
    fn killer_register_session_binds_session_thumbprint() {
        let key = DPoPKey::generate();
        let session = crate::session::OAuthSession::new(
            "did:plc:alice123",
            "at_session_token",
            None,
            "DPoP",
            Some("atproto".to_string()),
            Some(3600),
            key.clone(),
            None,
            None,
            None,
        )
        .unwrap();
        let expected_jkt = key.jwk_thumbprint();
        let store = InMemoryTokenValidator::new();
        store.register_session(&session);
        assert_eq!(store.len(), 1);
        // Correct thumbprint validates and carries the session DID/scope.
        let user = store
            .validate_sync("at_session_token", &expected_jkt)
            .unwrap();
        assert_eq!(user.did, "did:plc:alice123");
        assert_eq!(user.scope.as_deref(), Some("atproto"));
        // A different thumbprint is rejected — register_session must bind
        // the session's real key.
        assert!(store
            .validate_sync("at_session_token", "some-other-jkt")
            .is_err());
    }
}