oauth-resource-server 0.1.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
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
//! Configuration: the unvalidated input shape ([`OAuthConfig`]), its validation
//! ([`OAuthConfig::resolve`]), and the validated shape the validator is built from
//! ([`ResolvedOAuthConfig`]).
//!
//! Validation is all-or-nothing: an enabled config either resolves completely or
//! fails with **every** problem at once, each naming the offending setting the way
//! the operator spelled it — a dotted YAML key or an environment variable, chosen
//! by [`KeyNaming`]. A half-usable OAuth config must fail at startup, with the key
//! in the message, rather than as a wall of 401s later.

use std::fmt;

use crate::algorithms::{Algorithm, DEFAULT_ALGORITHMS, parse_algorithm};
use crate::validator::plain_http_non_loopback;

/// Default [`OAuthConfig::scope_claims`]. `scope` is RFC 9068 §2.2.3's
/// space-delimited string (Authentik, Kanidm, Keycloak); `scp` is what Authelia
/// (array), Okta (array), Ory Hydra (array or string) and Entra ID (string) emit
/// instead. Reading both by default is what makes an Authelia token pass without
/// per-provider config, and it cannot widen access for a token that carries only
/// `scope` (every Authentik token) because a claim the token does not have
/// contributes nothing.
pub const DEFAULT_SCOPE_CLAIMS: &[&str] = &["scope", "scp"];

/// Default [`OAuthConfig::principal_claims`]. `email` is left out on purpose so a
/// default deployment does not write addresses into its logs; an operator who
/// wants it adds it.
pub const DEFAULT_PRINCIPAL_CLAIMS: &[&str] = &["preferred_username", "sub"];

/// Default [`OAuthConfig::leeway_secs`]: the clock-skew allowance, in seconds.
pub const DEFAULT_LEEWAY_SECS: u64 = 60;

/// Ceiling on [`OAuthConfig::leeway_secs`]. Leeway is for clock drift; a value
/// large enough to matter against a 5–15 minute token lifetime (Kanidm issues
/// 900 s tokens) is a way of switching `exp` off, which config must not be able
/// to do.
pub const MAX_LEEWAY_SECS: u64 = 300;

/// How problem messages name a setting, so they match how the operator wrote it.
///
/// - `Dotted("mcp.oauth")` names the issuer `mcp.oauth.issuer` — a key in a YAML
///   (or other serde) config nested under that path.
/// - `Env("MYAPP_OAUTH_")` names it `MYAPP_OAUTH_ISSUER` — the field name
///   uppercased and appended to the prefix.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum KeyNaming<'a> {
    /// A dotted path prefix; a field is named `<prefix>.<field>`.
    Dotted(&'a str),
    /// An environment-variable prefix; a field is named `<PREFIX><FIELD>`.
    Env(&'a str),
}

impl KeyNaming<'_> {
    /// The name of setting `field` (a lower-case [`OAuthConfig`] field name).
    pub fn key(&self, field: &str) -> String {
        match self {
            KeyNaming::Dotted("") => field.to_string(),
            KeyNaming::Dotted(prefix) => format!("{prefix}.{field}"),
            KeyNaming::Env(prefix) => format!("{prefix}{}", field.to_ascii_uppercase()),
        }
    }

    /// The name of the whole block: the dotted prefix itself, or `PREFIX*` for
    /// environment variables. An empty dotted prefix (the OAuth fields at the
    /// root of the config) has no path to name, so the block is called
    /// `OAuth config` rather than rendering as an empty string.
    pub fn section(&self) -> String {
        match self {
            KeyNaming::Dotted("") => "OAuth config".to_string(),
            KeyNaming::Dotted(prefix) => prefix.to_string(),
            KeyNaming::Env(prefix) => format!("{prefix}*"),
        }
    }

    /// The owned form, for storing past the borrow.
    pub fn to_buf(&self) -> KeyNamingBuf {
        match self {
            KeyNaming::Dotted(p) => KeyNamingBuf::Dotted((*p).to_string()),
            KeyNaming::Env(p) => KeyNamingBuf::Env((*p).to_string()),
        }
    }
}

/// Owned [`KeyNaming`], carried on [`ResolvedOAuthConfig`] and [`ConfigError`] so
/// that log lines and errors produced after resolution (a token naming an
/// algorithm outside the allowlist, a discovery document for another issuer) name
/// settings the same way the config did.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum KeyNamingBuf {
    /// See [`KeyNaming::Dotted`].
    Dotted(String),
    /// See [`KeyNaming::Env`].
    Env(String),
}

impl KeyNamingBuf {
    /// Borrow as a [`KeyNaming`].
    pub fn as_naming(&self) -> KeyNaming<'_> {
        match self {
            KeyNamingBuf::Dotted(p) => KeyNaming::Dotted(p),
            KeyNamingBuf::Env(p) => KeyNaming::Env(p),
        }
    }

    /// Shorthand for `self.as_naming().key(field)`.
    pub fn key(&self, field: &str) -> String {
        self.as_naming().key(field)
    }

    /// Shorthand for `self.as_naming().section()`.
    pub fn section(&self) -> String {
        self.as_naming().section()
    }
}

/// An enabled config that cannot be used, with every problem found.
///
/// `Display` renders all of them under one header naming the block the way
/// [`KeyNaming`] spells it; for `Dotted("mcp.oauth")` that is
///
/// ```text
/// mcp.oauth.enabled is true but the OAuth config is not usable:
///   - <problem>
///   - <problem>
/// Fix these, or set mcp.oauth.enabled: false.
/// ```
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub struct ConfigError {
    /// One human-readable sentence per problem, each naming its setting.
    pub problems: Vec<String>,
    naming: KeyNamingBuf,
}

impl ConfigError {
    /// An error listing `problems`, whose header names settings per `naming`.
    /// For loaders that add their own problems (parse errors, say) alongside the
    /// ones [`OAuthConfig::resolve`] finds.
    ///
    /// `problems` must not be empty: an error with nothing to fix would display
    /// as a header over one blank bullet. Debug builds assert it.
    pub fn new(naming: KeyNaming<'_>, problems: Vec<String>) -> Self {
        debug_assert!(
            !problems.is_empty(),
            "ConfigError::new called with no problems"
        );
        Self {
            problems,
            naming: naming.to_buf(),
        }
    }

    /// How this error names settings.
    pub fn naming(&self) -> KeyNaming<'_> {
        self.naming.as_naming()
    }
}

impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let list = self.problems.join("\n  - ");
        match &self.naming {
            KeyNamingBuf::Dotted(_) => {
                let enabled = self.naming.key("enabled");
                write!(
                    f,
                    "{enabled} is true but the OAuth config is not usable:\n  - {list}\n\
                     Fix these, or set {enabled}: false."
                )
            }
            KeyNamingBuf::Env(_) => {
                let section = self.naming.section();
                write!(
                    f,
                    "OAuth is configured through {section} but the config is not usable:\n  \
                     - {list}\nFix these, or unset every {section} variable."
                )
            }
        }
    }
}

