oauth-resource-server 0.2.0

OAuth 2.0 bearer-token resource server for Rust HTTP services: JWT access-token validation against a JWKS, RFC 9728 protected-resource metadata, RFC 6750 challenges, optional static API key, axum integration.
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
//! What a validation produces: the accepted token ([`AuthorizedToken`]) or the
//! reason it was refused ([`TokenRejection`]), plus the claim readers and the
//! header `typ` check that feed them.

use std::collections::HashSet;
use std::fmt;
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use serde::de::DeserializeOwned;
use serde_json::{Map, Value};

use crate::config::KeyNamingBuf;

/// Cap on a presented credential. Real access tokens are well under 8 KiB even
/// with group claims; anything larger is refused before it is base64-decoded.
pub(crate) const MAX_TOKEN_BYTES: usize = 16 * 1024;

/// Cap on any token-derived string that reaches a log line (`kid`, `typ`,
/// principal). A signed claim is trustworthy but not necessarily short, and an
/// unverified header field is neither.
pub(crate) const MAX_LOGGED_CHARS: usize = 128;

/// What [`AuthorizedToken::new`] puts in `expires_at`: 2100-01-01T00:00:00Z.
const FAR_FUTURE_SECS: u64 = 4_102_444_800;

/// A successfully validated access token. The axum middleware (feature `axum`)
/// inserts it into request extensions, so handlers can read who called and with
/// which scopes.
///
/// The scopes come from the one place that actually verified them, so a handler
/// enforcing a finer-grained scope (say, a write scope on some routes) should ask
/// [`AuthorizedToken::has_scope`] rather than re-parse the header.
///
/// # The verified claims
///
/// Besides the fields below, the token keeps the whole claim set the signature
/// covered, read with [`AuthorizedToken::claims`] (raw) or
/// [`AuthorizedToken::claims_as`] (into your own type), for anything this crate
/// has no field for: `groups`, `roles`, `email`, a tenant id. There is no need to
/// decode the JWT a second time in a handler. The claims are stored once and
/// shared (`Arc`), so cloning a token is cheap. Their size is bounded by the
/// credential cap: a token is refused above 16 KiB before it is decoded, so
/// the stored claims cannot outgrow that (their parsed in-memory form is a small
/// multiple of it).
///
/// # Debug
///
/// `Debug` prints every field except the claim *values*: the claims appear as
/// their names only. Claims routinely carry personal data (`email`, `name`,
/// group memberships) and a `{token:?}` in a log line or a panic message must
/// not leak it. `subject`, `principal` and `client_id` are printed, as they
/// always have been (`subject`, `principal`) or are identifiers meant for logs.
/// Read values deliberately through [`AuthorizedToken::claims`].
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct AuthorizedToken {
    /// The token's `sub`, verbatim, when it carried one as a string. It is
    /// signed, so it is safe to key per-user decisions on (it is bounded only
    /// by the 16 KiB credential cap); this crate's own log lines truncate it.
    pub subject: Option<String>,
    /// The first present, non-empty string claim of
    /// [`crate::OAuthConfig::principal_claims`], verbatim — who the request is
    /// from, for logs and attribution. Never the token itself. Which claim it
    /// came from depends on config, so key authorization on
    /// [`AuthorizedToken::subject`] rather than on this.
    pub principal: Option<String>,
    /// The union of every [`crate::OAuthConfig::scope_claims`] claim, in
    /// first-seen order, deduplicated.
    pub scopes: Vec<String>,
    /// The token's `iss`: the exact string that matched the configured issuer.
    /// Empty on a token built with [`AuthorizedToken::new`].
    pub issuer: String,
    /// The token's `aud`, normalized to a list whether the token carried a
    /// single string or an array (non-string entries are dropped). On a
    /// validated token at least one entry is a configured audience. Empty on a
    /// token built with [`AuthorizedToken::new`].
    pub audiences: Vec<String>,
    /// The token's `exp`. A validated token was not expired at the moment of
    /// validation (within the configured leeway), so a long-lived connection,
    /// such as an SSE stream, can close itself at this instant. A fractional
    /// `exp` is rounded to whole seconds exactly as the validation rounded it, and
    /// one later than 9999-12-31T23:59:59Z saturates to that instant. A token built
    /// with [`AuthorizedToken::new`] gets 2100-01-01T00:00:00Z.
    pub expires_at: SystemTime,
    /// The token's `iat`, when it carried a valid NumericDate. Checked only
    /// when [`crate::OAuthConfig::max_token_age_secs`] is set. Rounded and saturated like
    /// [`expires_at`](Self::expires_at); `None` when `iat` is absent or not a
    /// non-negative number (the token is still accepted then). `None` on a token built with [`AuthorizedToken::new`].
    pub issued_at: Option<SystemTime>,
    /// The OAuth client the token was issued to: `client_id` (RFC 9068 §2.2),
    /// else `azp`, the first that is a non-empty string. The
    /// [`crate::OAuthConfig::allowed_client_ids`] check reads the same claims
    /// more strictly: there, a `client_id` that is present but empty or not a
    /// string refuses the token instead of falling through to `azp`. `None` when the token
    /// carries neither, and on a token built with [`AuthorizedToken::new`].
    pub client_id: Option<String>,
    /// The token's `jti`, when it carried one as a non-empty string. `None` on
    /// a token built with [`AuthorizedToken::new`].
    pub jti: Option<String>,
    claims: Arc<Map<String, Value>>,
}

impl fmt::Debug for AuthorizedToken {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AuthorizedToken")
            .field("subject", &self.subject)
            .field("principal", &self.principal)
            .field("scopes", &self.scopes)
            // The configured issuer, which may carry userinfo.
            .field("issuer", &crate::jwks::debug_url(&self.issuer))
            .field("audiences", &self.audiences)
            .field("expires_at", &self.expires_at)
            .field("issued_at", &self.issued_at)
            .field("client_id", &self.client_id)
            .field("jti", &self.jti)
            // Names only: the values may be personal data.
            .field("claims", &self.claims.keys().collect::<Vec<_>>())
            .finish()
    }
}

/// The latest time a token timestamp maps to: 9999-12-31T23:59:59Z. A claim later
/// than this (`jsonwebtoken` accepts an `exp` up to `u64::MAX`, more than
/// `SystemTime` can hold on every platform) saturates here instead of failing,
/// so a validly signed, far-future `exp` never reads as already expired.
const MAX_TIMESTAMP_SECS: u64 = 253_402_300_799;

/// The token's own timestamp claim as a point in time, read the way
/// `jsonwebtoken` reads `exp` and `nbf` (its `numeric_type` deserializer): a
/// non-negative integer, or a finite non-negative float rounded to the nearest
/// whole second (half away from zero). Anything later than
/// [`MAX_TIMESTAMP_SECS`] saturates to it. `None` for anything else (a string, a
/// negative, a non-finite or out-of-`u64` number). Never panics.
fn numeric_date(value: &Value) -> Option<SystemTime> {
    let secs = numeric_date_secs(value)?;
    Some(UNIX_EPOCH + Duration::from_secs(secs))
}

/// [`numeric_date`] as whole seconds since the epoch, saturated the same way.
pub(crate) fn numeric_date_secs(value: &Value) -> Option<u64> {
    let secs = match value.as_u64() {
        Some(secs) => secs,
        None => {
            let f = value.as_f64()?;
            if !(f.is_finite() && f >= 0.0 && f < u64::MAX as f64) {
                return None;
            }
            f.round() as u64
        }
    };
    Some(secs.min(MAX_TIMESTAMP_SECS))
}

/// The OAuth client a token was issued to: `client_id` (RFC 9068 §2.2), else
/// `azp`, the first that is a non-empty string. The one reading of it, shared
/// by [`AuthorizedToken::client_id`] and the `allowed_client_ids` check.
pub(crate) fn client_id_of(claims: &Map<String, Value>) -> Option<&str> {
    ["client_id", "azp"].into_iter().find_map(|name| {
        claims
            .get(name)
            .and_then(Value::as_str)
            .filter(|s| !s.is_empty())
    })
}

/// `aud` as a list: a string is one audience, an array contributes its string
/// entries.
fn audiences_of(claims: &Map<String, Value>) -> Vec<String> {
    match claims.get("aud") {
        Some(Value::String(s)) => vec![s.clone()],
        Some(Value::Array(items)) => items
            .iter()
            .filter_map(Value::as_str)
            .map(str::to_string)
            .collect(),
        _ => Vec::new(),
    }
}

impl AuthorizedToken {
    /// Fill every field from a token's claims, with `subject`, `principal` and
    /// `scopes` already extracted by the caller. Only called on claims a
    /// signature verification produced. An `exp` that cannot be read (which
    /// the decoder has already refused, as it is required) would read as the
    /// epoch, i.e. expired, never as "never expires".
    pub(crate) fn from_verified_claims(
        claims: Map<String, Value>,
        subject: Option<String>,
        principal: Option<String>,
        scopes: Vec<String>,
    ) -> Self {
        let string_claim = |name: &str| {
            claims
                .get(name)
                .and_then(Value::as_str)
                .filter(|s| !s.is_empty())
                .map(str::to_string)
        };
        Self {
            subject,
            principal,
            scopes,
            issuer: claims
                .get("iss")
                .and_then(Value::as_str)
                .unwrap_or_default()
                .to_string(),
            audiences: audiences_of(&claims),
            expires_at: claims
                .get("exp")
                .and_then(numeric_date)
                .unwrap_or(UNIX_EPOCH),
            issued_at: claims.get("iat").and_then(numeric_date),
            client_id: client_id_of(&claims).map(str::to_string),
            jti: string_claim("jti"),
            claims: Arc::new(claims),
        }
    }

    /// Build a token record from parts, with `scopes` deduplicated in
    /// first-seen order (blank entries dropped), as a validation produces them.
    ///
    /// This verifies nothing — it is a plain value constructor for code that
    /// needs an `AuthorizedToken` without a validation, chiefly tests that place
    /// one in request extensions. [`crate::OAuthValidator::validate`] is the only
    /// source of a token that was actually checked. The struct is
    /// `#[non_exhaustive]`, so a field added later gets a default here rather
    /// than breaking callers.
    ///
    /// The fields beyond the three arguments get test-friendly defaults: empty
    /// `issuer`, `audiences` and [`claims`](Self::claims), `None` for
    /// `issued_at`, `client_id` and `jti`, and an `expires_at` of
    /// 2100-01-01T00:00:00Z. The far-future expiry is deliberate: a handler
    /// that closes a stream when the token expires must not see a fixture as
    /// already expired. Set any of them with the `with_*` builders.
    pub fn new(
        subject: Option<String>,
        principal: Option<String>,
        scopes: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        let mut deduped: Vec<String> = Vec::new();
        for scope in scopes {
            let scope = scope.into();
            let scope = scope.trim();
            if !scope.is_empty() && !deduped.iter().any(|s| s == scope) {
                deduped.push(scope.to_string());
            }
        }
        Self {
            subject,
            principal,
            scopes: deduped,
            issuer: String::new(),
            audiences: Vec::new(),
            expires_at: UNIX_EPOCH + Duration::from_secs(FAR_FUTURE_SECS),
            issued_at: None,
            client_id: None,
            jti: None,
            claims: Arc::new(Map::new()),
        }
    }

    /// The verified claim set, exactly as the token carried it: every claim the
    /// signature covered, including the ones with their own field here.
    /// Empty for a token built with [`AuthorizedToken::new`] unless
    /// [`with_claims`](Self::with_claims) was used.
    ///
    /// # Security
    ///
    /// Claims are trustworthy only on a token a validation produced; one from
    /// [`AuthorizedToken::new`] holds whatever the caller put there. Claim
    /// values can be personal data, so [`Debug`](fmt::Debug) does not print them.
    ///
    /// # Examples
    ///
    /// ```
    /// use oauth_resource_server::AuthorizedToken;
    /// use serde_json::json;
    ///
    /// let token = AuthorizedToken::new(Some("user-1".into()), None, ["api:read"])
    ///     .with_claims(json!({"groups": ["admins", "dev"]}).as_object().unwrap().clone());
    /// let in_admins = token.claims()["groups"]
    ///     .as_array()
    ///     .is_some_and(|g| g.iter().any(|v| v == "admins"));
    /// assert!(in_admins);
    /// ```
    pub fn claims(&self) -> &Map<String, Value> {
        &self.claims
    }

    /// The verified claim set deserialized into your own type, for a typed view
    /// of the claims your application cares about. Unknown claims are ignored
    /// unless your type says otherwise (`deny_unknown_fields`). The claim map is
    /// cloned to deserialize it, so call this once per request, not per field.
    ///
    /// # Errors
    ///
    /// [`serde_json::Error`] when the claims do not fit `T`, for example a
    /// required field the token did not carry or one of the wrong type.
    ///
    /// # Examples
    ///
    /// ```
    /// use oauth_resource_server::AuthorizedToken;
    /// use serde::Deserialize;
    /// use serde_json::json;
    ///
    /// #[derive(Deserialize)]
    /// struct Claims {
    ///     email: String,
    ///     #[serde(default)]
    ///     groups: Vec<String>,
    /// }
    ///
    /// let token = AuthorizedToken::new(None, None, ["api:read"]).with_claims(
    ///     json!({"email": "ada@example.com", "groups": ["admins"]})
    ///         .as_object()
    ///         .unwrap()
    ///         .clone(),
    /// );
    /// let claims: Claims = token.claims_as().unwrap();
    /// assert_eq!(claims.email, "ada@example.com");
    /// assert_eq!(claims.groups, ["admins"]);
    /// ```
    pub fn claims_as<T: DeserializeOwned>(&self) -> Result<T, serde_json::Error> {
        serde_json::from_value(Value::Object((*self.claims).clone()))
    }

    /// Replace the claim set, for building a token in a test. Only the claim
    /// set changes: the typed fields ([`issuer`](Self::issuer),
    /// [`client_id`](Self::client_id), …) are not re-derived from it, so set
    /// them with their own `with_*` builders. Verifies nothing.
    #[must_use]
    pub fn with_claims(mut self, claims: Map<String, Value>) -> Self {
        self.claims = Arc::new(claims);
        self
    }

    /// Set [`issuer`](Self::issuer), for building a token in a test.
    #[must_use]
    pub fn with_issuer(mut self, issuer: impl Into<String>) -> Self {
        self.issuer = issuer.into();
        self
    }