/// The OAuth resource-server settings, as written by an operator — unvalidated.
///
/// Turns the process into an OAuth 2.0 *resource server* (RFC 9728, RFC 9068,
/// RFC 6750): it verifies JWT access tokens minted by a separate authorization
/// server and never issues, refreshes or introspects anything itself. Call
/// [`OAuthConfig::resolve`] to validate it into a [`ResolvedOAuthConfig`].
///
/// Provider-agnostic by construction: every provider-specific difference
/// (audience value, scope claim name and shape, signing algorithm, `typ`,
/// username claim) is a field below rather than a code path.
///
/// Every field is optional in serde input (feature `serde`); unknown keys are
/// refused. Nothing here hot-reloads: a changed value takes effect only when a
/// new validator is built from it, which in practice means a restart.
///
/// Deliberately not `#[non_exhaustive]`, so applications can write
/// `OAuthConfig { enabled: true, ..OAuthConfig::default() }` — a
/// functional-record update that keeps compiling even after a field is
/// added. What breaks instead is an exhaustive struct literal or
/// destructuring pattern that names every field, which is possible only
/// because every field here is public and the struct carries no
/// `#[non_exhaustive]`; adding a field is still a breaking change under
/// `0.x` (a new minor release, which Cargo treats as incompatible), just not
/// for the functional-record-update form above.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct OAuthConfig {
    /// Master switch. False (the default) means [`OAuthConfig::resolve`] returns
    /// `Ok(None)`: no JWT validation happens at all and nothing else here is
    /// checked.
    #[cfg_attr(feature = "serde", serde(default))]
    pub enabled: bool,
    /// The authorization server's issuer identifier, compared BYTE-EXACTLY
    /// against each token's `iss` claim and echoed verbatim in the
    /// protected-resource metadata's `authorization_servers`. Copy it from the
    /// AS's own discovery document including any trailing slash — Authentik's
    /// issuer ends in one, and a token minted with `.../app/` will not match
    /// `.../app`. Required; an absolute URL with no query or fragment, and no
    /// space, control or non-ASCII character.
    ///
    /// `https`, as RFC 8414 §2 requires of an issuer: the signing keys are
    /// found through it, and keys fetched over cleartext can be substituted by
    /// anyone on the path. Plain `http` is accepted only for a loopback host,
    /// or with [`OAuthConfig::allow_insecure_http`].
    #[cfg_attr(feature = "serde", serde(default))]
    pub issuer: String,
    /// Where to fetch the signing keys (JWKS). Optional: absent or blank, it is
    /// discovered from the issuer's own metadata (OpenID Connect Discovery, then
    /// RFC 8414), and the discovered document's `issuer` must equal `issuer`
    /// byte-for-byte or it is refused. Setting it explicitly skips discovery.
    /// Fetched at startup and hourly in the background, and on an unknown `kid`
    /// at most once a minute. The same URL rules as `issuer` apply, except
    /// that a query is allowed; RFC 8414 §2 requires `https` for it too.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub jwks_uri: Option<String>,
    /// A value each token's `aud` claim must contain (string or array, RFC 7519
    /// §4.1.3). Unioned with `audiences`; at least one of the two must be set,
    /// and there is deliberately no default, because the right value depends on
    /// the authorization server and a wrong guess either rejects everything or
    /// accepts tokens meant for another service:
    ///
    /// - servers that honour RFC 8707 or let you configure an access-token
    ///   audience (Authelia with a client `audience`) put the RESOURCE URL there
    ///   — use the same value as `resource`;
    /// - servers that ignore RFC 8707 and stamp the OAuth CLIENT ID (Authentik,
    ///   Kanidm) need the client_id here.
    ///
    /// A client_id audience departs from RFC 9068 §4 (the `aud` must identify
    /// this resource server) and from MCP's requirement that a server accept
    /// only tokens issued for it as audience (RFC 8707 §2): every token that
    /// client obtains from the authorization server, for any resource, carries
    /// the same `aud`. It is sound only when that OAuth client is dedicated to
    /// this one resource server and shared with no other API. Prefer a
    /// resource-URL audience wherever the authorization server supports one.
    #[cfg_attr(feature = "serde", serde(default))]
    pub audience: String,
    /// Additional accepted audiences. A token passes the audience check if its
    /// `aud` contains ANY configured value. Useful while migrating from a
    /// client_id audience to a resource-URL audience.
    #[cfg_attr(feature = "serde", serde(default))]
    pub audiences: Vec<String>,
    /// This resource server's canonical identifier, published as `resource` in
    /// the protected-resource metadata and used to derive the metadata URL
    /// advertised in `WWW-Authenticate` (RFC 9728 §3). The public URL of the
    /// protected endpoint, e.g. `https://api.example.com/v1`; required, with
    /// the same URL rules as `issuer`.
    ///
    /// `https`, as RFC 9728 §1.2 requires of a resource identifier: it is the
    /// URL clients send their bearer tokens to (RFC 6750 §5.3). Plain `http` is
    /// accepted only for a loopback host, or with
    /// [`OAuthConfig::allow_insecure_http`].
    ///
    /// Not implicitly compared against `aud` — list it in `audience`/`audiences`
    /// when the authorization server stamps it there.
    #[cfg_attr(feature = "serde", serde(default))]
    pub resource: String,
    /// A scope every token must carry. A valid token missing it gets 403
    /// `insufficient_scope`, not 401. A single RFC 6749 §3.3 scope-token —
    /// printable ASCII with no space, `"` or `\` — matched exactly and
    /// case-sensitively. Unioned with `required_scopes`.
    ///
    /// No default. With neither this nor `required_scopes` set, no scope is
    /// checked, and [`OAuthConfig::resolve`] then insists on
    /// `require_at_jwt` or [`OAuthConfig::allow_unscoped_tokens`]. An
    /// explicitly empty value is an error rather than "no scope", so a typo
    /// cannot silently drop the check.
    ///
    /// The check is an exact all-of match with no scope hierarchy: a token
    /// holding only `api:write` does not satisfy `api:read`, whatever the
    /// authorization server means by it. Require a scope every accepted token
    /// carries, and make finer, hierarchy-aware decisions in the application
    /// with [`crate::AuthorizedToken::has_scope`].
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub required_scope: Option<String>,
    /// Further scopes every token must carry — ALL of them, together with
    /// `required_scope`. Each entry follows the same rules as `required_scope`.
    /// Empty (the default) adds nothing.
    #[cfg_attr(feature = "serde", serde(default))]
    pub required_scopes: Vec<String>,
    /// Advertised in the metadata document's `scopes_supported` and the 401
    /// challenge's `scope` so a client knows what to ask for. Purely declarative —
    /// enforcement is `required_scope`/`required_scopes`. Each entry is a
    /// scope-token, as for `required_scope`.
    ///
    /// `None` (the default, and what an omitted key deserializes to) resolves to
    /// the required scopes (`required_scope`, then `required_scopes`), so a
    /// client that asks for exactly what is advertised gets a token that
    /// passes. `Some(vec![])` resolves to an empty list: the metadata document
    /// then omits `scopes_supported` (RFC 9728 §3.2), and the 401 challenge
    /// names the required scopes instead. The two are kept distinct so an
    /// application can supply its own default for an omitted key without
    /// overriding an operator's explicit empty list — e.g.
    /// `cfg.scopes_supported.get_or_insert_with(|| vec!["api:read".into()])`
    /// before [`OAuthConfig::resolve`].
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub scopes_supported: Option<Vec<String>>,
    /// Which claims hold the token's scopes. Every listed claim is read in every
    /// shape — a space-delimited string or an array of strings — and the results
    /// are unioned. The default ([`DEFAULT_SCOPE_CLAIMS`]) reads RFC 9068's
    /// `scope` AND the `scp` that Authelia, Okta, Ory Hydra and Entra ID use
    /// instead; reading a claim a token does not carry changes nothing.
    #[cfg_attr(feature = "serde", serde(default = "default_scope_claims"))]
    pub scope_claims: Vec<String>,
    /// Claims tried in order to name the caller in logs — the first present,
    /// non-empty string wins. Several servers put no username in access tokens
    /// (Authelia, Kanidm: only a UUID `sub`), hence a chain ending in `sub`.
    /// `email` is not in the default ([`DEFAULT_PRINCIPAL_CLAIMS`]) so addresses
    /// do not land in logs unasked. Used for logging only, never for an
    /// authorization decision.
    #[cfg_attr(feature = "serde", serde(default = "default_principal_claims"))]
    pub principal_claims: Vec<String>,
    /// JWS algorithms a token may be signed with. Each key in the JWKS is
    /// additionally limited to the algorithms its own type (and its `alg`, when
    /// it declares one) can produce. `HS256`/`HS384`/`HS512` and `none` are
    /// refused at resolve time: a resource server must never verify with a shared
    /// secret. The default ([`DEFAULT_ALGORITHMS`]) is every asymmetric algorithm
    /// this build can verify.
    #[cfg_attr(feature = "serde", serde(default = "default_algorithms"))]
    pub algorithms: Vec<String>,
    /// Clock-skew allowance, in seconds, applied to `exp` and `nbf`. Default
    /// [`DEFAULT_LEEWAY_SECS`]; capped at [`MAX_LEEWAY_SECS`], since a leeway
    /// comparable to a token's lifetime is a way of disabling expiry.
    #[cfg_attr(feature = "serde", serde(default = "default_leeway_secs"))]
    pub leeway_secs: u64,
    /// Require the JWT header `typ` to be `at+jwt` (RFC 9068 §2.1). Off by
    /// default because Authentik, Keycloak, Entra ID and Okta emit `JWT` or no
    /// `typ`. Turn it ON for servers that do emit `at+jwt` (Authelia, Kanidm): it
    /// is the check that stops an ID token minted for the same client from being
    /// replayed as an access token. With it off, `at+jwt`, `JWT` and no `typ` pass
    /// and any other type (`dpop+jwt`, `logout+jwt`...) is still refused.
    ///
    /// Off is a deliberate, configurable departure from RFC 9068 §4, under
    /// which a resource server MUST reject any `typ` other than `at+jwt` or
    /// `application/at+jwt`; RFC 8725 §3.11 recommends the same explicit
    /// typing. With it off, a required scope is what keeps ID tokens out.
    #[cfg_attr(feature = "serde", serde(default))]
    pub require_at_jwt: bool,
    /// Accept a configuration with no required scope and `require_at_jwt`
    /// off. Default false: [`OAuthConfig::resolve`] refuses that combination,
    /// because nothing in it tells an access token from an OIDC ID token
    /// minted for the same client (RFC 8725 §3.11–3.12), and on servers that
    /// stamp the client_id as `aud` (Authentik, Kanidm) the ID token a front
    /// end got at login would then be a working API credential. Set it only
    /// when "signed by this issuer for this audience" really is all the
    /// application needs; the validator still logs a `warn` at startup.
    #[cfg_attr(feature = "serde", serde(default))]
    pub allow_unscoped_tokens: bool,
    /// Accept a plain-`http` `issuer`, `jwks_uri` or `resource` on a
    /// non-loopback host. Default false: [`OAuthConfig::resolve`] refuses one,
    /// because signing keys fetched over cleartext can be substituted by anyone
    /// on the path (RFC 8414 §2 requires `https` for the issuer and its
    /// `jwks_uri`), and bearer tokens sent to a cleartext resource can be read
    /// in transit (RFC 9728 §1.2, RFC 6750 §5.3). Loopback hosts (`127.0.0.0/8`,
    /// `::1`, `localhost`) are always allowed, for tests and local development.
    ///
    /// The same rule holds at run time for URLs the configuration does not
    /// name: a `jwks_uri` discovered from a (plain-`http`) issuer's metadata,
    /// and every redirect a metadata or JWKS fetch follows, may reach plain
    /// `http` on a non-loopback host only with this set. An `https` issuer
    /// never hands out an `http` `jwks_uri`, and a redirect from `https` to
    /// `http` is never followed, whatever this says.
    ///
    /// Set it for an in-cluster address on a private network (an
    /// `http://idp:9000/...` `jwks_uri`, say) where the path itself is trusted;
    /// the validator still logs a `warn` for each such URL at startup, and for
    /// each such discovered URL or redirect when it is used.
    #[cfg_attr(feature = "serde", serde(default))]
    pub allow_insecure_http: bool,
    /// Whether a static token (an API key the application configures
    /// separately) is still accepted while OAuth is on. Default true: both
    /// credentials work side by side. Set false to run OAuth-only even if a
    /// static token is configured (it is then ignored). Read by
    /// [`crate::static_token_policy`]; the validator itself never looks at it.
    #[cfg_attr(feature = "serde", serde(default = "default_true"))]
    pub accept_static_bearer: bool,
}