    /// Set [`audiences`](Self::audiences), for building a token in a test.
    #[must_use]
    pub fn with_audiences(
        mut self,
        audiences: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        self.audiences = audiences.into_iter().map(Into::into).collect();
        self
    }

    /// Set [`expires_at`](Self::expires_at), for building a token in a test.
    #[must_use]
    pub fn with_expires_at(mut self, expires_at: SystemTime) -> Self {
        self.expires_at = expires_at;
        self
    }

    /// Set [`issued_at`](Self::issued_at), for building a token in a test.
    #[must_use]
    pub fn with_issued_at(mut self, issued_at: SystemTime) -> Self {
        self.issued_at = Some(issued_at);
        self
    }

    /// Set [`client_id`](Self::client_id), for building a token in a test.
    #[must_use]
    pub fn with_client_id(mut self, client_id: impl Into<String>) -> Self {
        self.client_id = Some(client_id.into());
        self
    }

    /// Set [`jti`](Self::jti), for building a token in a test.
    #[must_use]
    pub fn with_jti(mut self, jti: impl Into<String>) -> Self {
        self.jti = Some(jti.into());
        self
    }

    /// Whether the token carries `scope` (exact, case-sensitive match, RFC 6749
    /// §3.3). The single place that answers the question, so callers never
    /// hand-roll a `.iter().any()` over `scopes`.
    ///
    /// # Examples
    ///
    /// ```
    /// use oauth_resource_server::AuthorizedToken;
    ///
    /// let token = AuthorizedToken::new(Some("user-1".into()), None, ["api:read", "api:write"]);
    /// assert!(token.has_scope("api:write"));
    /// assert!(!token.has_scope("API:WRITE"));
    /// ```
    pub fn has_scope(&self, scope: &str) -> bool {
        self.scopes.iter().any(|s| s == scope)
    }

    /// Whether the token carries EVERY scope in `required` (all-of): `Ok(())`,
    /// or the [`MissingScopes`] naming what it lacks. An empty `required`
    /// passes every token.
    ///
    /// The same matching the validator's own `required_scopes` check runs, on
    /// the same [`scopes`](Self::scopes) (every configured scope claim, a
    /// string split on whitespace, an array taken element by element), so a
    /// route asking for a scope here and a validator requiring it agree
    /// exactly: an exact, case-sensitive comparison per scope (RFC 6749 §3.3).
    /// An entry that is blank or contains whitespace can never be carried, so
    /// it is always missing.
    ///
    /// This is the per-route or per-operation check on top of the
    /// validator's floor; the layers' `require_scopes`, the `axum` feature's
    /// `RequireScopes` and `Scoped` extractor, and the `mcp` feature all run
    /// it. To answer a refusal with a 403 whose challenge names these scopes,
    /// see [`crate::refusal_for_scopes`]; `?` converts the error into
    /// [`TokenRejection::InsufficientScope`].
    ///
    /// # Errors
    ///
    /// [`MissingScopes`] when at least one entry of `required` is not among
    /// the token's scopes.
    ///
    /// # Examples
    ///
    /// ```
    /// use oauth_resource_server::AuthorizedToken;
    ///
    /// let token = AuthorizedToken::new(None, None, ["docs:read"]);
    /// assert!(token.require_scopes(&["docs:read"]).is_ok());
    ///
    /// let missing = token.require_scopes(&["docs:read", "docs:write"]).unwrap_err();
    /// assert_eq!(missing.required(), ["docs:read", "docs:write"]);
    /// assert_eq!(missing.missing(), ["docs:write"]);
    /// ```
    pub fn require_scopes(&self, required: &[&str]) -> Result<(), MissingScopes> {
        let missing = missing_scopes(&self.scopes, required.iter().copied());
        if missing.is_empty() {
            return Ok(());
        }
        Err(MissingScopes {
            required: required.iter().map(|s| (*s).to_string()).collect(),
            missing: missing.into_iter().map(str::to_string).collect(),
        })
    }
}

/// The entries of `required` that `present` does not carry, in order: the one
/// scope-matching rule, shared by the validator's `required_scopes` check and
/// [`AuthorizedToken::require_scopes`] (exact, case-sensitive, all-of).
pub(crate) fn missing_scopes<'r>(
    present: &[String],
    required: impl IntoIterator<Item = &'r str>,
) -> Vec<&'r str> {
    required
        .into_iter()
        .filter(|required| !present.iter().any(|p| p == required))
        .collect()
}

/// A token that is valid but lacks scopes a route or operation requires; see
/// [`AuthorizedToken::require_scopes`]. It answers with 403
/// `insufficient_scope`: convert it with `?` (or `From`) into
/// [`TokenRejection::InsufficientScope`], and build the response with
/// [`crate::refusal_for_scopes`] so the challenge names what was required.
///
/// Scopes are not secret; `Display` names the missing ones.
///
/// `#[non_exhaustive]`: read it through its accessors.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("insufficient scope: missing {}", .missing.join(" "))]
#[non_exhaustive]
pub struct MissingScopes {
    required: Vec<String>,
    missing: Vec<String>,
}

impl MissingScopes {
    /// Every scope that was required, in the order given.
    pub fn required(&self) -> &[String] {
        &self.required
    }

    /// The required scopes the token does not carry, in the order given;
    /// never empty.
    pub fn missing(&self) -> &[String] {
        &self.missing
    }
}

impl From<MissingScopes> for TokenRejection {
    fn from(_: MissingScopes) -> Self {
        TokenRejection::InsufficientScope
    }
}

/// Why a bearer credential was refused, and — crucially — with which HTTP status.
///
/// The split is the whole point: RFC 6750 distinguishes "this token is not good"
/// (401 `invalid_token`, go get a new one) from "this token is fine but not
/// sufficient" (403 `insufficient_scope`). A client that gets 401 for an
/// insufficient-scope token will loop through the authorization flow forever and
/// land back on the same refusal.
///
/// | Variant | Status | `WWW-Authenticate` (with OAuth configured) |
/// |---|---|---|
/// | [`Missing`](Self::Missing) | 401 | [`crate::OAuthValidator::invalid_token_challenge`] |
/// | [`Invalid`](Self::Invalid) | 401 | [`crate::OAuthValidator::invalid_token_challenge`] |
/// | [`InsufficientScope`](Self::InsufficientScope) | 403 | [`crate::OAuthValidator::insufficient_scope_challenge`] |
///
/// `#[non_exhaustive]`: treat a variant this code does not know as a 401.
///
/// It implements [`std::error::Error`], so `?` carries it into
/// `Box<dyn Error>` or `anyhow`. `Display` deliberately renders the category
/// only — `missing credential`, `invalid token`, `insufficient scope` — and
/// never [`Invalid`](Self::Invalid)'s reason, so a careless `format!("{e}")`
/// in a response body cannot tell a caller which check failed. The reason is
/// reachable through the variant itself ([`InvalidToken`]) and through
/// `Debug`, for logs.
///
/// ```
/// use oauth_resource_server::{InvalidToken, InvalidTokenKind, TokenRejection};
///
/// let e = TokenRejection::Invalid(InvalidToken::new(
///     InvalidTokenKind::WrongAudience,
///     "token rejected: InvalidAudience",
/// ));
/// assert_eq!(e.to_string(), "invalid token");
/// assert!(format!("{e:?}").contains("InvalidAudience"));
/// ```
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum TokenRejection {
    /// 401: the request carried no credential at all. Separate from `Invalid` so
    /// a server can log it quietly — every OAuth client's first request looks
    /// like this — not because the response differs (it should not: a missing
    /// credential gets the same `invalid_token` challenge as a bad one).
    #[error("missing credential")]
    Missing,
    /// 401 `invalid_token`: malformed, unsigned, wrong issuer/audience/type,
    /// expired, or signed by a key we could not obtain. The
    /// [`InvalidToken`] says which check failed: its
    /// [`kind`](InvalidToken::kind) is stable and matchable (a metrics label
    /// via [`InvalidTokenKind::as_str`]), its [`detail`](InvalidToken::detail)
    /// is for logs only — never return it to the caller, since telling an
    /// unauthenticated client exactly which check failed is a free oracle.
    #[error("invalid token")]
    Invalid(InvalidToken),
    /// 403 `insufficient_scope`: signature, issuer, audience and expiry all
    /// passed, but the token does not carry every required scope.
    #[error("insufficient scope")]
    InsufficientScope,
}