impl Default for OAuthConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            issuer: String::new(),
            jwks_uri: None,
            audience: String::new(),
            audiences: Vec::new(),
            resource: String::new(),
            required_scope: None,
            required_scopes: Vec::new(),
            scopes_supported: None,
            scope_claims: default_scope_claims(),
            principal_claims: default_principal_claims(),
            algorithms: default_algorithms(),
            leeway_secs: default_leeway_secs(),
            require_at_jwt: false,
            allow_unscoped_tokens: false,
            allow_insecure_http: false,
            accept_static_bearer: true,
        }
    }
}

fn strings(list: &[&str]) -> Vec<String> {
    list.iter().map(|s| s.to_string()).collect()
}

fn default_scope_claims() -> Vec<String> {
    strings(DEFAULT_SCOPE_CLAIMS)
}

fn default_principal_claims() -> Vec<String> {
    strings(DEFAULT_PRINCIPAL_CLAIMS)
}

fn default_algorithms() -> Vec<String> {
    strings(DEFAULT_ALGORITHMS)
}

fn default_leeway_secs() -> u64 {
    DEFAULT_LEEWAY_SECS
}

#[cfg(feature = "serde")]
fn default_true() -> bool {
    true
}

impl OAuthConfig {
    /// Validate and resolve: `Ok(None)` when disabled, `Ok(Some(..))` when
    /// enabled and usable, `Err` naming every problem it can find at once when
    /// enabled and not. `naming` decides how the problems (and, later, the
    /// validator's log lines) name each setting.
    ///
    /// Does no I/O: whether the issuer is reachable and publishes usable keys
    /// is found out later, by the validator.
    ///
    /// # Errors
    ///
    /// A [`ConfigError`] listing every problem in an enabled config: a blank
    /// `issuer` or `resource`, no audience in either `audience` or `audiences`,
    /// a URL (`issuer`, `resource` or `jwks_uri`) that is not absolute
    /// `http`/`https`, has surrounding whitespace or contains a space, control
    /// or non-ASCII character (or, for `issuer` and `resource`, that has a
    /// query or a fragment), a plain-`http` URL on a non-loopback host without
    /// [`OAuthConfig::allow_insecure_http`], a blank or multi-word required
    /// scope, a required or supported scope that is not an RFC 6749 §3.3
    /// scope-token, no required scope with neither `require_at_jwt` nor
    /// [`OAuthConfig::allow_unscoped_tokens`] set, an empty `scope_claims`, a
    /// blank entry in a list, an algorithm that is HMAC, `none` or unknown, an
    /// empty algorithm list, or a `leeway_secs` over [`MAX_LEEWAY_SECS`].
    ///
    /// # Examples
    ///
    /// ```
    /// use oauth_resource_server::{KeyNaming, OAuthConfig};
    ///
    /// let config = OAuthConfig {
    ///     enabled: true,
    ///     issuer: "https://auth.example.com/".into(),
    ///     audience: "example-api".into(),
    ///     resource: "https://api.example.com".into(),
    ///     required_scope: Some("api:read".into()),
    ///     scopes_supported: Some(vec!["api:read".into()]),
    ///     ..OAuthConfig::default()
    /// };
    /// let resolved = config.resolve(KeyNaming::Dotted("oauth")).unwrap().unwrap();
    /// assert_eq!(resolved.required_scopes, ["api:read"]);
    /// assert_eq!(resolved.jwks_uri, None); // discovered from the issuer later
    ///
    /// // Disabled: nothing is checked.
    /// assert_eq!(OAuthConfig::default().resolve(KeyNaming::Dotted("oauth")), Ok(None));
    ///
    /// // Broken: every problem at once, each named the way the operator wrote it.
    /// let err = OAuthConfig {
    ///     enabled: true,
    ///     required_scope: Some("api:read".into()),
    ///     leeway_secs: 3600,
    ///     ..OAuthConfig::default()
    /// }
    /// .resolve(KeyNaming::Env("MYAPP_OAUTH_"))
    /// .unwrap_err();
    /// assert_eq!(err.problems.len(), 2);
    /// assert!(err.problems[0].contains("MYAPP_OAUTH_ISSUER"));
    /// assert!(err.problems[1].contains("MYAPP_OAUTH_LEEWAY_SECS"));
    /// ```
    pub fn resolve(
        self,
        naming: KeyNaming<'_>,
    ) -> Result<Option<ResolvedOAuthConfig>, ConfigError> {
        if !self.enabled {
            return Ok(None);
        }
        let key = |field: &str| naming.key(field);
        let mut problems: Vec<String> = Vec::new();

        let mut blank = Vec::new();
        for (name, value) in [("issuer", &self.issuer), ("resource", &self.resource)] {
            if value.trim().is_empty() {
                blank.push(key(name));
            }
        }
        if self.audience.trim().is_empty() && self.audiences.is_empty() {
            blank.push(format!("{} (or {})", key("audience"), key("audiences")));
        }
        if !blank.is_empty() {
            problems.push(format!(
                "these required settings are empty: {}. Set issuer to the authorization \
                 server's issuer (byte-exact, including any trailing slash), resource to \
                 this server's public URL, and audience to what that server puts in \
                 an access token's `aud` — the resource URL if it honours RFC 8707 or \
                 lets you configure an audience (e.g. Authelia), or the OAuth client_id \
                 if it stamps that (e.g. Authentik, Kanidm)",
                blank.join(", ")
            ));
        }

        let urls = [
            ("issuer", Some(&self.issuer), true),
            ("resource", Some(&self.resource), true),
            ("jwks_uri", self.jwks_uri.as_ref(), false),
        ];
        for (name, value, identifier) in urls {
            let Some(value) = value.filter(|v| !v.trim().is_empty()) else {
                continue;
            };
            match check_url(&key(name), value, identifier) {
                Err(e) => problems.push(e),
                Ok(()) if !self.allow_insecure_http && plain_http_non_loopback(value) => {
                    problems.push(format!(
                        "{} {value:?} uses plain http on a non-loopback host — {}. Use https, \
                         or set {} if this address is on a network you trust",
                        key(name),
                        if name == "resource" {
                            "bearer tokens sent to it can be read in transit (RFC 9728 §1.2 \
                             requires https)"
                        } else {
                            "signing keys fetched over it can be substituted by anyone on the \
                             path (RFC 8414 §2 requires https)"
                        },
                        key("allow_insecure_http")
                    ));
                }
                Ok(()) => {}
            }
        }
        if self.audiences.iter().any(|a| a.trim().is_empty()) {
            problems.push(format!("{} contains an empty entry", key("audiences")));
        }

        if let Some(required_scope) = &self.required_scope {
            if required_scope.trim().is_empty() {
                problems.push(format!(
                    "{} must not be empty — a blank required scope would let any signed \
                     token through unscoped. Use a scope your authorization server \
                     actually issues",
                    key("required_scope")
                ));
            } else if required_scope.split_whitespace().count() != 1 {
                problems.push(format!(
                    "{} {:?} must be a single scope (no spaces) — scopes are matched one \
                     token at a time",
                    key("required_scope"),
                    required_scope
                ));
            } else if !is_scope_token(required_scope.trim()) {
                problems.push(scope_token_problem(&key("required_scope"), required_scope));
            }
        }
        for scope in &self.required_scopes {
            if scope.trim().is_empty() {
                problems.push(format!(
                    "{} contains an empty entry — a blank required scope would let a \
                     token through without it. Remove the entry or name a scope your \
                     authorization server actually issues",
                    key("required_scopes")
                ));
            } else if scope.split_whitespace().count() != 1 {
                problems.push(format!(
                    "{} entry {:?} must be a single scope (no spaces) — scopes are matched \
                     one token at a time; list each one as its own entry",
                    key("required_scopes"),
                    scope
                ));
            } else if !is_scope_token(scope.trim()) {
                problems.push(scope_token_problem(
                    &format!("{} entry", key("required_scopes")),
                    scope,
                ));
            }
        }
        if let Some(supported) = &self.scopes_supported {
            if supported.iter().any(|s| s.trim().is_empty()) {
                problems.push(format!(
                    "{} contains an empty entry",
                    key("scopes_supported")
                ));
            }
            for scope in supported.iter().filter(|s| !s.trim().is_empty()) {
                if !is_scope_token(scope.trim()) {
                    problems.push(scope_token_problem(
                        &format!("{} entry", key("scopes_supported")),
                        scope,
                    ));
                }
            }
        }
        if self.required_scope.is_none()
            && self.required_scopes.is_empty()
            && !self.require_at_jwt
            && !self.allow_unscoped_tokens
        {
            problems.push(format!(
                "no required scope is configured ({} and {} are unset) and {} is off — \
                 nothing would tell an access token from an OIDC ID token minted for the \
                 same client, so any token this issuer signs for the audience would be \
                 accepted. Set {} to a scope only access tokens carry, turn on {} if the \
                 authorization server emits typ at+jwt, or set {} to accept that",
                key("required_scope"),
                key("required_scopes"),
                key("require_at_jwt"),
                key("required_scope"),
                key("require_at_jwt"),
                key("allow_unscoped_tokens")
            ));
        }
        if self.scope_claims.is_empty() || self.scope_claims.iter().any(|c| c.trim().is_empty()) {
            problems.push(format!(
                "{} must list at least one non-empty claim name (default: [\"scope\", \
                 \"scp\"])",
                key("scope_claims")
            ));
        }
        if self.principal_claims.iter().any(|c| c.trim().is_empty()) {
            problems.push(format!(
                "{} contains an empty entry",
                key("principal_claims")
            ));
        }

        let mut algorithms = Vec::new();
        let mut bad_algorithms = Vec::new();
        for name in &self.algorithms {
            match parse_algorithm(name) {
                Ok(alg) if !algorithms.contains(&alg) => algorithms.push(alg),
                Ok(_) => {}
                Err(reason) => bad_algorithms.push(reason.to_string()),
            }
        }
        if !bad_algorithms.is_empty() {
            problems.push(format!(
                "{} has unacceptable entries: {}",
                key("algorithms"),
                bad_algorithms.join("; ")
            ));
        } else if algorithms.is_empty() {
            problems.push(format!(
                "{} must list at least one algorithm",
                key("algorithms")
            ));
        }

        if self.leeway_secs > MAX_LEEWAY_SECS {
            problems.push(format!(
                "{} {} is over the {}-second cap — leeway is for clock drift, not for \
                 extending token lifetimes",
                key("leeway_secs"),
                self.leeway_secs,
                MAX_LEEWAY_SECS
            ));
        }

        if !problems.is_empty() {
            return Err(ConfigError::new(naming, problems));
        }

        // `required_scope` first, then `required_scopes` in order, trimmed and
        // deduplicated — a stable order keeps the 403 challenge's `scope` value
        // the same from one start to the next.
        let mut required_scopes: Vec<String> = Vec::new();
        for scope in self
            .required_scope
            .iter()
            .chain(self.required_scopes.iter())
        {
            let scope = scope.trim();
            if !required_scopes.iter().any(|s| s == scope) {
                required_scopes.push(scope.to_string());
            }
        }

        // An omitted `scopes_supported` advertises what is required, so a client
        // that asks for exactly the advertised scopes gets a token that passes.
        let scopes_supported = match self.scopes_supported {
            Some(listed) => listed.iter().map(|s| s.trim().to_string()).collect(),
            None => required_scopes.clone(),
        };

        Ok(Some(ResolvedOAuthConfig {
            issuer: self.issuer,
            jwks_uri: self.jwks_uri.filter(|u| !u.trim().is_empty()),
            audience: self.audience,
            audiences: self.audiences,
            resource: self.resource,
            required_scopes,
            scopes_supported,
            scope_claims: self.scope_claims,
            principal_claims: self.principal_claims,
            algorithms,
            leeway_secs: self.leeway_secs,
            require_at_jwt: self.require_at_jwt,
            allow_unscoped_tokens: self.allow_unscoped_tokens,
            allow_insecure_http: self.allow_insecure_http,
            accept_static_bearer: self.accept_static_bearer,
            resource_name: None,
            key_naming: naming.to_buf(),
        }))
    }
}