impl TokenRejection {
    /// `Invalid` of `kind`: the one constructor every refusal this crate makes
    /// goes through, so each site names its kind.
    pub(crate) fn invalid(kind: InvalidTokenKind, detail: impl Into<String>) -> Self {
        Self::Invalid(InvalidToken::new(kind, detail))
    }
}

/// Why a credential was refused as [`TokenRejection::Invalid`]: a stable,
/// matchable [`kind`](Self::kind) and a log-only [`detail`](Self::detail).
///
/// `Display` (and `Deref<Target = str>`) is the detail — the same reason text
/// `Invalid` carried as a `String` before 0.2.0 — so logging it, calling
/// `str` methods on it and comparing it with a string literal keep working.
/// Match on [`kind`](Self::kind), never on the text: the kind a given refusal
/// carries is part of this crate's semver contract, its wording is not.
///
/// Equality compares the **detail only** — between two `InvalidToken`s as
/// with a `str` or `String` — so a 0.1-style
/// `assert_eq!(r, TokenRejection::Invalid("..".into()))` keeps passing
/// against a refusal the crate made. Assert [`kind`](Self::kind) separately
/// when the kind matters. With the `serde` feature it serializes as its
/// kind's [`as_str`](InvalidTokenKind::as_str) label (`"expired"`), never
/// the detail, so a serialized refusal cannot leak the log-only text.
///
/// # Security
///
/// The detail names the check that failed and can quote token-derived text
/// (truncated). Log it; never put it in a response body, where it would be a
/// free oracle for an unauthenticated caller. The kind's
/// [`as_str`](InvalidTokenKind::as_str) label is low-cardinality and meant for
/// metrics and logs; this crate's own responses never carry it either.
///
/// # Examples
///
/// ```
/// use oauth_resource_server::{InvalidToken, InvalidTokenKind, TokenRejection};
///
/// fn metrics_label(rejection: &TokenRejection) -> &'static str {
///     match rejection {
///         TokenRejection::Missing => "missing",
///         TokenRejection::Invalid(invalid) => invalid.kind().as_str(),
///         TokenRejection::InsufficientScope => "insufficient_scope",
///         _ => "other",
///     }
/// }
///
/// let expired = TokenRejection::Invalid(InvalidToken::new(
///     InvalidTokenKind::Expired,
///     "token rejected: ExpiredSignature",
/// ));
/// assert_eq!(metrics_label(&expired), "expired");
///
/// // The 0.1 shapes still compile: a string converts (kind `Other`), and the
/// // reason reads as a `str`.
/// let legacy = TokenRejection::Invalid("custom refusal".into());
/// if let TokenRejection::Invalid(reason) = &legacy {
///     assert_eq!(reason.kind(), InvalidTokenKind::Other);
///     assert!(reason.contains("custom"));
///     assert_eq!(reason, "custom refusal");
///     assert_eq!(reason.to_string(), "custom refusal");
/// }
/// ```
///
/// A `String` expression needs `.into()`: `Invalid(format!(..))` does not
/// compile, `Invalid(format!(..).into())` does.
///
/// ```compile_fail
/// # use oauth_resource_server::TokenRejection;
/// let _ = TokenRejection::Invalid(format!("{} candidates", 3));
/// ```
// Equality is hand-written, on the detail only (see the type docs). If `Hash`
// is ever added it must hash the detail only too, or `a == b` would no longer
// imply `hash(a) == hash(b)`.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct InvalidToken {
    kind: InvalidTokenKind,
    detail: String,
}

impl InvalidToken {
    /// A refusal of `kind`, with `detail` for the log. Every refusal this
    /// crate makes is built here; an application building its own (in a test,
    /// or for a check of its own) can name a kind the same way.
    pub fn new(kind: InvalidTokenKind, detail: impl Into<String>) -> Self {
        Self {
            kind,
            detail: detail.into(),
        }
    }

    /// Which check refused the token: stable and matchable, see
    /// [`InvalidTokenKind`].
    pub fn kind(&self) -> InvalidTokenKind {
        self.kind
    }

    /// The human-readable reason, for logs only (see the type's `# Security`).
    /// Its wording may change in any release.
    pub fn detail(&self) -> &str {
        &self.detail
    }

    /// The same as [`detail`](Self::detail), under the name 0.1's `String`
    /// reason offered (`reason.as_str()`).
    pub fn as_str(&self) -> &str {
        &self.detail
    }
}

/// Detail only; see the type docs.
impl PartialEq for InvalidToken {
    fn eq(&self, other: &Self) -> bool {
        self.detail == other.detail
    }
}

impl Eq for InvalidToken {}

/// The detail, so `std::error::Error` consumers (`Box<dyn Error>`, `?` into
/// `anyhow`) take an `InvalidToken` as they took the `String`. Log-only, like
/// the detail itself.
impl std::error::Error for InvalidToken {}

/// Serializes as the kind's [`as_str`](InvalidTokenKind::as_str) label — a
/// string such as `"expired"` — never the [`detail`](InvalidToken::detail):
/// a `#[derive(Serialize)]` response type or `json!({"reason": reason})`
/// would otherwise carry the log-only text into a body. Serialize
/// `reason.detail()` explicitly where the detail is wanted, in a log record.
#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl serde::Serialize for InvalidToken {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.kind.as_str())
    }
}

/// The detail, as the 0.1 `String` was.
impl From<InvalidToken> for String {
    fn from(invalid: InvalidToken) -> Self {
        invalid.detail
    }
}

impl fmt::Display for InvalidToken {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.detail)
    }
}

/// Kind [`InvalidTokenKind::Other`]: what a 0.1-style
/// `TokenRejection::Invalid(reason.into())` builds.
impl From<String> for InvalidToken {
    fn from(detail: String) -> Self {
        Self::new(InvalidTokenKind::Other, detail)
    }
}

/// Kind [`InvalidTokenKind::Other`]: what a 0.1-style
/// `TokenRejection::Invalid("reason".into())` builds.
impl From<&str> for InvalidToken {
    fn from(detail: &str) -> Self {
        Self::new(InvalidTokenKind::Other, detail)
    }
}