/// Check that a URL setting is an absolute http(s) URL, and (for the two
/// identifiers, `issuer` and `resource`) that it carries no fragment or query:
/// RFC 8414 §2 forbids both in an issuer, RFC 8707 §2 a fragment in a resource,
/// and either one in an identifier that is compared byte-for-byte is a typo
/// waiting to reject every token.
///
/// It also refuses a space, a control character or a non-ASCII character
/// anywhere in the value. The URL parser would silently drop an embedded tab or
/// newline and percent-encode the rest, but the RAW string is what is stored,
/// compared and echoed into every `WWW-Authenticate` challenge — where such a
/// character makes the header invalid, and the 401 would go out without one.
fn check_url(key: &str, value: &str, identifier: bool) -> Result<(), String> {
    let parsed = reqwest::Url::parse(value.trim())
        .map_err(|e| format!("{key} {value:?} is not an absolute URL ({e})"))?;
    if !matches!(parsed.scheme(), "https" | "http") {
        return Err(format!("{key} {value:?} must be an http(s) URL"));
    }
    if identifier && (parsed.fragment().is_some() || parsed.query().is_some()) {
        return Err(format!(
            "{key} {value:?} must not contain a query or fragment"
        ));
    }
    if value != value.trim() {
        return Err(format!(
            "{key} {value:?} has leading/trailing whitespace — it is compared byte-for-byte"
        ));
    }
    if value.chars().any(|c| !c.is_ascii_graphic()) {
        return Err(format!(
            "{key} {value:?} contains a space, a control character or a non-ASCII \
             character — write it percent-encoded (and an internationalized host in its \
             punycode form)"
        ));
    }
    Ok(())
}

/// RFC 6749 §3.3 `scope-token = 1*( %x21 / %x23-5B / %x5D-7E )`: printable
/// ASCII other than space, `"` and `\`. RFC 6750 §3 holds the `scope` attribute
/// of a challenge to the same set, and RFC 9728 §2 `scopes_supported` to the
/// same values.
fn is_scope_token(scope: &str) -> bool {
    !scope.is_empty()
        && scope
            .bytes()
            .all(|b| b == 0x21 || (0x23..=0x5B).contains(&b) || (0x5D..=0x7E).contains(&b))
}

fn scope_token_problem(what: &str, scope: &str) -> String {
    format!(
        "{what} {scope:?} is not a valid scope — a scope is printable ASCII with no space, \
         '\"' or '\\' (RFC 6749 §3.3)"
    )
}