/// The [`detail`](InvalidToken::detail), so `str` methods (`contains`,
/// `starts_with`, ...) keep working on a 0.1-style `Invalid(reason)` binding.
impl std::ops::Deref for InvalidToken {
    type Target = str;

    fn deref(&self) -> &str {
        &self.detail
    }
}

/// Compares the [`detail`](InvalidToken::detail) only.
impl PartialEq<str> for InvalidToken {
    fn eq(&self, other: &str) -> bool {
        self.detail == other
    }
}

/// Compares the [`detail`](InvalidToken::detail) only.
impl PartialEq<&str> for InvalidToken {
    fn eq(&self, other: &&str) -> bool {
        self.detail == *other
    }
}

/// Compares the [`detail`](InvalidToken::detail) only.
impl PartialEq<String> for InvalidToken {
    fn eq(&self, other: &String) -> bool {
        self.detail == *other
    }
}

/// Compares the [`detail`](InvalidToken::detail) only.
impl PartialEq<InvalidToken> for str {
    fn eq(&self, other: &InvalidToken) -> bool {
        self == other.detail
    }
}

/// Compares the [`detail`](InvalidToken::detail) only.
impl PartialEq<InvalidToken> for &str {
    fn eq(&self, other: &InvalidToken) -> bool {
        *self == other.detail
    }
}

/// Compares the [`detail`](InvalidToken::detail) only.
impl PartialEq<InvalidToken> for String {
    fn eq(&self, other: &InvalidToken) -> bool {
        *self == other.detail
    }
}

/// Which check refused a token — see [`InvalidToken::kind`].
///
/// Each kind names one family of checks, and [`as_str`](Self::as_str) gives it
/// a stable, low-cardinality `snake_case` label for metrics and alerting (for
/// example, [`KeySetUnavailable`](Self::KeySetUnavailable) is an
/// authorization-server outage, not junk traffic). Every kind is a 401
/// `invalid_token`; the kind changes nothing about the response.
///
/// `#[non_exhaustive]`: a kind may be added in a minor release, so match with a
/// wildcard arm. Which kind an existing refusal carries, and each kind's label,
/// are stable; the [`InvalidToken::detail`] text is not.
///
/// # Examples
///
/// ```
/// use oauth_resource_server::{InvalidToken, InvalidTokenKind};
///
/// /// Whether a refusal points at the authorization server rather than at the
/// /// caller — worth an alert of its own.
/// fn is_idp_trouble(invalid: &InvalidToken) -> bool {
///     match invalid.kind() {
///         InvalidTokenKind::KeySetUnavailable => true,
///         InvalidTokenKind::Expired | InvalidTokenKind::BadSignature => false,
///         _ => false,
///     }
/// }
///
/// let outage = InvalidToken::new(InvalidTokenKind::KeySetUnavailable, "JWKS refresh failed");
/// assert!(is_idp_trouble(&outage));
/// assert_eq!(outage.kind().as_str(), "key_set_unavailable");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum InvalidTokenKind {
    /// The credential is over the 16 KiB cap; refused before it is decoded.
    TooLarge,
    /// The credential is not three dot-separated segments: a mistyped static
    /// token, or an opaque (non-JWT) access token.
    NotJwt,
    /// The JWS protected header is not a base64url JSON object this crate can
    /// read (including an `alg` it does not know at all, such as `none`).
    MalformedHeader,
    /// The header lists critical extensions (`crit`, RFC 7515 §4.1.11), none of
    /// which this crate supports.
    CriticalHeader,
    /// The header's `alg` is not in the configured allowlist.
    AlgorithmNotAllowed,
    /// The header's `typ` is not an access-token type (or is absent or `JWT`
    /// while `require_at_jwt` is on).
    TypeNotAllowed,
    /// No held key matches the token's `kid` and `alg` while the key set is
    /// healthy: not in it even after a refetch, or unknown while the
    /// unknown-`kid` refetch cooldown runs and the last refresh succeeded.
    KeyNotFound,
    /// The key set could not be loaded: discovery or the JWKS fetch failed,
    /// including during the refetch cooldown when the last refresh failed or
    /// no key is held at all. An authorization-server (or network) outage,
    /// not the caller's fault.
    KeySetUnavailable,
    /// The header checks passed but the rest does not decode: the payload is
    /// not base64url JSON (an object), or the signature is not base64url.
    MalformedToken,
    /// The signature does not verify with the selected key (or the key could
    /// not be used to verify it).
    BadSignature,
    /// `exp` is in the past (beyond the configured leeway).
    Expired,
    /// `nbf` is in the future (beyond the configured leeway), or, with
    /// `max_token_age_secs` set, `iat` is.
    NotYetValid,
    /// `iss` is not exactly the configured issuer (including an `iss` array).
    WrongIssuer,
    /// No `aud` entry is an accepted audience.
    WrongAudience,
    /// A claim the checks need is absent: `exp`, `iss` or `aud`; `iat` with
    /// `max_token_age_secs` set; a `required_claims` entry.
    MissingClaim,
    /// A claim the checks need is present but unreadable: an `exp`, `iss` or
    /// `aud` of the wrong type, an `nbf` (or, with `max_token_age_secs` set,
    /// an `iat`) that is not a NumericDate.
    MalformedClaim,
    /// The token carries `cnf` (a DPoP or mTLS sender constraint), which this
    /// crate cannot verify and so refuses as a bearer token.
    SenderConstrained,
    /// `allowed_client_ids` is set and the token's client (`client_id`, else
    /// `azp`) is absent or not listed.
    ClientNotAllowed,
    /// `max_token_age_secs` is set and the token was issued (`iat`) longer ago
    /// than that, plus the leeway.
    TokenTooOld,
    /// A `required_claims` entry is present in the token with another value
    /// (and, for an array claim, not among its elements).
    ClaimMismatch,
    /// Only static tokens are configured (no OAuth validator) and no
    /// credential is one of them.
    StaticTokenMismatch,
    /// Neither a static token nor an OAuth validator is configured.
    NoMechanism,
    /// A credential was accepted, but the handler needs an OAuth access token
    /// (the axum `AuthorizedToken` extractor) and got a static token.
    OAuthTokenRequired,
    /// A credential was accepted, but the handler needs a static token (the
    /// axum `StaticTokenMatch` extractor) and got an OAuth access token.
    StaticTokenRequired,
    /// Anything else: every [`InvalidToken`] built from a `String` or `&str`,
    /// and a decoder failure this crate cannot classify more precisely.
    Other,
}

impl InvalidTokenKind {
    /// A stable, lowercase `snake_case` label (`"expired"`, `"bad_signature"`,
    /// `"key_set_unavailable"`, ...), for a metrics label or a log field. It
    /// does not change between releases for an existing kind.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::TooLarge => "too_large",
            Self::NotJwt => "not_jwt",
            Self::MalformedHeader => "malformed_header",
            Self::CriticalHeader => "critical_header",
            Self::AlgorithmNotAllowed => "algorithm_not_allowed",
            Self::TypeNotAllowed => "type_not_allowed",
            Self::KeyNotFound => "key_not_found",
            Self::KeySetUnavailable => "key_set_unavailable",
            Self::MalformedToken => "malformed_token",
            Self::BadSignature => "bad_signature",
            Self::Expired => "expired",
            Self::NotYetValid => "not_yet_valid",
            Self::WrongIssuer => "wrong_issuer",
            Self::WrongAudience => "wrong_audience",
            Self::MissingClaim => "missing_claim",
            Self::MalformedClaim => "malformed_claim",
            Self::SenderConstrained => "sender_constrained",
            Self::ClientNotAllowed => "client_not_allowed",
            Self::TokenTooOld => "token_too_old",
            Self::ClaimMismatch => "claim_mismatch",
            Self::StaticTokenMismatch => "static_token_mismatch",
            Self::NoMechanism => "no_mechanism",
            Self::OAuthTokenRequired => "oauth_token_required",
            Self::StaticTokenRequired => "static_token_required",
            Self::Other => "other",
        }
    }
}

impl fmt::Display for InvalidTokenKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// The union of every configured scope claim, in first-seen order, deduplicated.
///
/// Every claim is read in every shape: a string is split on whitespace (RFC 9068
/// §2.2.3's `scope`, and Entra ID's / Hydra's string `scp`), an array contributes
/// each string element whole (Authelia's and Okta's `scp`). Anything else — a
/// number, an object, a claim the token does not have — contributes nothing rather
/// than failing the token, since the only consequence of "no scopes found" is the
/// 403 for a missing required scope, which is the correct answer anyway.
pub(crate) fn extract_scopes(claims: &Map<String, Value>, claim_names: &[String]) -> Vec<String> {
    let mut seen = HashSet::new();
    let mut out = Vec::new();
    let mut push = |s: &str| {
        let s = s.trim();
        if !s.is_empty() && seen.insert(s.to_string()) {
            out.push(s.to_string());
        }
    };
    for name in claim_names {
        match claims.get(name) {
            Some(Value::String(s)) => s.split_whitespace().for_each(&mut push),
            Some(Value::Array(items)) => items.iter().filter_map(Value::as_str).for_each(&mut push),
            _ => {}
        }
    }
    out
}

/// The first present, non-empty string claim among `claim_names`, verbatim.
/// Truncate it (`for_log`) where it is logged, never here.
pub(crate) fn extract_principal(
    claims: &Map<String, Value>,
    claim_names: &[String],
) -> Option<String> {
    claim_names.iter().find_map(|name| match claims.get(name) {
        Some(Value::String(s)) if !s.trim().is_empty() => Some(s.clone()),
        _ => None,
    })
}

/// RFC 9068 §2.1 / §4: the header `typ` of a JWT access token is `at+jwt`
/// (`application/at+jwt` is the same media type, RFC 7515 §4.1.9, compared
/// case-insensitively). Many servers still emit `JWT` or nothing (Authentik, Entra
/// ID, Okta, Keycloak by default), so those pass unless `require_at_jwt` is on —
/// which an operator whose AS does emit `at+jwt` (Authelia, Kanidm) should turn on,
/// since it is the one check that tells an access token from an ID token minted
/// for the same client. Any OTHER explicit type (`dpop+jwt`, `logout+jwt`,
/// `secevent+jwt`...) is a different kind of JWT and is always refused.
///
/// `naming` only shapes the (log-only) rejection reason.
pub(crate) fn check_typ(
    typ: Option<&str>,
    require_at_jwt: bool,
    naming: &KeyNamingBuf,
) -> Result<(), TokenRejection> {
    let Some(raw) = typ else {
        return if require_at_jwt {
            Err(TokenRejection::invalid(
                InvalidTokenKind::TypeNotAllowed,
                format!(
                    "token header has no typ and {} is on",
                    naming.key("require_at_jwt")
                ),
            ))
        } else {
            Ok(())
        };
    };
    let lower = raw.trim().to_ascii_lowercase();
    let media = lower.strip_prefix("application/").unwrap_or(&lower);
    match media {
        "at+jwt" => Ok(()),
        "jwt" if !require_at_jwt => Ok(()),
        _ => Err(TokenRejection::invalid(
            InvalidTokenKind::TypeNotAllowed,
            format!(
                "token typ {:?} is not accepted as an access token{}",
                for_log(raw),
                if require_at_jwt {
                    format!(" ({} is on)", naming.key("require_at_jwt"))
                } else {
                    String::new()
                }
            ),
        )),
    }
}

/// Test helper: `result` is an `Invalid` of `kind` with exactly `detail`.
/// `InvalidToken`'s equality compares the detail only, so a test that means
/// the kind too says so through this.
#[cfg(test)]
#[track_caller]
pub(crate) fn assert_invalid<T: fmt::Debug>(
    result: Result<T, TokenRejection>,
    kind: InvalidTokenKind,
    detail: &str,
    context: &str,
) {
    match result {
        Err(TokenRejection::Invalid(invalid)) => {
            assert_eq!(invalid.kind(), kind, "{context}");
            assert_eq!(invalid.detail(), detail, "{context}");
        }
        other => panic!("expected Invalid({kind:?}), got {other:?} {context}"),
    }
}

/// Truncate a token-derived string for a log line. See [`MAX_LOGGED_CHARS`].
pub(crate) fn for_log(s: &str) -> String {
    let mut out: String = s.chars().take(MAX_LOGGED_CHARS).collect();
    if s.chars().count() > MAX_LOGGED_CHARS {
        out.push('…');
    }
    out
}

/// A token's scopes for a log field, each through [`for_log`]: they come
/// from the (signed) token, but a scope may still be any length up to the
/// credential cap.
pub(crate) fn scopes_for_log(scopes: &[String]) -> Vec<String> {
    scopes.iter().map(|s| for_log(s)).collect()
}

/// A token-derived string for a tracing span field (the unverified header's
/// `kid` and `alg`): [`for_log`]'s truncation, then every character outside
/// printable ASCII escaped as `\u{..}`. A field is written verbatim by some
/// subscribers (a JSON formatter, an OpenTelemetry exporter) rather than
/// through `Debug`, so the escaping is done here: no control character, ANSI
/// escape or bidi override from an attacker's header reaches a terminal or a
/// log store raw. At most `MAX_LOGGED_CHARS` input characters, each at most
/// ten output bytes, plus the ellipsis.
pub(crate) fn for_log_field(s: &str) -> String {
    let bounded = for_log(s);
    let mut out = String::with_capacity(bounded.len());
    for c in bounded.chars() {
        if c.is_ascii_graphic() || c == ' ' || c == '…' {
            out.push(c);
        } else {
            out.extend(c.escape_unicode());
        }
    }
    out
}