/// The validated config an [`crate::OAuthValidator`] is built from.
///
/// Only [`OAuthConfig::resolve`] produces one with every invariant checked, so
/// holding a `ResolvedOAuthConfig` (rather than an `Option` of one) IS the answer
/// to "is OAuth on and usable" — nothing downstream re-checks a boolean. Fields
/// are public so tests and applications can adjust a resolved value (the
/// validator re-checks the invariants whose violation it could not survive: a
/// non-empty audience set, a non-empty algorithm list, and `leeway_secs` within
/// [`MAX_LEEWAY_SECS`]).
///
/// `#[non_exhaustive]`: outside this crate one comes from
/// [`OAuthConfig::resolve`] (or, in tests, `testing::resolved_config`) and is
/// then adjusted field by field, never built with a struct literal — which is
/// what lets a new resolved setting be added without a breaking change.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ResolvedOAuthConfig {
    /// See [`OAuthConfig::issuer`]; byte-exact.
    pub issuer: String,
    /// `None` means "discover from the issuer's metadata". Never blank.
    pub jwks_uri: Option<String>,
    /// The single audience; may be empty when `audiences` is not. Use
    /// [`ResolvedOAuthConfig::accepted_audiences`] for the effective set.
    pub audience: String,
    /// See [`OAuthConfig::audiences`].
    pub audiences: Vec<String>,
    /// See [`OAuthConfig::resource`].
    pub resource: String,
    /// `required_scope` ∪ `required_scopes`: trimmed, deduplicated, in config
    /// order (`required_scope` first). A token must carry every one; empty means
    /// no scope check at all.
    pub required_scopes: Vec<String>,
    /// See [`OAuthConfig::scopes_supported`]; `None` there resolves to
    /// `required_scopes`. Advertised in the metadata document (omitted from it
    /// when empty) and in the 401 challenge.
    pub scopes_supported: Vec<String>,
    /// See [`OAuthConfig::scope_claims`].
    pub scope_claims: Vec<String>,
    /// See [`OAuthConfig::principal_claims`].
    pub principal_claims: Vec<String>,
    /// Parsed and deduplicated. [`Algorithm`] has no HMAC or `none` variant,
    /// so this can never hold one.
    pub algorithms: Vec<Algorithm>,
    /// See [`OAuthConfig::leeway_secs`].
    pub leeway_secs: u64,
    /// See [`OAuthConfig::require_at_jwt`].
    pub require_at_jwt: bool,
    /// See [`OAuthConfig::allow_unscoped_tokens`]. Informational once
    /// resolved: `resolve` has already applied it.
    pub allow_unscoped_tokens: bool,
    /// See [`OAuthConfig::allow_insecure_http`]. `resolve` has already applied
    /// it to the configured URLs; the validator still reads it, for a
    /// discovered `jwks_uri` and for redirects followed while fetching keys.
    pub allow_insecure_http: bool,
    /// See [`OAuthConfig::accept_static_bearer`].
    pub accept_static_bearer: bool,
    /// Human-readable name published as `resource_name` in the RFC 9728
    /// metadata document; omitted from it when `None`. Not a config key:
    /// [`OAuthConfig::resolve`] leaves it `None`, and an application that wants
    /// one sets it on the resolved value (it names the application, which the
    /// operator has no reason to change).
    pub resource_name: Option<String>,
    /// How the validator's log lines and errors name settings; what `resolve`
    /// was given.
    pub key_naming: KeyNamingBuf,
}

impl ResolvedOAuthConfig {
    /// `audience` ∪ `audiences`, blanks dropped, in config order.
    pub fn accepted_audiences(&self) -> Vec<String> {
        let mut out: Vec<String> = Vec::new();
        for a in std::iter::once(&self.audience).chain(self.audiences.iter()) {
            if !a.trim().is_empty() && !out.contains(a) {
                out.push(a.clone());
            }
        }
        out
    }
}

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

    const WIKI: KeyNaming<'static> = KeyNaming::Dotted("mcp.oauth");

    /// An enabled block with every required key set, for the rejection tests to
    /// break one key at a time. It opts into an unscoped configuration, so a
    /// test that sets no scope is not also refused for that; the unscoped
    /// refusal has tests of its own.
    fn enabled(edit: impl FnOnce(&mut OAuthConfig)) -> OAuthConfig {
        let mut cfg = OAuthConfig {
            enabled: true,
            issuer: "https://idp.example.test/".into(),
            resource: "https://kb.example.test/mcp".into(),
            audience: "c".into(),
            allow_unscoped_tokens: true,
            ..OAuthConfig::default()
        };
        edit(&mut cfg);
        cfg
    }

    fn resolve_err(cfg: OAuthConfig) -> String {
        cfg.resolve(WIKI).unwrap_err().to_string()
    }

    // ── defaults ─────────────────────────────────────────────────────────────

    #[test]
    fn oauth_is_disabled_by_default_and_has_no_default_scope() {
        let cfg = OAuthConfig::default();
        assert!(!cfg.enabled);
        // The crate is not MCP-specific: no required scope and no advertised
        // scopes unless the application or operator names them.
        assert_eq!(cfg.required_scope, None);
        assert!(cfg.required_scopes.is_empty());
        assert_eq!(cfg.scopes_supported, None);
        assert_eq!(cfg.jwks_uri, None);
        assert_eq!(cfg.scope_claims, ["scope", "scp"]);
        assert_eq!(cfg.principal_claims, ["preferred_username", "sub"]);
        assert_eq!(cfg.algorithms, DEFAULT_ALGORITHMS);
        assert_eq!(cfg.leeway_secs, 60);
        assert!(!cfg.require_at_jwt);
        assert!(!cfg.allow_unscoped_tokens);
        assert!(!cfg.allow_insecure_http);
        assert!(cfg.accept_static_bearer);
    }

    #[test]
    fn disabled_resolves_to_none() {
        assert_eq!(OAuthConfig::default().resolve(WIKI), Ok(None));
        // Even a broken disabled block: nothing is checked.
        let cfg = OAuthConfig {
            algorithms: vec!["HS256".into()],
            ..OAuthConfig::default()
        };
        assert_eq!(cfg.resolve(WIKI), Ok(None));
    }

    #[test]
    fn a_minimal_enabled_block_resolves_with_every_default() {
        let cfg = OAuthConfig {
            enabled: true,
            issuer: "https://authentik.example.test/application/o/example-app/".into(),
            jwks_uri: Some("https://authentik.example.test/application/o/example-app/jwks/".into()),
            audience: "some-client-id".into(),
            resource: "https://kb.example.test/mcp".into(),
            required_scope: Some("api:read".into()),
            ..OAuthConfig::default()
        };
        let oauth = cfg.resolve(WIKI).unwrap().expect("enabled");
        // The trailing slash must survive verbatim: it is compared byte-exactly
        // against the `iss` claim, and Authentik's issuer has one.
        assert_eq!(
            oauth.issuer,
            "https://authentik.example.test/application/o/example-app/"
        );
        assert_eq!(oauth.audience, "some-client-id");
        assert_eq!(oauth.resource, "https://kb.example.test/mcp");
        assert_eq!(oauth.required_scopes, ["api:read"]);
        // An omitted `scopes_supported` advertises the required scopes.
        assert_eq!(oauth.scopes_supported, ["api:read"]);
        assert_eq!(oauth.accepted_audiences(), ["some-client-id"]);
        assert_eq!(oauth.scope_claims, ["scope", "scp"]);
        assert_eq!(oauth.principal_claims, ["preferred_username", "sub"]);
        assert!(oauth.algorithms.contains(&Algorithm::RS256));
        assert_eq!(oauth.leeway_secs, 60);
        assert!(!oauth.require_at_jwt);
        assert!(!oauth.allow_unscoped_tokens);
        assert!(!oauth.allow_insecure_http);
        assert!(oauth.accept_static_bearer);
        assert_eq!(oauth.resource_name, None);
        assert_eq!(oauth.key_naming, KeyNamingBuf::Dotted("mcp.oauth".into()));
    }

    // ── rejection: every problem at once, each naming its key ────────────────

    #[test]
    fn enabled_with_blank_required_settings_is_rejected_naming_all_of_them() {
        let cfg = OAuthConfig {
            enabled: true,
            ..OAuthConfig::default()
        };
        let err = resolve_err(cfg);
        for setting in [
            "mcp.oauth.issuer",
            "mcp.oauth.audience",
            "mcp.oauth.resource",
        ] {
            assert!(err.contains(setting), "{setting} missing from: {err}");
        }
        // Optional: an absent jwks_uri means "discover it".
        assert!(!err.contains("mcp.oauth.jwks_uri"), "{err}");
    }

    /// The two phrases where mcp-md-wiki's messages are MCP-specific and this
    /// crate's are not. mcp-md-wiki#308: mcp-md-wiki keeps its historical text
    /// byte-identical by rewriting exactly these in `ConfigError::problems`
    /// before display.
    ///
    /// An early warning, not a contract. Message text is not a stable API (see
    /// the README's semver policy), and what actually guarantees mcp-md-wiki's
    /// text is its own test pinning its full output, which fails there on the
    /// dependency bump if this wording changes. This pin only makes the
    /// breakage visible here first: when a test below fails, change the text
    /// deliberately and tell mcp-md-wiki, rather than treating the phrase as
    /// frozen.
    const WIKI_REWRITES: [(&str, &str); 2] = [
        ("this server's public URL,", "this server's public MCP URL,"),
        (
            "unscoped. Use a scope your",
            "unscoped. Use \"mcp:read\" (the default) or a scope your",
        ),
    ];

    fn as_wiki_text(problem: &str) -> String {
        WIKI_REWRITES
            .iter()
            .fold(problem.to_string(), |p, (generic, wiki)| {
                p.replace(generic, wiki)
            })
    }

    #[test]
    fn config_error_display_for_dotted_naming_is_generic_and_maps_to_mcp_md_wiki_text() {
        // A required scope, as mcp-md-wiki always supplies one before resolving,
        // so the unscoped refusal does not join the one problem pinned here.
        let cfg = OAuthConfig {
            enabled: true,
            required_scope: Some("mcp:read".into()),
            ..OAuthConfig::default()
        };
        // Spelled out in full, not rebuilt from the format strings under test.
        let expected = "mcp.oauth.enabled is true but the OAuth config is not usable:\n  - \
these required settings are empty: mcp.oauth.issuer, mcp.oauth.resource, mcp.oauth.audience \
(or mcp.oauth.audiences). Set issuer to the authorization server's issuer (byte-exact, \
including any trailing slash), resource to this server's public URL, and audience to \
what that server puts in an access token's `aud` — the resource URL if it honours RFC 8707 \
or lets you configure an audience (e.g. Authelia), or the OAuth client_id if it stamps that \
(e.g. Authentik, Kanidm)\nFix these, or set mcp.oauth.enabled: false.";
        let mut err = cfg.resolve(WIKI).unwrap_err();
        assert_eq!(err.to_string(), expected);
        assert_eq!(err.problems[0].matches(WIKI_REWRITES[0].0).count(), 1);

        // The text mcp-md-wiki printed before mcp-md-wiki#308, recovered by its
        // rewrite of the generic phrase.
        let wiki_expected = "mcp.oauth.enabled is true but the OAuth config is not usable:\n  - \
these required settings are empty: mcp.oauth.issuer, mcp.oauth.resource, mcp.oauth.audience \
(or mcp.oauth.audiences). Set issuer to the authorization server's issuer (byte-exact, \
including any trailing slash), resource to this server's public MCP URL, and audience to \
what that server puts in an access token's `aud` — the resource URL if it honours RFC 8707 \
or lets you configure an audience (e.g. Authelia), or the OAuth client_id if it stamps that \
(e.g. Authentik, Kanidm)\nFix these, or set mcp.oauth.enabled: false.";
        err.problems = err.problems.iter().map(|p| as_wiki_text(p)).collect();
        assert_eq!(err.to_string(), wiki_expected);
    }

    #[test]
    fn scope_problem_messages_are_generic_and_map_to_mcp_md_wiki_text() {
        let err = enabled(|c| c.required_scope = Some(String::new()))
            .resolve(WIKI)
            .unwrap_err();
        assert_eq!(
            err.problems,
            [
                "mcp.oauth.required_scope must not be empty — a blank required scope would \
              let any signed token through unscoped. Use a scope your authorization server \
              actually issues"
            ]
        );
        assert_eq!(err.problems[0].matches(WIKI_REWRITES[1].0).count(), 1);
        // mcp-md-wiki#308: mcp-md-wiki's pre-extraction text, recovered.
        assert_eq!(
            as_wiki_text(&err.problems[0]),
            "mcp.oauth.required_scope must not be empty — a blank required scope would \
              let any signed token through unscoped. Use \"mcp:read\" (the default) or a \
              scope your authorization server actually issues"
        );
        // Nothing MCP-specific leaks into a non-MCP consumer's messages.
        let text = OAuthConfig {
            enabled: true,
            required_scope: Some(String::new()),
            ..OAuthConfig::default()
        }
        .resolve(KeyNaming::Env("APP_OAUTH_"))
        .unwrap_err()
        .to_string();
        assert!(!text.contains("MCP") && !text.contains("mcp"), "{text}");
        let err = enabled(|c| c.required_scope = Some("mcp:read mcp:write".into()))
            .resolve(WIKI)
            .unwrap_err();
        assert_eq!(
            err.problems,
            [
                "mcp.oauth.required_scope \"mcp:read mcp:write\" must be a single scope (no \
              spaces) — scopes are matched one token at a time"
            ]
        );
        let err = enabled(|c| c.leeway_secs = 3600).resolve(WIKI).unwrap_err();
        assert_eq!(
            err.to_string(),
            "mcp.oauth.enabled is true but the OAuth config is not usable:\n  - \
             mcp.oauth.leeway_secs 3600 is over the 300-second cap — leeway is for clock \
             drift, not for extending token lifetimes\nFix these, or set mcp.oauth.enabled: \
             false."
        );
    }

    #[test]
    fn env_naming_uppercases_and_appends_the_field() {
        let naming = KeyNaming::Env("MYAPP_OAUTH_");
        assert_eq!(naming.key("issuer"), "MYAPP_OAUTH_ISSUER");
        assert_eq!(naming.key("required_scopes"), "MYAPP_OAUTH_REQUIRED_SCOPES");
        assert_eq!(naming.section(), "MYAPP_OAUTH_*");
        assert_eq!(
            KeyNaming::Dotted("mcp.oauth").key("issuer"),
            "mcp.oauth.issuer"
        );
        assert_eq!(KeyNaming::Dotted("").key("issuer"), "issuer");
        assert_eq!(KeyNaming::Dotted("").section(), "OAuth config");
        assert_eq!(KeyNaming::Dotted("mcp.oauth").section(), "mcp.oauth");

        let cfg = OAuthConfig {
            enabled: true,
            required_scope: Some(String::new()),
            ..OAuthConfig::default()
        };
        let err = cfg.resolve(naming).unwrap_err();
        let text = err.to_string();
        for key in [
            "MYAPP_OAUTH_ISSUER",
            "MYAPP_OAUTH_RESOURCE",
            "MYAPP_OAUTH_AUDIENCE (or MYAPP_OAUTH_AUDIENCES)",
            "MYAPP_OAUTH_REQUIRED_SCOPE must not be empty",
        ] {
            assert!(text.contains(key), "{key} missing from: {text}");
        }
        assert!(!text.contains("mcp.oauth"), "{text}");
        assert!(
            text.starts_with(
                "OAuth is configured through MYAPP_OAUTH_* but the config is not \
                 usable:\n  - "
            ),
            "{text}"
        );
        assert!(
            text.ends_with("\nFix these, or unset every MYAPP_OAUTH_* variable."),
            "{text}"
        );
        assert_eq!(err.naming(), naming);
    }

    #[test]
    fn accepts_audiences_without_audience_and_an_omitted_or_blank_jwks_uri() {
        for jwks_uri in [None, Some(String::new()), Some("  ".to_string())] {
            let oauth = enabled(|c| {
                c.audience = String::new();
                c.audiences = vec!["https://kb.example.test/mcp".into()];
                c.jwks_uri = jwks_uri.clone();
            })
            .resolve(WIKI)
            .unwrap()
            .unwrap();
            assert_eq!(oauth.accepted_audiences(), ["https://kb.example.test/mcp"]);
            assert_eq!(oauth.jwks_uri, None, "blank means discover: {jwks_uri:?}");
        }
    }

    #[test]
    fn refuses_hmac_and_none_algorithms() {
        for alg in ["HS256", "none"] {
            let err = resolve_err(enabled(|c| {
                c.algorithms = vec!["RS256".into(), alg.into()];
            }));
            assert!(err.contains("mcp.oauth.algorithms"), "{err}");
            assert!(err.contains(alg), "{err}");
        }
        let err = resolve_err(enabled(|c| c.algorithms = vec![]));
        assert!(err.contains("at least one algorithm"), "{err}");
    }

    #[test]
    fn refuses_malformed_urls_naming_the_key() {
        for jwks_uri in ["idp.example.test/jwks", "ftp://idp.example.test/jwks"] {
            let err = resolve_err(enabled(|c| c.jwks_uri = Some(jwks_uri.into())));
            assert!(err.contains("mcp.oauth.jwks_uri"), "{err}");
        }
        let err = resolve_err(enabled(|c| {
            c.issuer = "https://idp.example.test/?x=1".into();
            c.resource = "kb.example.test/mcp".into();
        }));
        assert!(err.contains("mcp.oauth.issuer"), "{err}");
        assert!(err.contains("mcp.oauth.resource"), "{err}");
        let err = resolve_err(enabled(|c| c.issuer = " https://idp.example.test/".into()));
        assert!(err.contains("leading/trailing whitespace"), "{err}");
    }

    #[test]
    fn refuses_bad_scope_and_leeway_settings() {
        type Edit = fn(&mut OAuthConfig);
        let cases: [(Edit, &str); 5] = [
            (
                |c| c.required_scope = Some("mcp:read mcp:write".into()),
                "single scope",
            ),
            (|c| c.scope_claims = vec![], "mcp.oauth.scope_claims"),
            (
                |c| c.principal_claims = vec![String::new()],
                "mcp.oauth.principal_claims",
            ),
            (|c| c.leeway_secs = 3600, "mcp.oauth.leeway_secs"),
            (|c| c.audiences = vec![String::new()], "mcp.oauth.audiences"),
        ];
        for (edit, needle) in cases {
            let err = resolve_err(enabled(edit));
            assert!(err.contains(needle), "{needle} not in: {err}");
        }
    }

    #[test]
    fn a_blank_required_scope_is_rejected_not_treated_as_absent() {
        for blank in ["", "   "] {
            let err = resolve_err(enabled(|c| c.required_scope = Some(blank.into())));
            assert!(
                err.contains("mcp.oauth.required_scope"),
                "an empty required scope must not silently mean 'no scope': {err}"
            );
        }
    }

    #[test]
    fn every_problem_is_reported_at_once() {
        let err = enabled(|c| {
            c.issuer = String::new();
            c.required_scope = Some(String::new());
            c.required_scopes = vec!["a b".into()];
            c.leeway_secs = 9999;
            c.algorithms = vec!["HS256".into()];
        })
        .resolve(WIKI)
        .unwrap_err();
        assert_eq!(err.problems.len(), 5, "{err}");
    }

    // ── required_scopes ──────────────────────────────────────────────────────

    #[test]
    fn required_scopes_are_a_trimmed_deduplicated_order_stable_union() {
        let oauth = enabled(|c| {
            c.required_scope = Some(" a ".into());
            c.required_scopes = vec!["b".into(), "a".into(), " c".into(), "b".into()];
        })
        .resolve(WIKI)
        .unwrap()
        .unwrap();
        assert_eq!(oauth.required_scopes, ["a", "b", "c"]);

        let only_list = enabled(|c| c.required_scopes = vec!["x".into(), "y".into()])
            .resolve(WIKI)
            .unwrap()
            .unwrap();
        assert_eq!(only_list.required_scopes, ["x", "y"]);

        let only_single = enabled(|c| c.required_scope = Some("mcp:read".into()))
            .resolve(WIKI)
            .unwrap()
            .unwrap();
        assert_eq!(only_single.required_scopes, ["mcp:read"]);
    }

    #[test]
    fn an_empty_required_scope_union_is_valid_and_means_no_scope_check() {
        let oauth = enabled(|_| {}).resolve(WIKI).unwrap().unwrap();
        assert!(oauth.required_scopes.is_empty());
    }

    #[test]
    fn required_scopes_entries_follow_the_single_scope_rules() {
        let err = enabled(|c| c.required_scopes = vec!["ok".into(), "  ".into()])
            .resolve(WIKI)
            .unwrap_err();
        assert_eq!(err.problems.len(), 1, "{err}");
        assert!(
            err.problems[0].starts_with("mcp.oauth.required_scopes contains an empty entry"),
            "{err}"
        );
        let err = enabled(|c| c.required_scopes = vec!["a b".into()])
            .resolve(WIKI)
            .unwrap_err();
        assert!(
            err.problems[0]
                .starts_with("mcp.oauth.required_scopes entry \"a b\" must be a single scope"),
            "{err}"
        );
    }

    // ── serde ────────────────────────────────────────────────────────────────

    #[cfg(feature = "serde")]
    #[test]
    fn round_trips_from_yaml_with_every_default() {
        let yaml = "enabled: true
issuer: \"https://authentik.example.test/application/o/example-app/\"
jwks_uri: \"https://authentik.example.test/application/o/example-app/jwks/\"
audience: \"some-client-id\"
resource: \"https://kb.example.test/mcp\"
";
        let parsed: OAuthConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(
            parsed,
            OAuthConfig {
                enabled: true,
                issuer: "https://authentik.example.test/application/o/example-app/".into(),
                jwks_uri: Some(
                    "https://authentik.example.test/application/o/example-app/jwks/".into()
                ),
                audience: "some-client-id".into(),
                resource: "https://kb.example.test/mcp".into(),
                ..OAuthConfig::default()
            }
        );
        let back: OAuthConfig =
            serde_yaml_ng::from_str(&serde_yaml_ng::to_string(&parsed).unwrap()).unwrap();
        assert_eq!(back, parsed);
        // An empty document is the default config.
        let empty: OAuthConfig = serde_yaml_ng::from_str("{}").unwrap();
        assert_eq!(empty, OAuthConfig::default());
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_reads_both_scope_keys_and_refuses_unknown_keys() {
        let parsed: OAuthConfig =
            serde_yaml_ng::from_str("required_scope: \"a\"\nrequired_scopes: [\"b\", \"c\"]\n")
                .unwrap();
        assert_eq!(parsed.required_scope.as_deref(), Some("a"));
        assert_eq!(parsed.required_scopes, ["b", "c"]);
        // An explicit empty string is Some(""), which resolve refuses.
        let parsed: OAuthConfig = serde_yaml_ng::from_str("required_scope: \"\"\n").unwrap();
        assert_eq!(parsed.required_scope.as_deref(), Some(""));
        assert!(serde_yaml_ng::from_str::<OAuthConfig>("bogus: true\n").is_err());
        assert!(serde_yaml_ng::from_str::<OAuthConfig>("resource_name: \"x\"\n").is_err());
        let parsed: OAuthConfig =
            serde_yaml_ng::from_str("allow_unscoped_tokens: true\nallow_insecure_http: true\n")
                .unwrap();
        assert!(parsed.allow_unscoped_tokens && parsed.allow_insecure_http);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_distinguishes_an_omitted_scopes_supported_from_an_explicit_empty_list() {
        let omitted: OAuthConfig = serde_yaml_ng::from_str("enabled: true\n").unwrap();
        assert_eq!(omitted.scopes_supported, None);
        let empty: OAuthConfig = serde_yaml_ng::from_str("scopes_supported: []\n").unwrap();
        assert_eq!(empty.scopes_supported, Some(vec![]));
        let listed: OAuthConfig =
            serde_yaml_ng::from_str("scopes_supported: [\"a\", \"b\"]\n").unwrap();
        assert_eq!(listed.scopes_supported, Some(vec!["a".into(), "b".into()]));
        // Both survive a round trip: `None` is skipped on output (so it reads back
        // as omitted), and an explicit `[]` is written out.
        for cfg in [omitted, empty, listed] {
            let yaml = serde_yaml_ng::to_string(&cfg).unwrap();
            let back: OAuthConfig = serde_yaml_ng::from_str(&yaml).unwrap();
            assert_eq!(back, cfg, "{yaml}");
        }
    }

    #[test]
    fn an_omitted_scopes_supported_advertises_the_required_scopes_and_an_explicit_list_wins() {
        let with_required = |required: Option<&str>, scopes: Option<Vec<String>>| {
            enabled(|c| {
                c.required_scope = required.map(str::to_string);
                c.required_scopes = vec!["b".into(), "a".into()];
                c.scopes_supported = scopes;
            })
            .resolve(WIKI)
            .unwrap()
            .expect("enabled")
            .scopes_supported
        };
        // Omitted: the required scopes, in their resolved order.
        assert_eq!(with_required(Some("a"), None), ["a", "b"]);
        assert_eq!(with_required(None, None), ["b", "a"]);
        // An explicit list, even an empty one, is kept as written (trimmed).
        assert!(with_required(Some("a"), Some(vec![])).is_empty());
        assert_eq!(with_required(Some("a"), Some(vec![" c ".into()])), ["c"]);

        // Nothing required: an omitted list advertises nothing.
        let resolve = |scopes: Option<Vec<String>>| {
            enabled(|c| c.scopes_supported = scopes)
                .resolve(WIKI)
                .unwrap()
                .expect("enabled")
                .scopes_supported
        };
        assert!(resolve(None).is_empty());
        assert!(resolve(Some(vec![])).is_empty());
        assert_eq!(
            resolve(Some(vec!["mcp:read".into(), "mcp:write".into()])),
            ["mcp:read", "mcp:write"]
        );
        // The application-default pattern: fill an omitted key, leave an explicit
        // empty list alone.
        let app_default = |mut c: OAuthConfig| {
            c.scopes_supported
                .get_or_insert_with(|| vec!["mcp:read".into(), "mcp:write".into()]);
            c.resolve(WIKI).unwrap().expect("enabled").scopes_supported
        };
        assert_eq!(
            app_default(enabled(|c| c.scopes_supported = None)),
            ["mcp:read", "mcp:write"]
        );
        assert!(app_default(enabled(|c| c.scopes_supported = Some(vec![]))).is_empty());
    }

    // ── scope-token syntax (RFC 6749 §3.3) ───────────────────────────────────

    #[test]
    fn every_required_and_advertised_scope_must_be_a_scope_token() {
        for bad in ["a\"b", "a\\b", "caf\u{e9}", "a\u{7f}"] {
            let err = enabled(|c| c.required_scope = Some(bad.into()))
                .resolve(WIKI)
                .unwrap_err();
            assert_eq!(err.problems.len(), 1, "{err}");
            assert!(
                err.problems[0].starts_with("mcp.oauth.required_scope ")
                    && err.problems[0].contains("is not a valid scope"),
                "{err}"
            );
            let err = enabled(|c| c.required_scopes = vec!["ok".into(), bad.into()])
                .resolve(WIKI)
                .unwrap_err();
            assert!(
                err.problems[0].starts_with("mcp.oauth.required_scopes entry "),
                "{err}"
            );
            let err = enabled(|c| c.scopes_supported = Some(vec![bad.into()]))
                .resolve(WIKI)
                .unwrap_err();
            assert!(
                err.problems[0].starts_with("mcp.oauth.scopes_supported entry "),
                "{err}"
            );
        }
        // Blank and multi-word advertised entries are refused too.
        let err = enabled(|c| c.scopes_supported = Some(vec!["".into(), "two words".into()]))
            .resolve(WIKI)
            .unwrap_err();
        assert_eq!(err.problems.len(), 2, "{err}");
        assert_eq!(
            err.problems[0],
            "mcp.oauth.scopes_supported contains an empty entry"
        );
        assert!(err.problems[1].contains("\"two words\""), "{err}");
        // Every visible-ASCII scope-token character is fine, including the
        // `:`, `/`, `.` and `!` real scopes use.
        let oauth = enabled(|c| {
            c.required_scope =
                Some("https://api.example.test/things.read!#$%&'()*+,-./:;<=>?@[]^_`{|}~".into());
        })
        .resolve(WIKI)
        .unwrap()
        .unwrap();
        assert_eq!(oauth.required_scopes.len(), 1);
    }

    // ── URL characters, and plain http ───────────────────────────────────────

    #[test]
    fn a_url_with_a_space_control_or_non_ascii_character_is_refused() {
        // `url` would silently drop the tab/newline and percent-encode the rest,
        // but the raw string is what reaches every challenge header.
        for bad in [
            "https://kb.example.test/m\ncp",
            "https://kb.example.test/m\tcp",
            "https://kb.example.test/m cp",
            "https://kb.example.test/caf\u{e9}",
        ] {
            let err = resolve_err(enabled(|c| c.resource = bad.into()));
            assert!(
                err.contains("mcp.oauth.resource") && err.contains("percent-encoded"),
                "{bad:?}: {err}"
            );
            let err = resolve_err(enabled(|c| c.issuer = bad.into()));
            assert!(err.contains("mcp.oauth.issuer"), "{bad:?}: {err}");
            let err = resolve_err(enabled(|c| c.jwks_uri = Some(bad.into())));
            assert!(err.contains("mcp.oauth.jwks_uri"), "{bad:?}: {err}");
        }
        // Percent-encoded is fine, and so is a query on the jwks_uri.
        enabled(|c| {
            c.resource = "https://kb.example.test/caf%C3%A9".into();
            c.jwks_uri = Some("https://idp.example.test/keys?tenant=a".into());
        })
        .resolve(WIKI)
        .unwrap()
        .unwrap();
    }

    #[test]
    fn plain_http_off_loopback_is_refused_unless_explicitly_allowed() {
        let err = enabled(|c| {
            c.issuer = "http://idp.internal.test/app/".into();
            c.jwks_uri = Some("http://idp.internal.test/app/jwks/".into());
            c.resource = "http://kb.internal.test/mcp".into();
        })
        .resolve(WIKI)
        .unwrap_err();
        assert_eq!(err.problems.len(), 3, "{err}");
        assert!(
            err.problems[0].starts_with(
                "mcp.oauth.issuer \"http://idp.internal.test/app/\" uses plain http on a \
                 non-loopback host — signing keys"
            ),
            "{err}"
        );
        assert!(err.problems[0].contains("RFC 8414 §2"), "{err}");
        assert!(err.problems[1].starts_with("mcp.oauth.resource "), "{err}");
        assert!(err.problems[1].contains("RFC 9728 §1.2"), "{err}");
        assert!(err.problems[2].starts_with("mcp.oauth.jwks_uri "), "{err}");
        assert!(
            err.problems[2].contains("set mcp.oauth.allow_insecure_http"),
            "{err}"
        );

        // The explicit opt-in accepts all three.
        let oauth = enabled(|c| {
            c.issuer = "http://idp.internal.test/app/".into();
            c.jwks_uri = Some("http://idp.internal.test/app/jwks/".into());
            c.resource = "http://kb.internal.test/mcp".into();
            c.allow_insecure_http = true;
        })
        .resolve(WIKI)
        .unwrap()
        .unwrap();
        assert!(oauth.allow_insecure_http);

        // Loopback never needs it.
        enabled(|c| {
            c.issuer = "http://127.0.0.1:9000/app/".into();
            c.jwks_uri = Some("http://[::1]:9000/jwks".into());
            c.resource = "http://localhost:8001/mcp".into();
        })
        .resolve(WIKI)
        .unwrap()
        .unwrap();
    }

    // ── the unscoped posture ─────────────────────────────────────────────────

    #[test]
    fn no_required_scope_and_no_typ_check_is_refused_unless_explicitly_allowed() {
        let bare = |edit: fn(&mut OAuthConfig)| {
            let mut cfg = enabled(|c| c.allow_unscoped_tokens = false);
            edit(&mut cfg);
            cfg.resolve(WIKI)
        };
        let err = bare(|_| {}).unwrap_err();
        assert_eq!(err.problems.len(), 1, "{err}");
        assert_eq!(
            err.problems[0],
            "no required scope is configured (mcp.oauth.required_scope and \
             mcp.oauth.required_scopes are unset) and mcp.oauth.require_at_jwt is off — \
             nothing would tell an access token from an OIDC ID token minted for the same \
             client, so any token this issuer signs for the audience would be accepted. Set \
             mcp.oauth.required_scope to a scope only access tokens carry, turn on \
             mcp.oauth.require_at_jwt if the authorization server emits typ at+jwt, or set \
             mcp.oauth.allow_unscoped_tokens to accept that"
        );
        // Any one of the three is enough.
        assert!(bare(|c| c.required_scope = Some("a".into())).is_ok());
        assert!(bare(|c| c.required_scopes = vec!["a".into()]).is_ok());
        assert!(bare(|c| c.require_at_jwt = true).is_ok());
        let allowed = bare(|c| c.allow_unscoped_tokens = true).unwrap().unwrap();
        assert!(allowed.required_scopes.is_empty());
        assert!(allowed.allow_unscoped_tokens);
        // A blank scope is its own problem, not "unscoped" as well.
        let err = bare(|c| c.required_scope = Some(String::new())).unwrap_err();
        assert_eq!(err.problems.len(), 1, "{err}");
        // Named per the key naming.
        let err = OAuthConfig {
            enabled: true,
            ..OAuthConfig::default()
        }
        .resolve(KeyNaming::Env("APP_OAUTH_"))
        .unwrap_err();
        assert!(
            err.problems
                .iter()
                .any(|p| p.contains("set APP_OAUTH_ALLOW_UNSCOPED_TOKENS")),
            "{err}"
        );
    }
}