/// A `kid` for a log line or rejection reason: quoted and truncated, or `(none)`.
pub(crate) fn describe_kid(kid: Option<&str>) -> String {
    match kid {
        Some(kid) => format!("{:?}", for_log(kid)),
        None => "(none)".to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn new_fills_the_metadata_fields_with_documented_test_defaults() {
        let t = AuthorizedToken::new(Some("sub-1".into()), None, ["a"]);
        assert_eq!(t.issuer, "");
        assert!(t.audiences.is_empty());
        assert_eq!(t.issued_at, None);
        assert_eq!(t.client_id, None);
        assert_eq!(t.jti, None);
        assert!(t.claims().is_empty());
        // 2100-01-01T00:00:00Z: a fixture is never already expired.
        assert_eq!(
            t.expires_at,
            UNIX_EPOCH + Duration::from_secs(4_102_444_800)
        );
        assert!(t.expires_at > SystemTime::now());
    }

    #[test]
    fn builders_set_their_field_and_with_claims_leaves_the_rest_alone() {
        let claims = serde_json::json!({"groups": ["g1"], "n": 1});
        let claims = claims.as_object().unwrap().clone();
        let exp = UNIX_EPOCH + Duration::from_secs(1_000);
        let t = AuthorizedToken::new(Some("sub-1".into()), Some("p".into()), ["a"])
            .with_claims(claims.clone())
            .with_issuer("https://issuer.example.test")
            .with_audiences(["aud-1", "aud-2"])
            .with_expires_at(exp)
            .with_issued_at(UNIX_EPOCH)
            .with_client_id("client-1")
            .with_jti("jti-1");
        assert_eq!(t.claims(), &claims);
        assert_eq!(t.issuer, "https://issuer.example.test");
        assert_eq!(t.audiences, ["aud-1", "aud-2"]);
        assert_eq!(t.expires_at, exp);
        assert_eq!(t.issued_at, Some(UNIX_EPOCH));
        assert_eq!(t.client_id.as_deref(), Some("client-1"));
        assert_eq!(t.jti.as_deref(), Some("jti-1"));
        assert_eq!(t.subject.as_deref(), Some("sub-1"));
        assert_eq!(t.scopes, ["a"]);
        // `with_claims` alone does not derive typed fields from the map.
        let only = AuthorizedToken::new(None, None, Vec::<String>::new()).with_claims(
            serde_json::json!({"iss": "x", "jti": "y"})
                .as_object()
                .unwrap()
                .clone(),
        );
        assert_eq!(only.issuer, "");
        assert_eq!(only.jti, None);
    }

    #[test]
    fn equality_and_clone_cover_the_claims() {
        let a = AuthorizedToken::new(None, None, ["a"])
            .with_claims(serde_json::json!({"k": 1}).as_object().unwrap().clone());
        assert_eq!(a.clone(), a);
        assert_ne!(a, AuthorizedToken::new(None, None, ["a"]));
    }

    #[test]
    fn numeric_date_reads_like_jsonwebtoken_and_saturates_and_never_panics() {
        let secs = |s: u64| Some(UNIX_EPOCH + Duration::from_secs(s));
        let max = secs(MAX_TIMESTAMP_SECS);
        assert_eq!(numeric_date(&serde_json::json!(10)), secs(10));
        // Rounded to the nearest second, half away from zero, as jsonwebtoken does.
        assert_eq!(numeric_date(&serde_json::json!(1.4)), secs(1));
        assert_eq!(numeric_date(&serde_json::json!(1.5)), secs(2));
        assert_eq!(numeric_date(&serde_json::json!(0.4)), secs(0));
        assert_eq!(numeric_date(&serde_json::json!(u64::MAX)), max);
        assert_eq!(numeric_date(&serde_json::json!(i64::MAX as u64 + 1)), max);
        assert_eq!(numeric_date(&serde_json::json!(1e19)), max);
        assert_eq!(numeric_date(&serde_json::json!(-1)), None);
        assert_eq!(numeric_date(&serde_json::json!(-0.4)), None);
        assert_eq!(numeric_date(&serde_json::json!(1e30)), None);
        assert_eq!(numeric_date(&serde_json::json!("10")), None);
    }

    #[test]
    fn require_scopes_is_all_of_and_names_what_is_missing() {
        let t = AuthorizedToken::new(None, None, ["a", "b"]);
        assert_eq!(t.require_scopes(&[]), Ok(()));
        assert_eq!(t.require_scopes(&["a"]), Ok(()));
        assert_eq!(t.require_scopes(&["b", "a"]), Ok(()));
        let missing = t.require_scopes(&["a", "c", "b", "d"]).unwrap_err();
        assert_eq!(missing.required(), ["a", "c", "b", "d"]);
        assert_eq!(missing.missing(), ["c", "d"]);
        assert_eq!(missing.to_string(), "insufficient scope: missing c d");
        assert_eq!(
            TokenRejection::from(missing),
            TokenRejection::InsufficientScope
        );
        // Exact and case-sensitive; an entry no token can carry is missing.
        for never in ["A", "a ", "", "a b"] {
            assert_eq!(
                t.require_scopes(&[never]).unwrap_err().missing(),
                [never],
                "{never:?}"
            );
        }
    }

    #[test]
    fn require_scopes_matches_exactly_what_the_validator_extracts() {
        // Every accepted claim shape, read by the validator's own reader:
        // `require_scopes` on the result agrees with `missing_scopes`, the
        // rule `verify` applies to the same list.
        let claims = serde_json::json!({
            "scope": "a  b\tc",
            "scp": ["d", "e f", 7],
        });
        let names = vec!["scope".to_string(), "scp".to_string()];
        let scopes = extract_scopes(claims.as_object().unwrap(), &names);
        let t = AuthorizedToken::new(None, None, scopes.clone());
        for required in [
            vec!["a", "b", "c", "d"],
            vec!["e f"],
            vec!["e"],
            vec!["7"],
            vec!["a", "x"],
        ] {
            let by_token = t
                .require_scopes(&required)
                .map_err(|m| m.missing().to_vec());
            let by_rule = missing_scopes(&scopes, required.iter().copied());
            assert_eq!(
                by_token.is_ok(),
                by_rule.is_empty(),
                "{required:?}: {by_token:?} vs {by_rule:?}"
            );
        }
        assert!(t.require_scopes(&["a", "b", "c", "d", "e f"]).is_ok());
        assert_eq!(
            t.require_scopes(&["e", "7"]).unwrap_err().missing(),
            ["e", "7"]
        );
    }

    #[test]
    fn authorized_token_new_dedupes_scopes_like_a_validation() {
        let t = AuthorizedToken::new(Some("sub-1".into()), None, ["b", " a", "b", "", "a", "c"]);
        assert_eq!(t.subject.as_deref(), Some("sub-1"));
        assert_eq!(t.principal, None);
        assert_eq!(t.scopes, ["b", "a", "c"]);
        assert!(t.has_scope("a"));
        assert!(!t.has_scope(""));
        let none = AuthorizedToken::new(None, None, Vec::<String>::new());
        assert!(none.scopes.is_empty());
    }

    #[test]
    fn a_rejection_displays_its_category_but_never_the_reason() {
        let secret_reason = "token rejected: InvalidAudience";
        let invalid = TokenRejection::Invalid(secret_reason.into());
        assert_eq!(invalid.to_string(), "invalid token");
        assert!(!invalid.to_string().contains("InvalidAudience"));
        assert!(format!("{invalid:?}").contains(secret_reason));
        assert_eq!(TokenRejection::Missing.to_string(), "missing credential");
        assert_eq!(
            TokenRejection::InsufficientScope.to_string(),
            "insufficient scope"
        );
        let boxed: Box<dyn std::error::Error + Send + Sync> = Box::new(invalid);
        assert_eq!(boxed.to_string(), "invalid token");
    }

    #[test]
    fn logged_values_are_truncated() {
        let long = "x".repeat(MAX_LOGGED_CHARS * 3);
        assert_eq!(for_log(&long).chars().count(), MAX_LOGGED_CHARS + 1);
        assert_eq!(for_log("short"), "short");
    }

    #[test]
    fn span_field_values_are_truncated_and_escaped() {
        assert_eq!(for_log_field("kid-1 A"), "kid-1 A");
        assert_eq!(
            for_log_field("\u{1b}[31mx\u{7}\r\n\u{202e}é"),
            "\\u{1b}[31mx\\u{7}\\u{d}\\u{a}\\u{202e}\\u{e9}"
        );
        let hostile = "\u{1b}".repeat(5 * 1024);
        let shown = for_log_field(&hostile);
        assert_eq!(shown, format!("{}…", "\\u{1b}".repeat(MAX_LOGGED_CHARS)));
        assert!(for_log_field(&"\u{10ffff}".repeat(1000)).len() <= MAX_LOGGED_CHARS * 10 + 3);
    }

    #[test]
    fn typ_rejection_reasons_name_the_setting_per_key_naming() {
        let typ = |detail: &str| {
            Err(TokenRejection::Invalid(InvalidToken::new(
                InvalidTokenKind::TypeNotAllowed,
                detail,
            )))
        };
        let dotted = KeyNamingBuf::Dotted("mcp.oauth".into());
        assert_eq!(
            check_typ(None, true, &dotted),
            typ("token header has no typ and mcp.oauth.require_at_jwt is on")
        );
        assert_eq!(
            check_typ(Some("JWT"), true, &dotted),
            typ("token typ \"JWT\" is not accepted as an access token \
                 (mcp.oauth.require_at_jwt is on)")
        );
        assert_eq!(
            check_typ(Some("dpop+jwt"), false, &dotted),
            typ("token typ \"dpop+jwt\" is not accepted as an access token")
        );
        let env = KeyNamingBuf::Env("APP_OAUTH_".into());
        assert_eq!(
            check_typ(None, true, &env),
            typ("token header has no typ and APP_OAUTH_REQUIRE_AT_JWT is on")
        );
        // Equality is detail-only, so the kind is asserted on its own.
        for (t, require) in [(None, true), (Some("JWT"), true), (Some("dpop+jwt"), false)] {
            let Err(TokenRejection::Invalid(invalid)) = check_typ(t, require, &dotted) else {
                panic!("{t:?} passed");
            };
            assert_eq!(invalid.kind(), InvalidTokenKind::TypeNotAllowed);
        }
    }

    /// The 0.1 uses of `Invalid(String)` that 0.2 keeps compiling, each as a
    /// consumer would write it.
    #[test]
    #[allow(clippy::op_ref, clippy::cmp_owned)]
    fn invalid_token_keeps_the_string_uses_compiling() {
        // Construction from a literal and from an owned `String`: kind `Other`.
        let from_str = TokenRejection::Invalid("bad token".into());
        let from_string = TokenRejection::Invalid(String::from("bad token").into());
        assert_eq!(from_str, from_string);
        let TokenRejection::Invalid(reason) = &from_str else {
            panic!("not Invalid")
        };
        assert_eq!(reason.kind(), InvalidTokenKind::Other);
        assert_eq!(reason.detail(), "bad token");
        // `Display` is the detail, byte for byte; `format!`/`to_string` too.
        assert_eq!(reason.to_string(), "bad token");
        assert_eq!(format!("refused: {reason}"), "refused: bad token");
        // `Deref<Target = str>`: `str` methods and `&str` coercion.
        assert!(reason.contains("bad"));
        assert!(reason.starts_with("bad "));
        assert_eq!(reason.len(), 9);
        let as_str: &str = reason;
        assert_eq!(as_str, "bad token");
        // `PartialEq<str>` and `PartialEq<&str>`, from a reference and a value.
        assert!(reason == "bad token");
        assert!(*reason == "bad token");
        assert!(reason.clone() == "bad token");
        assert!(&**reason == "bad token");
        assert!(reason != "other");
        // `matches!` on the variant, with and without a binding.
        assert!(matches!(from_str, TokenRejection::Invalid(_)));
        assert!(matches!(&from_str, TokenRejection::Invalid(r) if r.contains("bad")));
        // Equality between two `InvalidToken`s compares the detail only, so
        // a 0.1-style comparison with a hand-built reason keeps passing.
        assert_eq!(
            InvalidToken::new(InvalidTokenKind::Expired, "bad token"),
            InvalidToken::from("bad token")
        );
        assert_ne!(
            InvalidToken::new(InvalidTokenKind::Expired, "bad token"),
            InvalidToken::new(InvalidTokenKind::Expired, "other")
        );
        // `as_str`, `String` comparisons both ways, and `str`/`&str` on the left.
        assert_eq!(reason.as_str(), "bad token");
        let owned = String::from("bad token");
        assert!(*reason == owned);
        assert!(owned == *reason);
        assert!("bad token" == *reason);
        assert!("bad token" == reason.clone());
        // Into an owned `String`, and into a boxed error.
        let s: String = reason.clone().into();
        assert_eq!(s, "bad token");
        let boxed: Box<dyn std::error::Error> = reason.clone().into();
        assert_eq!(boxed.to_string(), "bad token");
        // `Debug` still carries the reason, for logs.
        assert!(format!("{from_str:?}").contains("bad token"));
        // `Invalid(format!(..))` alone no longer compiles; `.into()` does.
        let n = 3;
        let formatted = TokenRejection::Invalid(format!("{n} candidates").into());
        assert!(matches!(formatted, TokenRejection::Invalid(r) if r == "3 candidates"));
    }

    #[test]
    fn every_invalid_token_kind_label_is_distinct_snake_case() {
        use InvalidTokenKind as K;
        let all = [
            K::TooLarge,
            K::NotJwt,
            K::MalformedHeader,
            K::CriticalHeader,
            K::AlgorithmNotAllowed,
            K::TypeNotAllowed,
            K::KeyNotFound,
            K::KeySetUnavailable,
            K::MalformedToken,
            K::BadSignature,
            K::Expired,
            K::NotYetValid,
            K::WrongIssuer,
            K::WrongAudience,
            K::MissingClaim,
            K::MalformedClaim,
            K::SenderConstrained,
            K::ClientNotAllowed,
            K::TokenTooOld,
            K::ClaimMismatch,
            K::StaticTokenMismatch,
            K::NoMechanism,
            K::OAuthTokenRequired,
            K::StaticTokenRequired,
            K::Other,
        ];
        let labels: HashSet<&str> = all.iter().map(|k| k.as_str()).collect();
        assert_eq!(labels.len(), all.len());
        for (kind, label) in all.iter().zip(all.iter().map(|k| k.as_str())) {
            assert!(
                label.bytes().all(|b| b.is_ascii_lowercase() || b == b'_'),
                "{label}"
            );
            assert_eq!(kind.to_string(), label);
        }
    }

    #[cfg(feature = "serde")]
    #[test]
    fn invalid_token_serializes_as_its_kind_label_never_the_detail() {
        let reason = InvalidToken::new(
            InvalidTokenKind::ClientNotAllowed,
            "token client \"secret-client\" is not in oauth.allowed_client_ids",
        );
        let body = serde_json::json!({ "reason": reason });
        assert_eq!(body, serde_json::json!({ "reason": "client_not_allowed" }));
        assert!(!body.to_string().contains("secret-client"), "{body}");
        let expired = InvalidToken::new(InvalidTokenKind::Expired, "token rejected: expired");
        assert_eq!(
            serde_json::to_string(&expired).unwrap(),
            "\"expired\"",
            "a derived response type gets the label too"
        );
    }
}