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
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
//! axum integration: the authentication layer ([`AuthLayer`], a
//! `tower::Layer`, also usable as state for the [`require_auth`] middleware
//! function) and the RFC 9728 metadata routes ([`metadata_router`]).
//!
//! ```no_run
//! use std::sync::Arc;
//!
//! use axum::{Router, routing::get};
//! use oauth_resource_server::axum::{AuthLayer, metadata_router};
//! use oauth_resource_server::{OAuthValidator, ResolvedOAuthConfig, static_token_policy};
//!
//! # fn app(config: &ResolvedOAuthConfig, static_token: Option<String>) -> Router {
//! let oauth = Arc::new(OAuthValidator::new(config).expect("validator"));
//! oauth.spawn_background_refresh();
//!
//! // `accept_static_bearer` only takes effect through `static_token_policy`, the
//! // one thing that reads the setting. Handing `static_token` straight to the
//! // builder instead would make `accept_static_bearer: false` silently do nothing.
//! let decision = static_token_policy(static_token, Some(config), false)
//!     .expect("oauth is configured here, so a credential always exists");
//! let auth = AuthLayer::from_decision(decision, Some(Arc::clone(&oauth)))
//!     .expect("the decision was made with OAuth on, and a validator is given");
//!
//! Router::new()
//!     .route("/api", get(|| async { "protected" }))
//!     .route_layer(auth)
//!     // Outside the auth layer: discovery must work for a caller that has no
//!     // credential yet.
//!     .merge(metadata_router(Some(oauth)))
//! # }
//! ```
//!
//! `.route_layer(auth)` and
//! `.route_layer(axum::middleware::from_fn_with_state(auth, require_auth))`
//! behave identically; the second form is for composing with other `from_fn`
//! middleware.
//!
//! # Refusals
//!
//! 401 for a missing or invalid credential, 403 for a valid token without the
//! required scopes, each with a `WWW-Authenticate` challenge: the validator's
//! when OAuth is configured, otherwise [`DEFAULT_STATIC_CHALLENGE`] (see
//! [`AuthLayerBuilder::static_challenge`]). The status and the challenge are
//! the ones [`crate::refusal()`] gives — the same decision, made by the same
//! code — so an integration outside axum built on it, and the `tower`
//! feature's [`HttpAuthLayer`](crate::http_layer::HttpAuthLayer), refuse exactly
//! as this layer does. There is no 400 `invalid_request`
//! (RFC 6750 §3.1's SHOULD for a malformed request): a request is authenticated
//! or it is not, and anything unreadable is simply no credential.
//!
//! # Extractors
//!
//! [`AuthorizedToken`], [`Credential`] and [`StaticTokenMatch`] are axum
//! extractors (`FromRequestParts`), and so are their `Option<T>` forms
//! (`OptionalFromRequestParts`). They read what the layer inserted, and refuse
//! fail-closed when it is not there:
//!
//! | The request… | `T` | `Option<T>` |
//! |---|---|---|
//! | carries the value (the layer accepted it) | the value | `Some(value)` |
//! | passed an [`optional`](AuthLayerBuilder::optional) layer with no credential, or an [`allow_unauthenticated`](AuthLayer::allow_unauthenticated) layer | the layer's own 401 and challenge | `None` |
//! | was accepted with the static token (`T` = [`AuthorizedToken`] only, and no outer layer inserted one — see [nested layers](self#nested-layers)) | the layer's own 401 and challenge | `None` |
//! | was accepted with an OAuth token (`T` = [`StaticTokenMatch`] only) | the layer's own 401 and challenge | `None` |
//! | never went through an [`AuthLayer`] (a route mounted outside it) | 500, logged at `error` | 500, logged at `error` |
//!
//! "The layer's own 401" is built by the same code that builds the layer's
//! refusals ([`AuthLayerBuilder::on_reject`] included), so its status and
//! `WWW-Authenticate` challenge are exactly the ones the layer would have sent
//! for a request with no credential. An [`allow_unauthenticated`](AuthLayer::allow_unauthenticated)
//! layer has no challenge of its own and answers with
//! [`DEFAULT_STATIC_CHALLENGE`].
//!
//! A route outside every layer is a wiring mistake in the server, not something
//! the caller can fix by authenticating, so it gets 500 (empty body) rather than
//! a 401 that would send an OAuth client into an authorization flow that can
//! never succeed there. It never grants access, and it never reads as "anonymous":
//! `Option<T>` fails the same way.
//!
//! ```
//! use axum::{Router, routing::get};
//! use oauth_resource_server::axum::AuthLayer;
//! use oauth_resource_server::{AuthorizedToken, Credential};
//!
//! async fn whoami(credential: Credential) -> String {
//!     match credential {
//!         Credential::OAuth(token) => format!("subject {:?}", token.subject),
//!         Credential::StaticToken => "the static API key".to_string(),
//!         // `Credential` is `#[non_exhaustive]`.
//!         _ => "some other credential".to_string(),
//!     }
//! }
//!
//! // Needs an OAuth token: a static-token request is refused with the
//! // layer's 401.
//! async fn subject(token: AuthorizedToken) -> String {
//!     token.subject.unwrap_or_default()
//! }
//!
//! let auth = AuthLayer::builder().static_token("example-static-key").build().unwrap();
//! let app: Router = Router::new()
//!     .route("/whoami", get(whoami))
//!     .route("/subject", get(subject))
//!     .route_layer(auth);
//! # let _ = app;
//! ```
//!
//! # Per-route and per-handler scopes
//!
//! On top of the validator's required scopes, with the same validator and so
//! the same key cache: [`AuthLayerBuilder::require_scopes`] for everything
//! behind a layer, the [`RequireScopes`] route layer (behind an
//! [`AuthLayer`]) for some routes, and the [`Scoped`] extractor for one
//! handler. Each refuses a token without its scopes with 403 through the
//! layer's own refusal path — its status, `on_reject` body, and a
//! `WWW-Authenticate` challenge naming the layer's scopes followed by the
//! route's ([`crate::refusal_for_scopes`] sends the same bytes). A static
//! token has no scopes and is refused the same way unless the layer or
//! [`RequireScopes`] opted in with `static_token_bypasses_scopes`.
//!
//! # Optional authentication
//!
//! [`AuthLayerBuilder::optional`] builds a layer for routes that serve everyone
//! but personalize for (or unlock more to) an authenticated caller: a valid
//! credential is inserted as usual, a request that presents NO credential
//! passes through with nothing inserted, and a credential that is presented
//! but refused — invalid, expired, or valid without the required scopes — is
//! refused exactly as by a non-optional layer. See that method for what counts
//! as "no credential". A `DPoP`-scheme `Authorization` value (a
//! sender-constrained token this crate cannot accept) and a `Bearer` value
//! separated from its token by a tab are counted as presented, and refused
//! exactly as a non-optional layer refuses them, never passed through.
//!
//! # Nested layers
//!
//! An optional layer first removes any [`Credential`], [`AuthorizedToken`] and
//! [`StaticTokenMatch`] an outer layer inserted, so what its handlers extract
//! is only ever what IT accepted: `None` after its pass-through, even when an
//! outer layer accepted a token.
//!
//! Strict (non-optional) layers never remove anything; the extensions
//! accumulate, as they always have. [`Credential`] reflects the innermost
//! layer that accepted the request, while an [`AuthorizedToken`] may have been
//! inserted by an OUTER layer: behind an outer OAuth layer, an inner
//! static-only layer that accepts its static token leaves the outer layer's
//! [`AuthorizedToken`] in place, and an `AuthorizedToken` extractor returns it.
//! When that matters, read [`Credential`] (the innermost decision) instead.
//! [`StaticTokenMatch`] always pairs with [`Credential`]: every layer that
//! accepts a static token inserts one, and every layer that accepts an OAuth
//! token removes any an outer layer inserted.
//!
//! # Logging
//!
//! The layer logs every outcome itself, so applications need not (target
//! `oauth_resource_server::axum`): an accepted OAuth token at `debug` (principal,
//! subject, scopes — never the token); an accepted static token at `debug`
//! (its label, never the token); a request with no credential at `debug`
//! when OAuth is configured, since every OAuth client's first request looks like
//! that; a request with no credential passed through by an
//! [`optional`](AuthLayerBuilder::optional) layer at `debug`; any other refusal
//! at `warn`, with the reason when OAuth is configured. The reason goes to the
//! log only, never to the caller. The extractors log their refusals the same
//! way, and a [`Scoped`] extractor's insufficient scope at `info`. Wiring
//! mistakes no request can satisfy are logged at `error`: an extractor on a
//! route no [`AuthLayer`] covers (500); a required extractor behind an
//! [`allow_unauthenticated`](AuthLayer::allow_unauthenticated) layer with no
//! enforcing layer around it, an [`AuthorizedToken`] extractor behind a layer
//! with no OAuth validator, and a [`StaticTokenMatch`] extractor behind a
//! layer with no static token (each a 401 no credential can ever satisfy); a
//! [`Scoped`] extractor behind a layer with no OAuth validator (a 403); and a
//! [`ScopeSet`] holding an entry that is not a scope-token (500 — unreachable
//! in practice, since such a set does not compile).
//!
//! Every one of these events (the extractors' included) also
//! carries the stable, low-cardinality fields `auth.outcome` (`accepted`,
//! `rejected`, `passed_through`), `auth.mechanism` (`static`, `oauth`,
//! `none`) and, on a refusal, `auth.reason` (an `InvalidTokenKind` label,
//! `missing`, `insufficient_scope` or `misconfigured`) and `auth.status`
//! (401, 403 or 500); an accepted labeled static token adds
//! `auth.static_label`. Unlike the message text, their names and values are
//! covered by semver — the README's "Observability" section lists them all,
//! with the spans and the `metrics` feature's counters.

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use ::axum::Json;
use ::axum::Router;
use ::axum::body::Body;
use ::axum::extract::{FromRequestParts, OptionalFromRequestParts, Request, State};
use ::axum::middleware::Next;
use ::axum::response::{IntoResponse, Response};
use ::axum::routing::{any, get};
use http::header::WWW_AUTHENTICATE;
use http::request::Parts;
use http::{HeaderValue, Method, StatusCode};
use tracing::{error, info};
use zeroize::Zeroizing;

use crate::authenticate::{Credential, StaticTokenMatch, StaticTokens};
use crate::challenge::PROTECTED_RESOURCE_METADATA_PREFIX;
use crate::policy::StaticTokenDecision;
use crate::token::{AuthorizedToken, InvalidTokenKind, TokenRejection};
use crate::validator::OAuthValidator;

use crate::http_layer::{
    Admission, Gate, GateRan, RefusalBody, log_layer_refusal, log_oauth_accepted,
    log_passed_through, log_static_accepted,
};
#[doc(inline)]
pub use crate::http_layer::{
    AuthLayerError, CredentialSource, InvalidScope, RejectContext, RequireScopes,
    RequireScopesService,
};
use crate::observe::{
    self, Mechanism, Outcome, REASON_MISCONFIGURED, REASON_NONE, Stage, count_request,
};
pub use crate::refusal::DEFAULT_STATIC_CHALLENGE;
// What the test module (`use super::*`) used from here before these moved to
// `crate::http_layer`.
#[cfg(test)]
use crate::http_layer::{bearer_credential, names_a_token};
#[cfg(test)]
use http::{HeaderMap, HeaderName};

/// Builds a refusal's body and extra headers; see [`AuthLayerBuilder::on_reject`].
pub type RejectFn = Arc<dyn Fn(RejectContext<'_>) -> Response + Send + Sync>;

/// Which credentials are accepted, where they are read from, and how a refusal
/// looks. Cheap to clone (one `Arc`).
///
/// It is a `tower::Layer`, so `router.route_layer(auth)` (or `.layer(auth)`)
/// protects routes directly; it is also the state for the [`require_auth`]
/// middleware function (`axum::middleware::from_fn_with_state(auth,
/// require_auth)`), which behaves identically.
///
/// **Fail-closed by construction.** [`AuthLayer::builder`] refuses to build
/// without at least one credential; the only way to get a layer that lets
/// requests through unauthenticated is to call
/// [`AuthLayer::allow_unauthenticated`] by name (or to hand
/// [`AuthLayer::from_decision`] or [`AuthLayerBuilder::build_with_decision`] a
/// [`StaticTokenDecision::Unauthenticated`], which [`crate::static_token_policy`]
/// returns only when its `allow_unauthenticated` argument is `true`, and which
/// can otherwise only be named directly).
///
/// Built once at startup. Nothing in it hot-reloads: a changed static token or
/// OAuth config takes effect when a new layer is built, which in practice means
/// a restart.
#[derive(Clone)]
pub struct AuthLayer {
    inner: Arc<Mode>,
}

enum Mode {
    Enforce(Enforce),
    AllowUnauthenticated,
}

/// An enforcing layer: the credential check shared with the `tower`
/// feature's `HttpAuthLayer` (`Gate`, which also holds the static token, the
/// validator, the sources, the pre-rendered challenges and
/// [`AuthLayerBuilder::optional`]), plus this layer's axum-typed `on_reject`.
struct Enforce {
    gate: Arc<Gate>,
    on_reject: Option<RejectFn>,
}

/// Hand-written so the static token never reaches a log line through `{:?}`.
impl std::fmt::Debug for AuthLayer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &*self.inner {
            Mode::AllowUnauthenticated => f
                .debug_struct("AuthLayer")
                .field("allow_unauthenticated", &true)
                .finish(),
            Mode::Enforce(e) => f
                .debug_struct("AuthLayer")
                .field("static_tokens", &e.gate.static_tokens)
                .field("oauth", &e.gate.oauth)
                .field("sources", &e.gate.sources)
                .field("on_reject", &e.on_reject.as_ref().map(|_| "<fn>"))
                .field("static_challenge", &e.gate.static_challenge)
                .field("optional", &e.gate.optional)
                .finish(),
        }
    }
}

impl AuthLayer {
    /// Start building an enforcing layer.
    ///
    /// Give it a static token, an OAuth validator, or both; optionally the
    /// credential sources (default: `Authorization: Bearer`) and an
    /// [`on_reject`](AuthLayerBuilder::on_reject) callback. To honour
    /// `accept_static_bearer`, finish with
    /// [`build_with_decision`](AuthLayerBuilder::build_with_decision) and a
    /// [`crate::static_token_policy`] decision rather than setting the static
    /// token directly.
    ///
    /// # Examples
    ///
    /// ```
    /// use axum::{Router, http::HeaderName, routing::get};
    /// use oauth_resource_server::axum::{AuthLayer, AuthLayerError, CredentialSource};
    ///
    /// // A static API key accepted from either header. (With OAuth, add
    /// // `.oauth(validator)` as well.)
    /// let auth = AuthLayer::builder()
    ///     .static_token("example-static-key")
    ///     .sources([
    ///         CredentialSource::authorization_bearer(),
    ///         CredentialSource::Raw(HeaderName::from_static("x-api-key")),
    ///     ])
    ///     .build()
    ///     .unwrap();
    /// let app: Router = Router::new()
    ///     .route("/api", get(|| async { "protected" }))
    ///     .route_layer(auth);
    ///
    /// // Fail closed: no credential configured is an error, not a pass-through.
    /// assert_eq!(AuthLayer::builder().build().unwrap_err(), AuthLayerError::NoCredential);
    /// # let _ = app;
    /// ```
    pub fn builder() -> AuthLayerBuilder {
        AuthLayerBuilder::default()
    }

    /// A layer that lets EVERY request through, unauthenticated, and inserts no
    /// credential into request extensions (so `Option<Credential>` and
    /// `Option<AuthorizedToken>` extract `None`, and the non-`Option`
    /// extractors refuse with a 401 carrying [`DEFAULT_STATIC_CHALLENGE`]; see
    /// the [module docs](self#extractors)).
    ///
    /// The explicit opt-out. The only other pass-through is a
    /// [`crate::StaticTokenDecision::Unauthenticated`] handed to
    /// [`AuthLayer::from_decision`] or [`AuthLayerBuilder::build_with_decision`],
    /// which builds this same layer. Pair it with a loud startup warning. [`crate::static_token_policy`]
    /// returns [`crate::StaticTokenDecision::Unauthenticated`] exactly
    /// when an application has chosen this.
    ///
    /// # Security
    ///
    /// Every request reaches the protected routes. Use it only where something
    /// else (a trusted network, a proxy that authenticates) stands in front.
    /// It still marks every `Authorization` header value sensitive
    /// (`http::HeaderValue::set_sensitive`), so a credential a client sends
    /// anyway is not printed by a `Debug` of the request downstream.
    pub fn allow_unauthenticated() -> Self {
        Self {
            inner: Arc::new(Mode::AllowUnauthenticated),
        }
    }

    /// The layer a [`crate::static_token_policy`] decision calls for, with the
    /// default source (`Authorization: Bearer`) and refusal shape — the whole
    /// startup mapping in one call. Shorthand for
    /// `AuthLayer::builder().optional_oauth(oauth).build_with_decision(decision)`;
    /// use that form to set sources or `on_reject` as well.
    ///
    /// # Errors
    ///
    /// See [`AuthLayerBuilder::build_with_decision`].
    pub fn from_decision(
        decision: StaticTokenDecision,
        oauth: Option<Arc<OAuthValidator>>,
    ) -> Result<Self, AuthLayerError> {
        Self::builder()
            .optional_oauth(oauth)
            .build_with_decision(decision)
    }

    /// Whether this is the [`AuthLayer::allow_unauthenticated`] pass-through.
    pub fn allows_unauthenticated(&self) -> bool {
        matches!(*self.inner, Mode::AllowUnauthenticated)
    }

    /// The OAuth validator, when one is configured.
    pub fn oauth(&self) -> Option<&Arc<OAuthValidator>> {
        match &*self.inner {
            Mode::Enforce(e) => e.gate.oauth.as_ref(),
            Mode::AllowUnauthenticated => None,
        }
    }
}

/// Builder for an enforcing [`AuthLayer`]; see [`AuthLayer::builder`].
#[derive(Default)]
pub struct AuthLayerBuilder {
    static_token: Option<Zeroizing<String>>,
    static_tokens: Option<StaticTokens>,
    oauth: Option<Arc<OAuthValidator>>,
    sources: Option<Vec<CredentialSource>>,
    on_reject: Option<RejectFn>,
    /// `None`: not set, so [`DEFAULT_STATIC_CHALLENGE`].
    static_challenge: Option<Option<HeaderValue>>,
    optional: bool,
    required_scopes: Vec<String>,
    static_bypasses_scopes: bool,
}

impl std::fmt::Debug for AuthLayerBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AuthLayerBuilder")
            .field(
                "static_token",
                &self.static_token.as_ref().map(|_| "<redacted>"),
            )
            .field("static_tokens", &self.static_tokens)
            .field("oauth", &self.oauth)
            .field("sources", &self.sources)
            .field("on_reject", &self.on_reject.as_ref().map(|_| "<fn>"))
            .field("static_challenge", &self.static_challenge)
            .field("optional", &self.optional)
            .field("required_scopes", &self.required_scopes)
            .field("static_bypasses_scopes", &self.static_bypasses_scopes)
            .finish()
    }
}

impl AuthLayerBuilder {
    /// Accept this static token (compared in constant time). An empty string
    /// counts as no token.
    ///
    /// # Security
    ///
    /// Setting the token here bypasses `accept_static_bearer`, which only
    /// [`crate::static_token_policy`] reads; with OAuth configured, prefer
    /// [`AuthLayerBuilder::build_with_decision`]. The token's length is not
    /// hidden by the comparison, and `Debug` output shows it as `<redacted>`.
    pub fn static_token(mut self, token: impl Into<String>) -> Self {
        self.static_token = Some(Zeroizing::new(token.into()));
        self
    }

    /// [`AuthLayerBuilder::static_token`] when `Some`; for threading through the
    /// output of [`crate::static_token_policy`] or a secret loader.
    pub fn optional_static_token(mut self, token: Option<String>) -> Self {
        self.static_token = token.map(Zeroizing::new);
        self
    }

    /// Accept every token in `tokens` — several static API keys at once, for
    /// a zero-downtime key rotation or one key per client — replacing a set
    /// given earlier. Each request's candidates are compared with every
    /// entry in constant time (see [`StaticTokens`]). On a match the request's
    /// extensions get [`Credential::StaticToken`], exactly as for a single
    /// [`static_token`](Self::static_token), and the [`StaticTokenMatch`]
    /// naming the entry's label, which a handler reads with the
    /// `StaticTokenMatch` extractor.
    ///
    /// How it combines with the other static-token settings:
    ///
    /// - With [`static_token`](Self::static_token): both are accepted. A
    ///   secret given both ways counts once, under the set's label.
    /// - With [`build_with_decision`](Self::build_with_decision) (or
    ///   [`AuthLayer::from_decision`], which takes no set): the set follows
    ///   the decision — see that method.
    /// - An empty set counts as no static token, as an empty `static_token`
    ///   does: it never satisfies the fail-closed build on its own.
    ///
    /// A one-entry set behaves exactly like [`static_token`](Self::static_token)
    /// with that secret (same statuses, challenges, bodies and
    /// [`Credential`]); only the [`StaticTokenMatch`] it inserts, unlabeled
    /// or not, is new — and a layer built with `static_token` inserts an
    /// unlabeled one too.
    ///
    /// # Security
    ///
    /// Setting tokens here bypasses `accept_static_bearer` unless the layer
    /// is built with [`build_with_decision`](Self::build_with_decision).
    /// `Debug` output shows the count and labels, never a secret.
    ///
    /// # Examples
    ///
    /// ```
    /// use axum::{Router, routing::get};
    /// use oauth_resource_server::StaticTokenMatch;
    /// use oauth_resource_server::StaticTokens;
    /// use oauth_resource_server::axum::AuthLayer;
    ///
    /// async fn which_key(matched: Option<StaticTokenMatch>) -> String {
    ///     match matched {
    ///         Some(m) => format!("key {}", m.label().unwrap_or("(unlabeled)")),
    ///         None => "not a static key".to_string(),
    ///     }
    /// }
    ///
    /// let tokens = StaticTokens::new()
    ///     .with(Some("current"), "example-key-old")
    ///     .and_then(|t| t.with(Some("next"), "example-key-new"))
    ///     .unwrap();
    /// let auth = AuthLayer::builder().static_tokens(tokens).build().unwrap();
    /// let app: Router = Router::new().route("/", get(which_key)).route_layer(auth);
    /// # let _ = app;
    /// ```
    pub fn static_tokens(mut self, tokens: StaticTokens) -> Self {
        self.static_tokens = Some(tokens);
        self
    }

    /// [`AuthLayerBuilder::static_tokens`] when `Some` — for threading through
    /// the output of the `env` feature's `static_tokens_from_env`; `None`
    /// clears a set given earlier.
    pub fn optional_static_tokens(mut self, tokens: Option<StaticTokens>) -> Self {
        self.static_tokens = tokens;
        self
    }

    /// Accept OAuth access tokens this validator accepts.
    pub fn oauth(mut self, validator: Arc<OAuthValidator>) -> Self {
        self.oauth = Some(validator);
        self
    }

    /// [`AuthLayerBuilder::oauth`] when `Some`.
    pub fn optional_oauth(mut self, validator: Option<Arc<OAuthValidator>>) -> Self {
        self.oauth = validator;
        self
    }

    /// Where to read credentials from, replacing the default
    /// `[CredentialSource::authorization_bearer()]`. Every source is checked,
    /// whatever the others hold.
    pub fn sources(mut self, sources: impl IntoIterator<Item = CredentialSource>) -> Self {
        self.sources = Some(sources.into_iter().collect());
        self
    }

    /// The `WWW-Authenticate` challenge every 401 carries when NO OAuth
    /// validator is configured; with one, the validator's challenges are used
    /// and this is ignored. Default: [`DEFAULT_STATIC_CHALLENGE`].
    ///
    /// `Some(value)` sends `value` instead — `Bearer realm="my-api"`, say, or
    /// your own scheme for an API-key header. `None` sends no challenge at all
    /// and leaves any `WWW-Authenticate` an [`on_reject`](Self::on_reject)
    /// callback set untouched. That departs from RFC 9110 §15.5.2 (a 401 MUST
    /// carry a challenge); use it only to keep an existing API's responses
    /// unchanged.
    ///
    /// ```
    /// use axum::http::HeaderValue;
    /// use oauth_resource_server::axum::AuthLayer;
    ///
    /// let auth = AuthLayer::builder()
    ///     .static_token("example-static-key")
    ///     .static_challenge(Some(HeaderValue::from_static("Bearer realm=\"my-api\"")))
    ///     .build()
    ///     .unwrap();
    /// # let _ = auth;
    /// ```
    pub fn static_challenge(mut self, challenge: Option<HeaderValue>) -> Self {
        self.static_challenge = Some(challenge);
        self
    }

    /// Let a request that presents NO credential through, unauthenticated, with
    /// nothing inserted into its extensions; everything else is decided exactly
    /// as without this. For routes that serve everyone but personalize for an
    /// authenticated caller, or read-open/write-authenticated APIs.
    ///
    /// - A credential that is accepted is inserted as usual.
    /// - A credential that is presented but refused — invalid, expired, signed
    ///   by an unknown key, not the static token, or a valid token without the
    ///   required scopes — gets the same 401 or 403, with the same
    ///   `WWW-Authenticate` challenge and [`on_reject`](Self::on_reject) body,
    ///   as without `optional()`. A client with a bad token learns so, rather
    ///   than being served silently as anonymous.
    /// - A request presents no credential when EVERY value of EVERY configured
    ///   [`CredentialSource`] header is absent or blank: empty or whitespace
    ///   for a [`CredentialSource::Raw`] header; for a
    ///   [`CredentialSource::Bearer`] header, empty or whitespace after
    ///   `Bearer`, or a value using some other scheme (which carries no bearer
    ///   credential to check). This is the same classification
    ///   [`crate::authenticate()`] reports as [`TokenRejection::Missing`],
    ///   with two stricter edges: a header value that is not visible ASCII
    ///   counts as a presented credential, not as a blank one, and so does a
    ///   non-blank LATER value of a repeated header (only the first is ever
    ///   authenticated). Both are refused with the layer's 401. So are a
    ///   `Bearer` value that uses a tab instead of a space before a non-blank
    ///   token, and any `DPoP`-scheme value (RFC 9449; a sender-constrained
    ///   token this crate cannot verify must be refused, not served as
    ///   anonymous). The strict parsing of those values is unchanged: they get
    ///   exactly the refusal a non-optional layer sends.
    /// - Any [`Credential`]/[`AuthorizedToken`] an outer layer inserted is
    ///   removed first, so a pass-through always extracts as `None` (see
    ///   [nested layers](self#nested-layers)).
    ///
    /// Handlers read the outcome with `Option<Credential>` or
    /// `Option<AuthorizedToken>` (see the [module docs](self#extractors)); a
    /// handler that takes a plain `Credential` or `AuthorizedToken` refuses a
    /// passed-through request with the layer's own 401 and challenge.
    ///
    /// # Security
    ///
    /// This is not a way around the fail-closed build: [`build`](Self::build)
    /// still requires a static token or an OAuth validator, and a credential
    /// the layer cannot accept is still refused. What passes through is only
    /// what any caller could send by leaving the credential headers off, so
    /// every handler behind an optional layer must treat `None` as
    /// unauthenticated. The pass-through is logged at `debug`.
    ///
    /// # Examples
    ///
    /// ```
    /// use axum::{Router, routing::get};
    /// use oauth_resource_server::Credential;
    /// use oauth_resource_server::axum::AuthLayer;
    ///
    /// async fn greeting(credential: Option<Credential>) -> &'static str {
    ///     match credential {
    ///         Some(_) => "hello, authenticated caller",
    ///         None => "hello, anonymous caller",
    ///     }
    /// }
    ///
    /// let auth = AuthLayer::builder()
    ///     .static_token("example-static-key")
    ///     .optional()
    ///     .build()
    ///     .unwrap();
    /// let app: Router = Router::new().route("/", get(greeting)).route_layer(auth);
    /// # let _ = app;
    /// ```
    pub fn optional(mut self) -> Self {
        self.optional = true;
        self
    }

    /// Require every scope in `scopes` (all-of) of every credential this
    /// layer accepts, on top of the validator's own `required_scopes` —
    /// replacing scopes given earlier. It runs after validation, on the same
    /// validator and so the same key cache: a layer for the routes that
    /// write needs no second validator, only a second layer built from the
    /// same `Arc<OAuthValidator>` (or, simpler, a [`RequireScopes`] route
    /// layer, or the [`Scoped`] extractor, behind this one).
    ///
    /// - An OAuth token missing one is refused with 403 and a challenge
    ///   naming the validator's required scopes followed by these — the
    ///   scopes this request needs, which is what a client re-authorizes for
    ///   ([`crate::refusal_for_scopes`] sends the same bytes).
    /// - A static token has no scopes, so it is refused the same way, with
    ///   403, unless [`static_token_bypasses_scopes`](Self::static_token_bypasses_scopes).
    ///   Fail-safe by default: in dual mode a static token was never subject
    ///   to the validator's scopes, but a route that asks for scopes by name
    ///   asks for them of every credential.
    /// - An [`optional`](Self::optional) layer still passes a request that
    ///   presents no credential (its handlers must treat that as
    ///   unauthenticated); a presented one is checked.
    /// - A layer that lets everything through
    ///   ([`AuthLayer::allow_unauthenticated`]) checks nothing, this
    ///   included, so [`build_with_decision`](Self::build_with_decision)
    ///   refuses an `Unauthenticated` decision on a builder with scopes
    ///   ([`AuthLayerError::ScopesWithoutAuthentication`]) rather than
    ///   silently drop them.
    ///
    /// [`build`](Self::build) refuses an entry that is not an RFC 6749 §3.3
    /// scope-token ([`AuthLayerError::InvalidScope`]), and scopes with no
    /// OAuth validator unless static tokens bypass them
    /// ([`AuthLayerError::ScopesNeedOAuth`]).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::sync::Arc;
    ///
    /// use axum::{Router, routing::{get, post}};
    /// use oauth_resource_server::OAuthValidator;
    /// use oauth_resource_server::axum::AuthLayer;
    ///
    /// # fn app(oauth: Arc<OAuthValidator>) -> Router {
    /// let reads = AuthLayer::builder().oauth(Arc::clone(&oauth)).build().unwrap();
    /// // The same validator: one key cache for both.
    /// let writes = AuthLayer::builder()
    ///     .oauth(oauth)
    ///     .require_scopes(["docs:write"])
    ///     .build()
    ///     .unwrap();
    /// Router::new()
    ///     .merge(Router::new().route("/docs", get(|| async { "read" })).route_layer(reads))
    ///     .merge(Router::new().route("/docs/new", post(|| async { "written" })).route_layer(writes))
    /// # }
    /// ```
    pub fn require_scopes(mut self, scopes: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.required_scopes = scopes.into_iter().map(Into::into).collect();
        self
    }

    /// Let a static token pass [`require_scopes`](Self::require_scopes)
    /// instead of refusing it with 403: the static token counts as holding
    /// every scope, as it did before per-route scopes existed. Without
    /// `require_scopes` it changes nothing.
    ///
    /// # Security
    ///
    /// Opt in only where the static token is meant to be a full-access key.
    pub fn static_token_bypasses_scopes(mut self) -> Self {
        self.static_bypasses_scopes = true;
        self
    }

    /// Build the body and any extra headers of a refusal — for an API whose
    /// errors are, say, JSON. Without it a refusal has an empty body. The
    /// [`RejectContext`] carries the rejection, the status and the request's
    /// parts (method, URI, headers), so the shape can depend on, say, `Accept`.
    ///
    /// The callback shapes the response only; it cannot change the outcome.
    /// Whatever it returns, the status is set to [`RejectContext::status`] (401
    /// for a missing or invalid credential, 403 for insufficient scope), and
    /// `WWW-Authenticate` is set to the layer's challenge, replacing any the
    /// callback set: the validator's when OAuth is configured — every 401/403
    /// must carry it, or claude.ai (among others) never starts the
    /// authorization flow — and otherwise the
    /// [`static_challenge`](Self::static_challenge). Only with
    /// `static_challenge(None)` and no OAuth are the callback's headers left
    /// as they are.
    ///
    /// Never put [`TokenRejection::Invalid`]'s reason in the body: telling an
    /// unauthenticated caller exactly which check failed is a free oracle. The
    /// credential headers in [`RejectContext::request`] are marked sensitive,
    /// and `RejectContext`'s `Debug` prints no header values.
    pub fn on_reject(
        mut self,
        f: impl Fn(RejectContext<'_>) -> Response + Send + Sync + 'static,
    ) -> Self {
        self.on_reject = Some(Arc::new(f));
        self
    }

    /// Build the layer a [`crate::static_token_policy`] decision calls for,
    /// keeping this builder's sources and `on_reject`.
    ///
    /// The decision's static token (if any) replaces one set on this builder.
    /// [`StaticTokenDecision::Unauthenticated`] yields
    /// [`AuthLayer::allow_unauthenticated`] — the decision is itself the
    /// application's explicit opt-out, since `static_token_policy` returns it
    /// only when asked to allow unauthenticated access. Every other decision
    /// builds an enforcing layer exactly as [`AuthLayerBuilder::build`] does.
    ///
    /// A [`static_tokens`](Self::static_tokens) set follows the decision,
    /// which speaks about one token (pass the current one to
    /// `static_token_policy`):
    ///
    /// | Decision | The builder's `static_tokens` set |
    /// |---|---|
    /// | `StaticOnly(t)`, `StaticAndOAuth(t)` | kept, and merged with `t` (a `t` already in the set counts once, under its label) |
    /// | `StaticIgnored` | dropped, with `t`: `accept_static_bearer: false` wins over every static token |
    /// | `OAuthOnly`, `Unauthenticated` | [`AuthLayerError::DecisionWithoutStaticToken`] — the policy was never told a static token exists, so the decision cannot speak for the set, and honouring it would silently drop the keys (or open the routes despite them) |
    ///
    /// An empty set is no set: it never causes that error.
    ///
    /// # Errors
    ///
    /// The decision must agree with the validator given via
    /// [`AuthLayerBuilder::oauth`]: [`AuthLayerError::DecisionNeedsOAuth`] when
    /// it was made with OAuth on and no validator was given,
    /// [`AuthLayerError::DecisionWithoutOAuth`] when it was made with OAuth off
    /// (including `Unauthenticated`) and one was given. Then
    /// [`AuthLayerError::DecisionWithoutStaticToken`] as above, then
    /// [`AuthLayerError::ScopesWithoutAuthentication`] for
    /// [`require_scopes`](Self::require_scopes) with an `Unauthenticated`
    /// decision. Otherwise as [`AuthLayerBuilder::build`].
    pub fn build_with_decision(
        mut self,
        decision: StaticTokenDecision,
    ) -> Result<AuthLayer, AuthLayerError> {
        Gate::check_decision(&decision, self.oauth.is_some())?;
        let unauthenticated = decision == StaticTokenDecision::Unauthenticated;
        let (token, tokens) = Gate::decision_tokens(decision, self.static_tokens.take())?;
        if unauthenticated && !self.required_scopes.is_empty() {
            return Err(AuthLayerError::ScopesWithoutAuthentication);
        }
        if unauthenticated {
            return Ok(AuthLayer::allow_unauthenticated());
        }
        self.static_token = token;
        self.static_tokens = tokens;
        self.build()
    }

    /// Build the layer.
    ///
    /// # Errors
    ///
    /// [`AuthLayerError::NoCredential`] with neither a non-blank static token
    /// (from [`static_token`](Self::static_token) or a non-empty
    /// [`static_tokens`](Self::static_tokens) set) nor an OAuth validator;
    /// [`AuthLayerError::NoSources`] with an empty
    /// source list; [`AuthLayerError::InvalidChallenge`] when the validator's
    /// challenge is not a valid header value (only reachable from a
    /// hand-edited resolved config); [`AuthLayerError::InvalidScope`] and
    /// [`AuthLayerError::ScopesNeedOAuth`] as
    /// [`require_scopes`](Self::require_scopes) says.
    pub fn build(self) -> Result<AuthLayer, AuthLayerError> {
        // The fail-closed checks, shared with the `tower` feature's
        // `HttpAuthLayerBuilder::build`.
        let gate = Gate::build(
            self.static_token,
            self.static_tokens,
            self.oauth,
            self.sources,
            self.static_challenge,
            self.optional,
            self.required_scopes,
            self.static_bypasses_scopes,
        )?;
        Ok(AuthLayer {
            inner: Arc::new(Mode::Enforce(Enforce {
                gate: Arc::new(gate),
                on_reject: self.on_reject,
            })),
        })
    }
}

impl Enforce {
    /// The response for a refusal. The status and (with OAuth) the
    /// `WWW-Authenticate` challenge are fixed here, after `on_reject`, so no
    /// callback can drop or contradict them.
    ///
    /// A request with NO credential gets the same `invalid_token` challenge as a
    /// bad one. RFC 6750 §3.1 says a server SHOULD NOT send an error code then,
    /// but this is the challenge claude.ai and Claude Code start the flow from,
    /// and the part they depend on — `resource_metadata` — is present either
    /// way. The distinction lives in the log level only.
    ///
    /// Without OAuth the challenge is the builder's `static_challenge`
    /// ([`DEFAULT_STATIC_CHALLENGE`] unless set), which RFC 9110 §15.5.2
    /// requires on every 401. An application that opted out with
    /// `static_challenge(None)` gets none (a deliberate deviation, for keeping
    /// an existing API's responses byte-identical) and keeps whatever its
    /// callback set.
    ///
    /// The status and the challenge come from the same decision as the public
    /// [`crate::refusal()`] (`refusal::select`, through `Gate`), so an
    /// integration built on `refusal()` sends exactly what this layer sends.
    fn reject(&self, rejection: &TokenRejection, request: &Parts) -> Response {
        self.reject_with(rejection, request, None)
    }

    /// [`Enforce::reject`], with a per-request 403 challenge
    /// (`Gate::scope_challenge`) in place of the layer's own when `Some`.
    fn reject_with(
        &self,
        rejection: &TokenRejection,
        request: &Parts,
        insufficient: Option<&HeaderValue>,
    ) -> Response {
        let (status, _) = self.gate.status_and_challenge_with(rejection, insufficient);
        let response = match &self.on_reject {
            Some(f) => f(RejectContext {
                rejection,
                status,
                request,
            }),
            None => Response::new(Body::empty()),
        };
        // `finish_with` sets the status and `insert`s the challenge, replacing
        // every value the callback set.
        self.gate.finish_with(rejection, insufficient, response)
    }

    /// The refusal for a [`Scoped`] extractor whose credential lacks
    /// `required`: 403 with the layer's own body and a challenge naming the
    /// layer's scopes followed by `required` — the same bytes the
    /// [`RequireScopes`] route layer sends for the same scopes. A layer with
    /// no OAuth validator can never satisfy it, which is logged at `error`.
    fn refuse_scoped(&self, request: &Parts, required: &[String]) -> Response {
        let path = request.uri.path();
        let rejection = TokenRejection::InsufficientScope;
        let mechanism = Mechanism::of_request(request.extensions.get::<Credential>(), &rejection);
        if self.gate.oauth.is_none() {
            count_request(
                Stage::Handler,
                Outcome::Rejected,
                mechanism,
                REASON_MISCONFIGURED,
            );
            error!(
                path = %path,
                required = ?required,
                auth.outcome = Outcome::Rejected.as_str(),
                auth.mechanism = mechanism.as_str(),
                auth.reason = REASON_MISCONFIGURED,
                auth.status = 403u16,
                "Server misconfiguration: the handler requires scopes, but its AuthLayer has no \
                 OAuth validator, so no credential can carry them; refusing the request"
            );
        } else {
            count_request(
                Stage::Handler,
                Outcome::Rejected,
                mechanism,
                observe::reason(&rejection),
            );
            let present = match request.extensions.get::<Credential>() {
                Some(Credential::OAuth(token)) => token.scopes.clone(),
                _ => Vec::new(),
            };
            info!(
                path = %path,
                required = ?required,
                present = ?crate::token::scopes_for_log(&present),
                auth.outcome = Outcome::Rejected.as_str(),
                auth.mechanism = mechanism.as_str(),
                auth.reason = observe::reason(&rejection),
                auth.status = 403u16,
                "The credential lacks the scopes this handler requires"
            );
        }
        // Without OAuth: the bare `insufficient_scope` challenge.
        let insufficient = self.gate.scope_challenge(required);
        self.reject_with(&rejection, request, insufficient.as_ref())
    }

    /// Log a refusal at the level the [module docs](self#logging) give (with
    /// `mechanism` as `auth.mechanism`), then build its response with
    /// [`Enforce::reject`]. Every refusal — the layer's own and an
    /// extractor's — goes through here.
    fn refuse(
        &self,
        rejection: &TokenRejection,
        request: &Parts,
        mechanism: Mechanism,
        stage: Stage,
    ) -> Response {
        // Every OAuth client's first request carries no credential (401 →
        // read `resource_metadata` → authorize), so it is logged at `debug`,
        // not as a warning.
        log_layer_refusal!(&self.gate, request, rejection, mechanism, stage);
        self.reject(rejection, request)
    }
}

/// Inserted into a request's extensions by every [`AuthLayer`] it passes, so
/// the extractors can tell "the layer ran and inserted no credential" (answer
/// with that layer's own refusal) from "no layer ran" (a server
/// misconfiguration). The type is private, so nothing outside this module can
/// insert, read or forge it.
#[derive(Clone)]
struct LayerRan(AuthLayer);

/// [`RefusalBody::build`] for an [`AuthLayer`]: its `on_reject`, if any.
fn axum_refusal_body(
    source: &(dyn std::any::Any + Send + Sync),
    cx: RejectContext<'_>,
) -> Option<Response> {
    match source.downcast_ref::<Mode>()? {
        Mode::Enforce(Enforce {
            on_reject: Some(f), ..
        }) => Some(f(cx)),
        _ => None,
    }
}

impl AuthLayer {
    /// Insert the markers a route-level scope check behind this layer reads
    /// (`http_layer::GateRan`, and this layer's refusal builder), shared with
    /// the `tower` feature's layer.
    fn mark(&self, extensions: &mut http::Extensions) {
        let gate = match &*self.inner {
            Mode::Enforce(enforce) => Some(Arc::clone(&enforce.gate)),
            Mode::AllowUnauthenticated => None,
        };
        // An `allow_unauthenticated` layer inside an enforcing one leaves the
        // outer marker in place: the credential a route check behind both
        // judges is the outer layer's, so its refusal must be too (a 403
        // step-up with the outer challenge, never the open layer's 401).
        if gate.is_none() && extensions.get::<GateRan>().is_some() {
            return;
        }
        extensions.insert(GateRan(gate));
        extensions.insert(RefusalBody::<Body> {
            source: Arc::clone(&self.inner) as Arc<dyn std::any::Any + Send + Sync>,
            build: axum_refusal_body,
        });
    }
}

impl AuthLayer {
    /// Authenticate `request`: the request to pass on (with the credential in
    /// its extensions), or the refusal to answer with. The one implementation
    /// behind both [`require_auth`] and the `tower::Layer` service, so the two
    /// cannot drift apart.
    async fn check(&self, mut request: Request) -> Result<Request, Response> {
        let enforce = match &*self.inner {
            Mode::AllowUnauthenticated => {
                count_request(
                    Stage::Layer,
                    Outcome::PassedThrough,
                    Mechanism::None,
                    REASON_NONE,
                );
                // Inside another axum layer, leave its `LayerRan` in place,
                // exactly as `mark` leaves its `GateRan`: the extractors and
                // the route-level checks then refuse with the same (outer)
                // layer's 401 and challenge (`resource_metadata` included),
                // never this open layer's bare one.
                if request.extensions().get::<LayerRan>().is_none() {
                    request.extensions_mut().insert(LayerRan(self.clone()));
                }
                crate::http_layer::mark_authorization_sensitive(request.headers_mut());
                self.mark(request.extensions_mut());
                return Ok(request);
            }
            Mode::Enforce(enforce) => enforce,
        };

        let (mut parts, body) = request.into_parts();
        // `Gate::admit` (shared with the `tower` feature's `HttpAuthLayer`):
        // clear an outer layer's credential for an optional layer, mark the
        // source headers sensitive, `authenticate`, insert what was accepted,
        // and decide an optional layer's pass-through. Logging stays here, so
        // its target stays `oauth_resource_server::axum`.
        match enforce.gate.admit(&mut parts).await {
            Admission::Static => log_static_accepted!(&parts),
            Admission::OAuth(token) => log_oauth_accepted!(&parts, &token),
            Admission::PassedThrough => log_passed_through!(&parts),
            Admission::Refused(rejection, mechanism) => {
                return Err(enforce.refuse(&rejection, &parts, mechanism, Stage::Layer));
            }
        }
        parts.extensions.insert(LayerRan(self.clone()));
        self.mark(&mut parts.extensions);
        Ok(Request::from_parts(parts, body))
    }

    /// The refusal for an extractor whose value the layer did not insert: the
    /// same response the layer itself gives a request with no acceptable
    /// credential, built by the same [`Enforce::reject`]. `wants` names what
    /// the extractor needs.
    ///
    /// Three wirings give a 401 no credential can ever satisfy — a required
    /// extractor behind [`AuthLayer::allow_unauthenticated`] with no
    /// enforcing layer around it, an [`AuthorizedToken`] extractor behind a
    /// layer with no OAuth validator, and a [`StaticTokenMatch`] extractor
    /// behind a layer with no static token — so, like the no-layer 500, they
    /// are logged at `error` rather than as an ordinary refusal. Behind an
    /// `allow_unauthenticated` layer INSIDE an enforcing `HttpAuthLayer` (a
    /// `GateRan` holding a gate, with no `LayerRan` of an enforcing axum
    /// layer), the refusal is that layer's, through
    /// `http_layer::scope_refusal`: its 401 and challenge.
    fn refuse_extraction(
        &self,
        rejection: &TokenRejection,
        parts: &Parts,
        wants: Wants,
    ) -> Response {
        let mechanism = Mechanism::of_request(parts.extensions.get::<Credential>(), rejection);
        let misconfigured = || {
            count_request(
                Stage::Handler,
                Outcome::Rejected,
                mechanism,
                REASON_MISCONFIGURED,
            )
        };
        match &*self.inner {
            Mode::Enforce(enforce)
                if wants == Wants::OAuthToken && enforce.gate.oauth.is_none() =>
            {
                misconfigured();
                error!(
                    path = %parts.uri.path(),
                    auth.outcome = Outcome::Rejected.as_str(),
                    auth.mechanism = mechanism.as_str(),
                    auth.reason = REASON_MISCONFIGURED,
                    auth.status = observe::status(rejection),
                    "Server misconfiguration: the handler requires an OAuth access token, but \
                     its AuthLayer has no OAuth validator; refusing the request"
                );
                enforce.reject(rejection, parts)
            }
            Mode::Enforce(enforce)
                if wants == Wants::StaticToken && enforce.gate.static_tokens.is_none() =>
            {
                misconfigured();
                error!(
                    path = %parts.uri.path(),
                    auth.outcome = Outcome::Rejected.as_str(),
                    auth.mechanism = mechanism.as_str(),
                    auth.reason = REASON_MISCONFIGURED,
                    auth.status = observe::status(rejection),
                    "Server misconfiguration: the handler requires a static token, but its \
                     AuthLayer has no static token; refusing the request"
                );
                enforce.reject(rejection, parts)
            }
            Mode::Enforce(enforce) => enforce.refuse(rejection, parts, mechanism, Stage::Handler),
            // Inside an enforcing `HttpAuthLayer` (an `optional()` one that
            // passed a request with no credential, or one that accepted a
            // credential of the wrong kind): that layer's refusal — its 401,
            // its challenge with `resource_metadata` — through the shared gate
            // marker, exactly as `RequireScopes` and `Scoped` answer on the
            // same stack. (Inside an enforcing axum layer, `LayerRan` already
            // names that layer, so this arm is not reached.)
            Mode::AllowUnauthenticated
                if matches!(parts.extensions.get::<GateRan>(), Some(GateRan(Some(_)))) =>
            {
                crate::http_layer::scope_refusal::<Body>(parts, rejection, &[], wants.extractor())
            }
            // No challenge of its own to send: the default one, as a
            // static-only layer would (RFC 9110 §15.5.2).
            Mode::AllowUnauthenticated => {
                misconfigured();
                error!(
                    path = %parts.uri.path(),
                    auth.outcome = Outcome::Rejected.as_str(),
                    auth.mechanism = mechanism.as_str(),
                    auth.reason = REASON_MISCONFIGURED,
                    auth.status = 401u16,
                    "Server misconfiguration: the handler requires a credential, but its \
                     AuthLayer allows unauthenticated requests; refusing the request"
                );
                (
                    StatusCode::UNAUTHORIZED,
                    [(
                        WWW_AUTHENTICATE,
                        HeaderValue::from_static(DEFAULT_STATIC_CHALLENGE),
                    )],
                )
                    .into_response()
            }
        }
    }
}

/// What an extractor needs from the request.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Wants {
    /// Any credential ([`Credential`]).
    AnyCredential,
    /// An OAuth access token ([`AuthorizedToken`]).
    OAuthToken,
    /// A static token ([`StaticTokenMatch`]).
    StaticToken,
}

impl Wants {
    /// The extractor's name, as the refusal logs give it.
    fn extractor(self) -> &'static str {
        match self {
            Self::AnyCredential => "Credential",
            Self::OAuthToken => "AuthorizedToken",
            Self::StaticToken => "StaticTokenMatch",
        }
    }
}

/// What the extractors find on a request.
enum Found<T> {
    /// The layer inserted it.
    Present(T),
    /// An [`AuthLayer`] ran but inserted no `T`.
    Absent(AuthLayer),
    /// No [`AuthLayer`] ran.
    NoLayer,
}

fn find<T: Clone + Send + Sync + 'static>(parts: &Parts) -> Found<T> {
    match (
        parts.extensions.get::<T>(),
        parts.extensions.get::<LayerRan>(),
    ) {
        (Some(value), _) => Found::Present(value.clone()),
        (None, Some(LayerRan(layer))) => Found::Absent(layer.clone()),
        (None, None) => Found::NoLayer,
    }
}

/// The response for an extractor on a route no [`AuthLayer`] covers: 500, and
/// an `error` log naming the mistake. Never access, never "anonymous".
fn no_layer(parts: &Parts, extractor: &'static str) -> Response {
    count_request(
        Stage::Handler,
        Outcome::Rejected,
        Mechanism::None,
        REASON_MISCONFIGURED,
    );
    error!(
        path = %parts.uri.path(),
        extractor,
        auth.outcome = Outcome::Rejected.as_str(),
        auth.mechanism = Mechanism::None.as_str(),
        auth.reason = REASON_MISCONFIGURED,
        auth.status = 500u16,
        "Server misconfiguration: an authentication extractor ran on a route no AuthLayer \
         covers; refusing the request"
    );
    StatusCode::INTERNAL_SERVER_ERROR.into_response()
}

/// The [`AuthLayer`]'s refusal for a required extractor with nothing to
/// extract. A static-token request asking for an [`AuthorizedToken`] (or an
/// OAuth request asking for a [`StaticTokenMatch`]) is a presented credential
/// of the wrong kind, so it is `Invalid`, not `Missing`.
fn refuse_absent(layer: &AuthLayer, parts: &Parts, wants: Wants) -> Response {
    let rejection = match (parts.extensions.get::<Credential>(), wants) {
        (Some(_), Wants::StaticToken) => TokenRejection::invalid(
            InvalidTokenKind::StaticTokenRequired,
            "a credential was accepted, but the handler requires a static token",
        ),
        (Some(_), _) => TokenRejection::invalid(
            InvalidTokenKind::OAuthTokenRequired,
            "a credential was accepted, but the handler requires an OAuth access token",
        ),
        (None, _) => TokenRejection::Missing,
    };
    layer.refuse_extraction(&rejection, parts, wants)
}

/// Extracts the OAuth token an [`AuthLayer`] accepted.
///
/// Refuses with the layer's own 401 and `WWW-Authenticate` challenge when no
/// token is in the extensions — an [`optional`](AuthLayerBuilder::optional) or
/// [`allow_unauthenticated`](AuthLayer::allow_unauthenticated) layer passed the
/// request through, or the static token was accepted — and with 500 (logged at
/// `error`) on a route no [`AuthLayer`] covers. Behind nested strict layers the
/// token may have been inserted by an OUTER layer even when the innermost one
/// accepted the static token; see the [module docs](self#nested-layers).
///
/// # Examples
///
/// ```
/// use axum::{Router, routing::get};
/// use oauth_resource_server::AuthorizedToken;
///
/// async fn subject(token: AuthorizedToken) -> String {
///     token.subject.unwrap_or_default()
/// }
/// # let _: Router = Router::new().route("/", get(subject));
/// ```
#[cfg_attr(docsrs, doc(cfg(feature = "axum")))]
impl<S: Send + Sync> FromRequestParts<S> for AuthorizedToken {
    type Rejection = Response;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Response> {
        match find::<AuthorizedToken>(parts) {
            Found::Present(token) => Ok(token),
            Found::Absent(layer) => Err(refuse_absent(&layer, parts, Wants::OAuthToken)),
            Found::NoLayer => Err(no_layer(parts, "AuthorizedToken")),
        }
    }
}

/// `Option<AuthorizedToken>`: `None` when an [`AuthLayer`] ran and no OAuth
/// token is in the extensions (no credential under an
/// [`optional`](AuthLayerBuilder::optional) or
/// [`allow_unauthenticated`](AuthLayer::allow_unauthenticated) layer, or the
/// static token was accepted and no outer strict layer inserted a token — see
/// [nested layers](self#nested-layers)). On a route no [`AuthLayer`] covers it
/// still refuses with 500, logged at `error`, rather than reading as anonymous.
#[cfg_attr(docsrs, doc(cfg(feature = "axum")))]
impl<S: Send + Sync> OptionalFromRequestParts<S> for AuthorizedToken {
    type Rejection = Response;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Option<Self>, Response> {
        match find::<AuthorizedToken>(parts) {
            Found::Present(token) => Ok(Some(token)),
            Found::Absent(_) => Ok(None),
            Found::NoLayer => Err(no_layer(parts, "Option<AuthorizedToken>")),
        }
    }
}

/// Extracts the credential an [`AuthLayer`] accepted.
///
/// Refuses with the layer's own 401 and `WWW-Authenticate` challenge when the
/// layer inserted none (an [`optional`](AuthLayerBuilder::optional) or
/// [`allow_unauthenticated`](AuthLayer::allow_unauthenticated) layer passed the
/// request through), and with 500 (logged at `error`) on a route no
/// [`AuthLayer`] covers. See the [module docs](self#extractors).
///
/// # Examples
///
/// ```
/// use axum::{Router, routing::get};
/// use oauth_resource_server::Credential;
///
/// async fn whoami(credential: Credential) -> String {
///     match credential {
///         Credential::OAuth(token) => format!("subject {:?}", token.subject),
///         Credential::StaticToken => "the static API key".to_string(),
///         _ => "some other credential".to_string(),
///     }
/// }
/// # let _: Router = Router::new().route("/", get(whoami));
/// ```
#[cfg_attr(docsrs, doc(cfg(feature = "axum")))]
impl<S: Send + Sync> FromRequestParts<S> for Credential {
    type Rejection = Response;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Response> {
        match find::<Credential>(parts) {
            Found::Present(credential) => Ok(credential),
            Found::Absent(layer) => Err(refuse_absent(&layer, parts, Wants::AnyCredential)),
            Found::NoLayer => Err(no_layer(parts, "Credential")),
        }
    }
}

/// `Option<Credential>`: `None` when an [`AuthLayer`] ran and inserted no
/// credential (no credential under an [`optional`](AuthLayerBuilder::optional)
/// or [`allow_unauthenticated`](AuthLayer::allow_unauthenticated) layer). On a
/// route no [`AuthLayer`] covers it still refuses with 500, logged at `error`,
/// rather than reading as anonymous.
#[cfg_attr(docsrs, doc(cfg(feature = "axum")))]
impl<S: Send + Sync> OptionalFromRequestParts<S> for Credential {
    type Rejection = Response;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Option<Self>, Response> {
        match find::<Credential>(parts) {
            Found::Present(credential) => Ok(Some(credential)),
            Found::Absent(_) => Ok(None),
            Found::NoLayer => Err(no_layer(parts, "Option<Credential>")),
        }
    }
}

/// Extracts which static token an [`AuthLayer`] accepted — its
/// [`label`](StaticTokenMatch::label), for an audit log or a per-client
/// decision.
///
/// Refuses, fail-closed, exactly as the [`AuthorizedToken`] extractor does:
/// with the layer's own 401 and `WWW-Authenticate` challenge when the layer
/// inserted none (an OAuth token was accepted, or an
/// [`optional`](AuthLayerBuilder::optional) or
/// [`allow_unauthenticated`](AuthLayer::allow_unauthenticated) layer passed
/// the request through), logged at `error` when the layer has no static token
/// at all, and with 500 (logged at `error`) on a route no [`AuthLayer`]
/// covers. The layer inserts one next to every [`Credential::StaticToken`] —
/// unlabeled for a single [`static_token`](AuthLayerBuilder::static_token) —
/// and removes an outer layer's whenever it accepts an OAuth token, so it
/// always describes the innermost accepted [`Credential`].
///
/// # Examples
///
/// ```
/// use axum::{Router, routing::get};
/// use oauth_resource_server::StaticTokenMatch;
///
/// async fn audit(matched: StaticTokenMatch) -> String {
///     format!("static key {:?}", matched.label())
/// }
/// # let _: Router = Router::new().route("/", get(audit));
/// ```
#[cfg_attr(docsrs, doc(cfg(feature = "axum")))]
impl<S: Send + Sync> FromRequestParts<S> for StaticTokenMatch {
    type Rejection = Response;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Response> {
        match find::<StaticTokenMatch>(parts) {
            Found::Present(matched) => Ok(matched),
            Found::Absent(layer) => Err(refuse_absent(&layer, parts, Wants::StaticToken)),
            Found::NoLayer => Err(no_layer(parts, "StaticTokenMatch")),
        }
    }
}

/// `Option<StaticTokenMatch>`: `None` when an [`AuthLayer`] ran and accepted
/// no static token (an OAuth token was accepted, or nothing was presented to
/// an [`optional`](AuthLayerBuilder::optional) or
/// [`allow_unauthenticated`](AuthLayer::allow_unauthenticated) layer). On a
/// route no [`AuthLayer`] covers it still refuses with 500, logged at
/// `error`, rather than reading as anonymous.
#[cfg_attr(docsrs, doc(cfg(feature = "axum")))]
impl<S: Send + Sync> OptionalFromRequestParts<S> for StaticTokenMatch {
    type Rejection = Response;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Option<Self>, Response> {
        match find::<StaticTokenMatch>(parts) {
            Found::Present(matched) => Ok(Some(matched)),
            Found::Absent(_) => Ok(None),
            Found::NoLayer => Err(no_layer(parts, "Option<StaticTokenMatch>")),
        }
    }
}

/// A set of scopes a handler requires, named as a type so the requirement is
/// part of the handler's signature: see [`Scoped`].
///
/// Implement it on a unit type of your own, once per distinct requirement.
/// Every entry must be an RFC 6749 §3.3 scope-token (printable ASCII with no
/// space, `"` or `\`); a set holding any other entry could never be
/// satisfied, so using it as a [`Scoped`] extractor is a **compile error**
/// (checked in a `const`, when the extractor is instantiated):
///
/// ```compile_fail
/// use axum::{Router, routing::post};
/// use oauth_resource_server::axum::{ScopeSet, Scoped};
///
/// struct Broken;
/// impl ScopeSet for Broken {
///     const SCOPES: &'static [&'static str] = &["two words"];
/// }
///
/// async fn handler(_: Scoped<Broken>) {}
///
/// let app: Router = Router::new().route("/", post(handler));
/// # let _ = app;
/// ```
///
/// ```
/// use oauth_resource_server::axum::ScopeSet;
///
/// struct DocsWrite;
/// impl ScopeSet for DocsWrite {
///     const SCOPES: &'static [&'static str] = &["docs:write"];
/// }
/// ```
pub trait ScopeSet: Send + Sync + 'static {
    /// The scopes required, all-of.
    const SCOPES: &'static [&'static str];
}

/// An axum extractor for the OAuth token an [`AuthLayer`] accepted, refusing
/// unless it carries every scope in `S` ([`ScopeSet::SCOPES`]) — a
/// per-handler scope requirement written in the handler's signature, checked
/// with [`AuthorizedToken::require_scopes`] on top of the layer's own.
///
/// Derefs to the [`AuthorizedToken`]. Refuses exactly as the layer and the
/// other extractors do, through the layer's own refusal path (status,
/// `WWW-Authenticate` and [`on_reject`](AuthLayerBuilder::on_reject) body):
///
/// | The request… | Answer |
/// |---|---|
/// | carries an OAuth token with every scope in `S` | the token |
/// | carries an OAuth token missing one | 403, with a challenge naming the layer's scopes followed by `S`'s — the same bytes as a [`RequireScopes`] layer with those scopes |
/// | was accepted with a static token (it has no scopes) | 403 the same way (logged at `error` when the layer has no OAuth validator: nothing can satisfy it) |
/// | carries no credential (an [`optional`](AuthLayerBuilder::optional) or [`allow_unauthenticated`](AuthLayer::allow_unauthenticated) layer passed it) | the layer's own 401, as the [`AuthorizedToken`] extractor answers |
/// | carries no credential behind only the `tower` feature's `HttpAuthLayer` (an `optional()` one) | that layer's own 401 |
/// | never went through an [`AuthLayer`] or an `HttpAuthLayer` | 500, logged at `error` |
///
/// There is no static-token opt-in here, since a static token has no
/// [`AuthorizedToken`] to extract: for a route a static key may also reach,
/// use a [`RequireScopes`] layer with
/// [`static_token_bypasses_scopes`](RequireScopes::static_token_bypasses_scopes)
/// and the [`Credential`] extractor.
///
/// # Examples
///
/// ```
/// use axum::{Router, routing::post};
/// use oauth_resource_server::axum::{AuthLayer, ScopeSet, Scoped};
///
/// struct DocsWrite;
/// impl ScopeSet for DocsWrite {
///     const SCOPES: &'static [&'static str] = &["docs:write"];
/// }
///
/// async fn write(token: Scoped<DocsWrite>) -> String {
///     format!("written by {:?}", token.subject)
/// }
///
/// # fn app(auth: AuthLayer) -> Router {
/// Router::new().route("/docs", post(write)).route_layer(auth)
/// # }
/// ```
pub struct Scoped<S: ScopeSet> {
    token: AuthorizedToken,
    _scopes: std::marker::PhantomData<fn() -> S>,
}

impl<S: ScopeSet> Scoped<S> {
    /// The token.
    pub fn token(&self) -> &AuthorizedToken {
        &self.token
    }

    /// The token, by value.
    pub fn into_token(self) -> AuthorizedToken {
        self.token
    }
}

impl<S: ScopeSet> std::ops::Deref for Scoped<S> {
    type Target = AuthorizedToken;

    fn deref(&self) -> &AuthorizedToken {
        &self.token
    }
}

impl<S: ScopeSet> Clone for Scoped<S> {
    fn clone(&self) -> Self {
        Self {
            token: self.token.clone(),
            _scopes: std::marker::PhantomData,
        }
    }
}

/// The token's own `Debug` (claim names only, never values), plus the scope
/// set required.
impl<S: ScopeSet> std::fmt::Debug for Scoped<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Scoped")
            .field("required", &S::SCOPES)
            .field("token", &self.token)
            .finish()
    }
}

#[cfg_attr(docsrs, doc(cfg(feature = "axum")))]
impl<S: ScopeSet, St: Send + Sync> FromRequestParts<St> for Scoped<S> {
    type Rejection = Response;

    async fn from_request_parts(parts: &mut Parts, _state: &St) -> Result<Self, Response> {
        // A `ScopeSet` naming a scope no token can carry fails the build of
        // any program that uses it as an extractor.
        let () = ValidScopeSet::<S>::CHECKED;
        // Unreachable after the check above; kept so the extractor never
        // proceeds on an unchecked set even if the check were removed.
        let Ok(required) = crate::http_layer::checked_scopes(S::SCOPES.iter().copied()) else {
            count_request(
                Stage::Handler,
                Outcome::Rejected,
                Mechanism::None,
                REASON_MISCONFIGURED,
            );
            error!(
                path = %parts.uri.path(),
                extractor = std::any::type_name::<S>(),
                auth.outcome = Outcome::Rejected.as_str(),
                auth.mechanism = Mechanism::None.as_str(),
                auth.reason = REASON_MISCONFIGURED,
                auth.status = 500u16,
                "Server misconfiguration: a ScopeSet holds an entry that is not a valid scope, \
                 which no token can carry; refusing the request"
            );
            return Err(StatusCode::INTERNAL_SERVER_ERROR.into_response());
        };
        match find::<Credential>(parts) {
            Found::Present(Credential::OAuth(token)) if token.require_scopes(S::SCOPES).is_ok() => {
                Ok(Self {
                    token,
                    _scopes: std::marker::PhantomData,
                })
            }
            // Valid, but insufficient: a token missing a scope, or a static
            // token, which has none.
            // The innermost layer's gate (`GateRan`) decides, as it does for
            // `RequireScopes`, so the two send the same bytes on any stack;
            // the axum layer's own path when that gate is the axum layer's.
            Found::Present(_) => {
                let gate = match parts.extensions.get::<GateRan>() {
                    Some(GateRan(Some(gate))) => Some(Arc::clone(gate)),
                    _ => None,
                };
                let layer = parts.extensions.get::<LayerRan>().map(|l| &*l.0.inner);
                Err(match (gate, layer) {
                    (Some(gate), Some(Mode::Enforce(enforce)))
                        if Arc::ptr_eq(&gate, &enforce.gate) =>
                    {
                        enforce.refuse_scoped(parts, &required)
                    }
                    (None, Some(Mode::Enforce(enforce))) => enforce.refuse_scoped(parts, &required),
                    // Accepted by the `tower` feature's layer (inside or
                    // outside the axum one), or by an outer layer around an
                    // `allow_unauthenticated` one: the same shared refusal
                    // path, through the gate marker.
                    _ => crate::http_layer::scope_refusal::<Body>(
                        parts,
                        &TokenRejection::InsufficientScope,
                        &required,
                        "Scoped",
                    ),
                })
            }
            Found::Absent(layer) => Err(refuse_absent(&layer, parts, Wants::OAuthToken)),
            // No axum layer, but the `tower` feature's `HttpAuthLayer` ran
            // (an `optional()` one passed a request with no credential): its
            // own 401 and challenge, through the shared gate marker.
            Found::NoLayer if parts.extensions.get::<GateRan>().is_some() => {
                Err(crate::http_layer::scope_refusal::<Body>(
                    parts,
                    &TokenRejection::Missing,
                    &required,
                    "Scoped",
                ))
            }
            Found::NoLayer => Err(no_layer(parts, "Scoped")),
        }
    }
}

/// The compile-time check behind [`Scoped`]: `CHECKED` fails to evaluate —
/// a build error wherever `Scoped<S>` is used as an extractor — when an entry
/// of `S::SCOPES` is not an RFC 6749 §3.3 scope-token.
struct ValidScopeSet<S>(std::marker::PhantomData<S>);

impl<S: ScopeSet> ValidScopeSet<S> {
    const CHECKED: () = assert!(
        crate::http_layer::all_scope_tokens(S::SCOPES),
        "every ScopeSet::SCOPES entry must be an RFC 6749 §3.3 scope-token: printable ASCII \
         with no space, '\"' or '\\'"
    );
}

/// The authentication middleware, for [`axum::middleware::from_fn_with_state`]
/// with an [`AuthLayer`] as state. Equivalent to using the [`AuthLayer`] as a
/// `tower::Layer` directly.
///
/// Collects one candidate per configured [`CredentialSource`] and runs
/// [`crate::authenticate()`] over them: any candidate matching the static token
/// or validating as an OAuth token with every required scope is accepted.
///
/// On success it inserts the [`Credential`] into request extensions and, for an
/// OAuth token, the [`AuthorizedToken`] too, so a
/// handler can enforce a finer-grained scope or attribute the request. On
/// refusal it answers 401 (missing or invalid credential) or 403 (valid token,
/// insufficient scope) itself; see [`AuthLayerBuilder::on_reject`] for the
/// response shape. See the [module docs](self) for what it logs.
///
/// # Examples
///
/// ```
/// use axum::{Router, middleware, routing::get};
/// use oauth_resource_server::axum::{AuthLayer, require_auth};
///
/// let auth = AuthLayer::builder().static_token("example-static-key").build().unwrap();
/// let app: Router = Router::new()
///     .route("/api", get(|| async { "protected" }))
///     .route_layer(middleware::from_fn_with_state(auth, require_auth));
/// # let _ = app;
/// ```
pub async fn require_auth(State(auth): State<AuthLayer>, request: Request, next: Next) -> Response {
    match auth.check(request).await {
        Ok(request) => next.run(request).await,
        Err(refusal) => refusal,
    }
}

impl<S> tower_layer::Layer<S> for AuthLayer {
    type Service = AuthService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        AuthService {
            auth: self.clone(),
            inner,
        }
    }
}

/// The service [`AuthLayer`] wraps a route (or router) in, as a
/// `tower::Layer`. Behaves exactly like [`require_auth`].
#[derive(Clone)]
pub struct AuthService<S> {
    auth: AuthLayer,
    inner: S,
}

impl<S: std::fmt::Debug> std::fmt::Debug for AuthService<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AuthService")
            .field("auth", &self.auth)
            .field("inner", &self.inner)
            .finish()
    }
}

impl<S> tower_service::Service<Request> for AuthService<S>
where
    S: tower_service::Service<Request, Response = Response> + Clone + Send + 'static,
    S::Future: Send + 'static,
{
    type Response = Response;
    type Error = S::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Response, S::Error>> + Send + 'static>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, request: Request) -> Self::Future {
        // Call the instance `poll_ready` was driven on and leave a fresh clone in
        // its place (the usual tower pattern for a service moved into a future).
        let clone = self.inner.clone();
        let mut inner = std::mem::replace(&mut self.inner, clone);
        let auth = self.auth.clone();
        Box::pin(async move {
            match auth.check(request).await {
                Ok(request) => inner.call(request).await,
                Err(refusal) => Ok(refusal),
            }
        })
    }
}

/// The RFC 9728 protected-resource metadata routes, to be merged into the app
/// **outside** the auth layer: this document is how a caller with no credential
/// discovers where to get one, so gating it behind that credential makes the
/// OAuth flow unstartable. It contains nothing secret.
///
/// With a validator, `GET` (and `HEAD`) answer with
/// [`OAuthValidator::metadata`] as JSON on:
///
/// - `/.well-known/oauth-protected-resource`, always, and
/// - [`OAuthValidator::metadata_path`] when the resource URL has a path (RFC
///   9728 §3.1: `https://api.example.com/v1` is described at
///   `/.well-known/oauth-protected-resource/v1`, and
///   `https://api.example.com/v1/` at `.../oauth-protected-resource/v1/`).
///
/// Serving the bare path for a resource that HAS a path is a deliberate
/// compatibility deviation: the document there still says
/// `"resource": "https://api.example.com/v1"`, and under RFC 9728 §3.3 a
/// client that derived the bare URL from `https://api.example.com` must
/// discard a document whose `resource` differs. Some MCP clients fall back to
/// the bare path and accept it anyway, and it costs a compliant client nothing
/// (it uses the `resource_metadata` URL every challenge carries, or the
/// path-suffixed form).
///
/// A served path answers any method other than `GET`/`HEAD` with 405. Every
/// other path under the well-known prefix answers 404 for every method. With
/// no validator, a `GET` on the bare path answers 404 too, as does any request
/// under the prefix, rather than an empty document being served: a client that
/// finds metadata will act on it, and metadata pointing at no authorization
/// server is worse than none. The router claims that prefix, so an app with a
/// fallback route still answers 404 there.
///
/// # Examples
///
/// ```no_run
/// use std::sync::Arc;
///
/// use axum::{Router, routing::get};
/// use oauth_resource_server::OAuthValidator;
/// use oauth_resource_server::axum::{AuthLayer, metadata_router};
///
/// fn app(oauth: Arc<OAuthValidator>) -> Router {
///     let auth = AuthLayer::builder().oauth(Arc::clone(&oauth)).build().unwrap();
///     Router::new()
///         .route("/v1/things", get(|| async { "protected" }))
///         .route_layer(auth)
///         // Merged after `route_layer`, so the auth layer does not cover it.
///         .merge(metadata_router(Some(oauth)))
/// }
/// ```
pub fn metadata_router<S>(oauth: Option<Arc<OAuthValidator>>) -> Router<S>
where
    S: Clone + Send + Sync + 'static,
{
    async fn not_found() -> StatusCode {
        StatusCode::NOT_FOUND
    }
    let catch_all = format!("{PROTECTED_RESOURCE_METADATA_PREFIX}/{{*rest}}");

    let Some(validator) = oauth else {
        // `any`, not `get`: an unserved suffix is 404 for every method.
        return Router::new()
            .route(&catch_all, any(not_found))
            .route(PROTECTED_RESOURCE_METADATA_PREFIX, get(not_found));
    };

    let serve = {
        let validator = Arc::clone(&validator);
        move || {
            let validator = Arc::clone(&validator);
            async move { Json(validator.metadata()).into_response() }
        }
    };
    // The resource's own metadata path comes from config, so it is never
    // registered as a route pattern: axum gives `{…}`, `:…` and `*…` segments
    // route meaning and panics at registration on a `:` or `*` segment, which
    // an absolute http(s) resource URL may legally contain. The catch-all under
    // the prefix compares the request path against it literally instead.
    let path: Arc<str> = validator.metadata_path().into();
    let suffix = move |request: Request| {
        let validator = Arc::clone(&validator);
        let path = Arc::clone(&path);
        async move {
            if request.uri().path() != &*path {
                return StatusCode::NOT_FOUND.into_response();
            }
            match *request.method() {
                Method::GET | Method::HEAD => Json(validator.metadata()).into_response(),
                _ => method_not_allowed(),
            }
        }
    };
    Router::new()
        .route(&catch_all, any(suffix))
        .route(PROTECTED_RESOURCE_METADATA_PREFIX, get(serve))
}

/// The 405 an axum `get` route answers any other method with, reproduced for
/// the metadata path the catch-all serves by hand.
fn method_not_allowed() -> Response {
    (
        StatusCode::METHOD_NOT_ALLOWED,
        [(http::header::ALLOW, HeaderValue::from_static("GET,HEAD"))],
    )
        .into_response()
}

#[cfg(test)]
mod scope_tests;

#[cfg(test)]
mod tests {
    use ::axum::Extension;
    use ::axum::middleware;
    use tower::ServiceExt;

    use super::*;
    use crate::AuthorizedToken;
    use crate::testing;

    const STATIC: &str = "secret";

    fn validator(jwks_uri: &str) -> Arc<OAuthValidator> {
        Arc::new(OAuthValidator::new(&testing::resolved_config(jwks_uri)).unwrap())
    }

    fn unreachable_validator() -> Arc<OAuthValidator> {
        validator("http://127.0.0.1:1/jwks")
    }

    fn app(auth: AuthLayer) -> Router {
        Router::new()
            .route("/test", get(|| async { "ok" }))
            .route_layer(middleware::from_fn_with_state(auth, require_auth))
    }

    /// mcp-md-wiki's pre-extraction `AuthState` constructor shape, with the one
    /// option it sets to keep its static-only refusals unchanged
    /// (`static_challenge(None)`).
    fn wiki_app(static_token: Option<&str>, oauth: Option<Arc<OAuthValidator>>) -> Router {
        app(AuthLayer::builder()
            .optional_static_token(static_token.map(str::to_string))
            .optional_oauth(oauth)
            .static_challenge(None)
            .build()
            .unwrap())
    }

    async fn send(app: &Router, headers: &[(&str, &str)]) -> Response {
        let mut req = Request::builder().uri("/test");
        for (name, value) in headers {
            req = req.header(*name, *value);
        }
        app.clone()
            .oneshot(req.body(Body::empty()).unwrap())
            .await
            .unwrap()
    }

    async fn get_with_auth(app: &Router, header: Option<&str>) -> Response {
        match header {
            Some(h) => send(app, &[("authorization", h)]).await,
            None => send(app, &[]).await,
        }
    }

    fn www_authenticate(resp: &Response) -> String {
        resp.headers()
            .get(WWW_AUTHENTICATE)
            .expect("a refusal with OAuth configured must carry WWW-Authenticate")
            .to_str()
            .unwrap()
            .to_string()
    }

    async fn body_bytes(resp: Response) -> Vec<u8> {
        ::axum::body::to_bytes(resp.into_body(), 64 * 1024)
            .await
            .unwrap()
            .to_vec()
    }

    fn unscoped_token() -> String {
        testing::mint(
            testing::KEY_A_PEM,
            testing::KID_A,
            &serde_json::json!({
                "iss": testing::ISSUER, "aud": testing::AUDIENCE,
                "exp": testing::now() + 3600, "scope": "openid profile",
            }),
        )
    }

    fn expired_token() -> String {
        testing::mint(
            testing::KEY_A_PEM,
            testing::KID_A,
            &serde_json::json!({
                "iss": testing::ISSUER, "aud": testing::AUDIENCE,
                "exp": testing::now() - 3600, "scope": "mcp:read",
            }),
        )
    }

    // --- Fail-closed construction ---

    #[test]
    fn the_builder_refuses_to_build_a_pass_through() {
        assert_eq!(
            AuthLayer::builder().build().unwrap_err(),
            AuthLayerError::NoCredential
        );
        assert_eq!(
            AuthLayer::builder().static_token("").build().unwrap_err(),
            AuthLayerError::NoCredential
        );
        // A whitespace-only token could never match: a layer holding only it
        // would lock every route without saying so. It is no credential.
        for blank in ["   ", "\t", " \n "] {
            assert_eq!(
                AuthLayer::builder()
                    .static_token(blank)
                    .build()
                    .unwrap_err(),
                AuthLayerError::NoCredential,
                "{blank:?}"
            );
            assert_eq!(
                AuthLayer::builder()
                    .static_token(blank)
                    .optional()
                    .build()
                    .unwrap_err(),
                AuthLayerError::NoCredential,
                "{blank:?}"
            );
            assert_eq!(
                AuthLayer::builder()
                    .build_with_decision(StaticTokenDecision::StaticOnly(blank.into()))
                    .unwrap_err(),
                AuthLayerError::NoCredential,
                "{blank:?}"
            );
        }
        assert_eq!(
            AuthLayer::builder()
                .optional_static_token(None)
                .optional_oauth(None)
                .build()
                .unwrap_err(),
            AuthLayerError::NoCredential
        );
        assert_eq!(
            AuthLayer::builder()
                .static_token(STATIC)
                .sources([])
                .build()
                .unwrap_err(),
            AuthLayerError::NoSources
        );
        let built = AuthLayer::builder().static_token(STATIC).build().unwrap();
        assert!(!built.allows_unauthenticated());
        assert!(built.oauth().is_none());
    }

    #[tokio::test]
    async fn only_the_explicit_opt_out_passes_requests_through() {
        let layer = AuthLayer::allow_unauthenticated();
        assert!(layer.allows_unauthenticated());
        let app = Router::new()
            .route(
                "/test",
                get(
                    |c: Option<Extension<Credential>>,
                     t: Option<Extension<AuthorizedToken>>,
                     headers: http::HeaderMap| async move {
                        assert!(c.is_none() && t.is_none(), "a pass-through inserts nothing");
                        // It still marks what a client sent anyway.
                        for value in headers.get_all(http::header::AUTHORIZATION) {
                            assert!(value.is_sensitive(), "Authorization must be sensitive");
                        }
                        "ok"
                    },
                ),
            )
            .route_layer(middleware::from_fn_with_state(layer, require_auth));
        assert_eq!(get_with_auth(&app, None).await.status(), StatusCode::OK);
        assert_eq!(
            get_with_auth(&app, Some("Bearer anything")).await.status(),
            StatusCode::OK
        );
    }

    #[test]
    fn debug_never_prints_the_static_token() {
        let layer = AuthLayer::builder()
            .static_token("hunter2")
            .build()
            .unwrap();
        let rendered = format!("{layer:?}");
        assert!(!rendered.contains("hunter2"), "{rendered}");
        let builder = AuthLayer::builder().static_token("hunter2");
        let rendered = format!("{builder:?}");
        assert!(!rendered.contains("hunter2"), "{rendered}");
    }

    // --- Ported from mcp-md-wiki's static-token middleware tests ---

    #[tokio::test]
    async fn static_token_only() {
        let app = wiki_app(Some(STATIC), None);
        for (header, status) in [
            (Some("Bearer secret"), StatusCode::OK),
            (Some("Bearer wrong-token"), StatusCode::UNAUTHORIZED),
            (None, StatusCode::UNAUTHORIZED),
            (Some("Basic c2VjcmV0LXRva2Vu"), StatusCode::UNAUTHORIZED),
        ] {
            let resp = get_with_auth(&app, header).await;
            assert_eq!(resp.status(), status, "{header:?}");
            // Static-only with `static_challenge(None)`: no challenge, ever.
            assert!(resp.headers().get(WWW_AUTHENTICATE).is_none(), "{header:?}");
        }
    }

    #[tokio::test]
    async fn a_static_only_401_carries_a_bearer_challenge_by_default() {
        // RFC 9110 §15.5.2: a 401 MUST carry a challenge.
        let app = app(AuthLayer::builder().static_token(STATIC).build().unwrap());
        for header in [None, Some("Bearer wrong-token"), Some("Basic abc")] {
            let resp = get_with_auth(&app, header).await;
            assert_eq!(resp.status(), StatusCode::UNAUTHORIZED, "{header:?}");
            assert_eq!(
                resp.headers()[WWW_AUTHENTICATE],
                DEFAULT_STATIC_CHALLENGE,
                "{header:?}"
            );
        }
        assert_eq!(
            get_with_auth(&app, Some("Bearer secret")).await.status(),
            StatusCode::OK
        );
        // `from_decision` uses the same default.
        let app = super::tests::app(
            AuthLayer::from_decision(StaticTokenDecision::StaticOnly(STATIC.into()), None).unwrap(),
        );
        assert_eq!(
            get_with_auth(&app, None).await.headers()[WWW_AUTHENTICATE],
            DEFAULT_STATIC_CHALLENGE
        );
        // An application's own challenge replaces it.
        let custom = HeaderValue::from_static("Bearer realm=\"my-api\"");
        let app = super::tests::app(
            AuthLayer::builder()
                .static_token(STATIC)
                .static_challenge(Some(custom.clone()))
                .build()
                .unwrap(),
        );
        assert_eq!(
            get_with_auth(&app, None).await.headers()[WWW_AUTHENTICATE],
            custom
        );
    }

    #[tokio::test]
    async fn the_static_challenge_is_ignored_when_oauth_is_configured() {
        let v = unreachable_validator();
        let layer = AuthLayer::builder()
            .static_token(STATIC)
            .oauth(Arc::clone(&v))
            .static_challenge(Some(HeaderValue::from_static("Bearer realm=\"x\"")))
            .build()
            .unwrap();
        let resp = get_with_auth(&app(layer), None).await;
        assert_eq!(www_authenticate(&resp), v.invalid_token_challenge());
    }

    #[test]
    fn an_oauth_challenge_that_is_not_a_header_value_fails_the_build() {
        // `resolve` refuses such a resource; a hand-edited resolved config is
        // the only way in, and it must not yield 401s without a challenge.
        let mut cfg = testing::resolved_config("http://127.0.0.1:1/jwks");
        cfg.resource = "https://kb.example.test/m\ncp".into();
        let v = Arc::new(OAuthValidator::new(&cfg).unwrap());
        assert_eq!(
            AuthLayer::builder().oauth(v).build().unwrap_err(),
            AuthLayerError::InvalidChallenge
        );
        let mut cfg = testing::resolved_config("http://127.0.0.1:1/jwks");
        cfg.required_scopes = vec!["a\u{1}b".into()];
        let v = Arc::new(OAuthValidator::new(&cfg).unwrap());
        assert_eq!(
            AuthLayer::builder()
                .static_token(STATIC)
                .oauth(v)
                .build()
                .unwrap_err(),
            AuthLayerError::InvalidChallenge
        );
    }

    #[tokio::test]
    async fn static_bearer_token_still_works_with_oauth_enabled() {
        // The JWKS endpoint is unreachable on purpose: a static-token request
        // must never reach the OAuth validator, let alone depend on the IdP.
        let app = wiki_app(Some(STATIC), Some(unreachable_validator()));
        assert_eq!(
            get_with_auth(&app, Some("Bearer secret")).await.status(),
            StatusCode::OK
        );
    }

    #[tokio::test]
    async fn an_oauth_token_is_accepted_alongside_the_static_token() {
        let jwks = testing::spawn_jwks_server("200 OK", testing::jwks_body()).await;
        let app = wiki_app(Some(STATIC), Some(validator(&jwks.url)));
        let header = format!("Bearer {}", testing::valid_token());
        assert_eq!(
            get_with_auth(&app, Some(&header)).await.status(),
            StatusCode::OK
        );
        assert_eq!(
            get_with_auth(&app, Some("Bearer secret")).await.status(),
            StatusCode::OK
        );
    }

    #[tokio::test]
    async fn a_missing_credential_gets_401_with_a_well_formed_challenge() {
        let jwks = testing::spawn_jwks_server("200 OK", testing::jwks_body()).await;
        let app = wiki_app(Some(STATIC), Some(validator(&jwks.url)));
        // No header, a wrong STATIC token, and a non-bearer scheme: all carry
        // the challenge — the server cannot tell which credential the caller
        // meant to present.
        for header in [None, Some("Bearer not-the-secret"), Some("Basic abc")] {
            let resp = get_with_auth(&app, header).await;
            assert_eq!(
                resp.status(),
                StatusCode::UNAUTHORIZED,
                "header: {header:?}"
            );
            assert_eq!(
                www_authenticate(&resp),
                "Bearer error=\"invalid_token\", \
                 resource_metadata=\"https://kb.example.test\
                 /.well-known/oauth-protected-resource/mcp\", \
                 scope=\"mcp:read mcp:write\""
            );
        }
    }

    #[tokio::test]
    async fn an_invalid_token_gets_401_and_an_insufficient_scope_token_gets_403() {
        let jwks = testing::spawn_jwks_server("200 OK", testing::jwks_body()).await;
        let app = wiki_app(None, Some(validator(&jwks.url)));

        let resp = get_with_auth(&app, Some(&format!("Bearer {}", expired_token()))).await;
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        assert!(www_authenticate(&resp).contains("error=\"invalid_token\""));

        let resp = get_with_auth(&app, Some(&format!("Bearer {}", unscoped_token()))).await;
        assert_eq!(
            resp.status(),
            StatusCode::FORBIDDEN,
            "a valid token missing the scope is 403, not 401"
        );
        assert_eq!(
            www_authenticate(&resp),
            "Bearer error=\"insufficient_scope\", scope=\"mcp:read\", \
             resource_metadata=\"https://kb.example.test\
             /.well-known/oauth-protected-resource/mcp\""
        );
    }

    #[tokio::test]
    async fn an_authelia_style_scp_token_is_accepted_through_the_middleware() {
        let jwks = testing::spawn_jwks_server("200 OK", testing::jwks_body()).await;
        let app = wiki_app(None, Some(validator(&jwks.url)));
        let token = testing::mint_with(
            crate::Algorithm::RS256,
            Some(testing::KID_A),
            Some("at+jwt"),
            &serde_json::json!({
                "iss": testing::ISSUER, "aud": [testing::AUDIENCE],
                "exp": testing::now() + 3600, "nbf": testing::now(),
                "sub": "44726d41-0000-4000-8000-000000000000",
                "scp": ["mcp:read", "mcp:write"],
            }),
        );
        let resp = get_with_auth(&app, Some(&format!("Bearer {token}"))).await;
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn the_bearer_scheme_is_case_insensitive_for_both_credentials() {
        let jwks = testing::spawn_jwks_server("200 OK", testing::jwks_body()).await;
        let app = wiki_app(Some(STATIC), Some(validator(&jwks.url)));
        for header in [
            "bearer secret".to_string(),
            "BEARER secret".to_string(),
            "Bearer   secret  ".to_string(),
            format!("bearer {}", testing::valid_token()),
        ] {
            assert_eq!(
                get_with_auth(&app, Some(&header)).await.status(),
                StatusCode::OK,
                "{header:.20}"
            );
        }
        for header in ["Basic secret", "Bearersecret", "secret", "Bearer\tsecret"] {
            assert_eq!(
                get_with_auth(&app, Some(header)).await.status(),
                StatusCode::UNAUTHORIZED,
                "{header}"
            );
        }
    }

    #[test]
    fn bearer_credential_parsing() {
        assert_eq!(bearer_credential("Bearer abc"), "abc");
        assert_eq!(bearer_credential("bEaReR  abc "), "abc");
        assert_eq!(bearer_credential("Bearer "), "");
        assert_eq!(bearer_credential("Bearer"), "");
        assert_eq!(bearer_credential("Basic abc"), "");
        assert_eq!(bearer_credential(""), "");
    }

    // --- Byte-identical default responses ---

    /// mcp-md-wiki's pre-extraction `AuthState`, `challenge`, `auth_rejection`,
    /// `bearer_auth` and `bearer_credential`, verbatim but for the log lines: the
    /// oracle the crate's default behaviour must match byte for byte, run
    /// through the same axum plumbing (which is what adds `content-length`).
    mod wiki {
        use subtle::ConstantTimeEq;

        use super::super::*;

        #[derive(Clone)]
        pub(super) struct AuthState {
            pub(super) bearer_token: Option<String>,
            pub(super) oauth: Option<Arc<OAuthValidator>>,
        }

        impl AuthState {
            fn challenge(&self, rejection: &TokenRejection) -> Option<String> {
                let oauth = self.oauth.as_ref()?;
                Some(match rejection {
                    TokenRejection::InsufficientScope => oauth.insufficient_scope_challenge(),
                    TokenRejection::Invalid(_) | TokenRejection::Missing => {
                        oauth.invalid_token_challenge()
                    }
                })
            }
        }

        fn auth_rejection(auth: &AuthState, rejection: TokenRejection) -> Response {
            let status = match rejection {
                TokenRejection::InsufficientScope => StatusCode::FORBIDDEN,
                TokenRejection::Invalid(_) | TokenRejection::Missing => StatusCode::UNAUTHORIZED,
            };
            let mut response = Response::builder().status(status);
            if let Some(challenge) = auth.challenge(&rejection)
                && let Ok(value) = HeaderValue::from_str(&challenge)
            {
                response = response.header(WWW_AUTHENTICATE, value);
            }
            response
                .body(Body::empty())
                .expect("a status-and-header-only response is always constructible")
        }

        pub(super) async fn bearer_auth(
            State(auth): State<AuthState>,
            headers: HeaderMap,
            request: Request,
            next: Next,
        ) -> Response {
            if auth.bearer_token.is_none() && auth.oauth.is_none() {
                return next.run(request).await;
            }
            let auth_header = headers
                .get("authorization")
                .and_then(|v| v.to_str().ok())
                .unwrap_or("");
            let token = bearer_credential(auth_header);
            if let Some(ref expected_token) = auth.bearer_token
                && !token.is_empty()
                && token.as_bytes().ct_eq(expected_token.as_bytes()).into()
            {
                return next.run(request).await;
            }
            let Some(ref oauth) = auth.oauth else {
                return auth_rejection(
                    &auth,
                    TokenRejection::Invalid("static token mismatch".into()),
                );
            };
            match oauth.validate(token).await {
                Ok(claims) => {
                    let mut request = request;
                    request.extensions_mut().insert(claims);
                    next.run(request).await
                }
                Err(TokenRejection::Missing) => auth_rejection(&auth, TokenRejection::Missing),
                Err(rejection) => auth_rejection(&auth, rejection),
            }
        }

        fn bearer_credential(header: &str) -> &str {
            match header.split_once(' ') {
                Some((scheme, token)) if scheme.eq_ignore_ascii_case("bearer") => token.trim(),
                _ => "",
            }
        }
    }

    fn wiki_oracle_app(static_token: Option<&str>, oauth: Option<Arc<OAuthValidator>>) -> Router {
        let auth_state = wiki::AuthState {
            bearer_token: static_token.map(str::to_string),
            oauth,
        };
        Router::new()
            .route("/test", get(|| async { "ok" }))
            .route_layer(middleware::from_fn_with_state(
                auth_state,
                wiki::bearer_auth,
            ))
    }

    async fn assert_same_response(actual: Response, expected: Response, what: &str) {
        assert_eq!(actual.status(), expected.status(), "{what}");
        assert_eq!(actual.version(), expected.version(), "{what}");
        assert_eq!(actual.headers(), expected.headers(), "{what}");
        assert_eq!(
            body_bytes(actual).await,
            body_bytes(expected).await,
            "{what}"
        );
    }

    #[tokio::test]
    async fn default_responses_are_byte_identical_to_the_wiki_middleware() {
        let jwks = testing::spawn_jwks_server("200 OK", testing::jwks_body()).await;
        let v = validator(&jwks.url);
        let valid = format!("Bearer {}", testing::valid_token());
        let lower = format!("bearer {}", testing::valid_token());
        let expired = format!("Bearer {}", expired_token());
        let unscoped = format!("Bearer {}", unscoped_token());
        let headers: Vec<Option<&str>> = vec![
            None,
            Some(""),
            Some("Bearer"),
            Some("Bearer "),
            Some("Bearer secret"),
            Some("bearer secret"),
            Some("Bearer  secret "),
            Some("Bearer wrong"),
            Some("Bearersecret"),
            Some("Bearer\tsecret"),
            Some("Basic c2VjcmV0"),
            Some("secret"),
            Some(&valid),
            Some(&lower),
            Some(&expired),
            Some(&unscoped),
        ];

        // Static-only (no challenge on any refusal), dual mode, OAuth-only.
        for (static_token, oauth) in [
            (Some(STATIC), None),
            (Some(STATIC), Some(Arc::clone(&v))),
            (None, Some(Arc::clone(&v))),
        ] {
            let ours = wiki_app(static_token, oauth.clone());
            let theirs = wiki_oracle_app(static_token, oauth.clone());
            for header in &headers {
                assert_same_response(
                    get_with_auth(&ours, *header).await,
                    get_with_auth(&theirs, *header).await,
                    &format!(
                        "static={static_token:?} oauth={} header={header:.30?}",
                        oauth.is_some()
                    ),
                )
                .await;
            }
        }
    }

    // --- on_reject ---

    #[tokio::test]
    async fn on_reject_shapes_the_body_but_not_the_status_or_challenge() {
        let jwks = testing::spawn_jwks_server("200 OK", testing::jwks_body()).await;
        let v = validator(&jwks.url);
        let layer = AuthLayer::builder()
            .static_token(STATIC)
            .oauth(Arc::clone(&v))
            .on_reject(|cx: RejectContext<'_>| {
                assert_eq!(cx.request.uri.path(), "/test");
                let status = cx.status;
                let body = match cx.rejection {
                    TokenRejection::InsufficientScope => r#"{"error":"insufficient_scope"}"#,
                    _ => r#"{"error":"unauthorized"}"#,
                };
                Response::builder()
                    // A callback that gets the status wrong, and tries to
                    // replace the challenge, is corrected on both counts.
                    .status(StatusCode::OK)
                    .header("content-type", "application/json")
                    .header("x-seen-status", status.as_str())
                    .header(WWW_AUTHENTICATE, "Basic realm=\"nope\"")
                    .header(WWW_AUTHENTICATE, "Bearer realm=\"also-nope\"")
                    .body(Body::from(body))
                    .unwrap()
            })
            .build()
            .unwrap();
        let app = app(layer);

        let resp = get_with_auth(&app, None).await;
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(resp.headers()["x-seen-status"], "401");
        assert_eq!(resp.headers()["content-type"], "application/json");
        assert_eq!(
            resp.headers().get_all(WWW_AUTHENTICATE).iter().count(),
            1,
            "the callback's challenges are replaced, not added to"
        );
        assert_eq!(www_authenticate(&resp), v.invalid_token_challenge());
        assert_eq!(body_bytes(resp).await, br#"{"error":"unauthorized"}"#);

        let resp = get_with_auth(&app, Some(&format!("Bearer {}", unscoped_token()))).await;
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
        assert_eq!(resp.headers()["x-seen-status"], "403");
        assert_eq!(www_authenticate(&resp), v.insufficient_scope_challenge());
        assert_eq!(body_bytes(resp).await, br#"{"error":"insufficient_scope"}"#);
    }

    #[tokio::test]
    async fn on_reject_without_oauth_or_a_static_challenge_keeps_its_own_headers() {
        let builder = || {
            AuthLayer::builder()
                .static_token(STATIC)
                .on_reject(|cx: RejectContext<'_>| {
                    Response::builder()
                        .status(cx.status)
                        .header(WWW_AUTHENTICATE, "ApiKey")
                        .body(Body::from("nope"))
                        .unwrap()
                })
        };
        let layer = builder().static_challenge(None).build().unwrap();
        let resp = get_with_auth(&app(layer), Some("Bearer wrong")).await;
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(resp.headers()[WWW_AUTHENTICATE], "ApiKey");
        assert_eq!(body_bytes(resp).await, b"nope");

        // With the default static challenge, the layer's challenge wins, as
        // it does with OAuth.
        let resp = get_with_auth(&app(builder().build().unwrap()), Some("Bearer wrong")).await;
        assert_eq!(resp.headers().get_all(WWW_AUTHENTICATE).iter().count(), 1);
        assert_eq!(resp.headers()[WWW_AUTHENTICATE], DEFAULT_STATIC_CHALLENGE);
        assert_eq!(body_bytes(resp).await, b"nope");
    }

    #[tokio::test]
    async fn the_presented_credential_never_reaches_a_debug_rendering() {
        let jwks = testing::spawn_jwks_server("200 OK", testing::jwks_body()).await;
        let v = validator(&jwks.url);
        let token = unscoped_token(); // valid and signed: a 403, not a 401
        let seen: Arc<std::sync::Mutex<Vec<String>>> = Arc::default();
        let log = Arc::clone(&seen);
        let layer = AuthLayer::builder()
            .oauth(v)
            .sources([
                CredentialSource::authorization_bearer(),
                CredentialSource::Raw(HeaderName::from_static("x-api-key")),
            ])
            .on_reject(move |cx: RejectContext<'_>| {
                log.lock().unwrap().push(format!("{cx:?}"));
                log.lock().unwrap().push(format!("{:?}", cx.request));
                Response::new(Body::empty())
            })
            .build()
            .unwrap();
        let bearer = format!("Bearer {token}");
        let resp = send(
            &app(layer),
            &[
                ("authorization", bearer.as_str()),
                ("x-api-key", "raw-api-key-value"),
                ("accept", "application/json"),
            ],
        )
        .await;
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
        let seen = seen.lock().unwrap();
        assert_eq!(seen.len(), 2);
        for rendered in seen.iter() {
            assert!(!rendered.contains(&token), "{rendered}");
            assert!(!rendered.contains("raw-api-key-value"), "{rendered}");
        }
        // The context still says what happened.
        assert!(seen[0].contains("InsufficientScope"), "{}", seen[0]);
        assert!(seen[0].contains("403"), "{}", seen[0]);
        assert!(seen[0].contains("authorization"), "{}", seen[0]);
        assert!(!seen[0].contains("application/json"), "{}", seen[0]);
    }

    #[tokio::test]
    async fn the_inner_service_sees_the_credential_headers_marked_sensitive() {
        let layer = AuthLayer::builder().static_token(STATIC).build().unwrap();
        let app = Router::new()
            .route(
                "/test",
                get(|headers: HeaderMap| async move {
                    assert!(headers["authorization"].is_sensitive());
                    assert!(!format!("{headers:?}").contains(STATIC));
                    assert!(!headers["accept"].is_sensitive());
                    "ok"
                }),
            )
            .route_layer(layer);
        let resp = send(
            &app,
            &[("authorization", "Bearer secret"), ("accept", "text/plain")],
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
    }

    // --- Multiple sources: a second credential header beside Authorization ---

    fn multi_source_app(v: Arc<OAuthValidator>) -> Router {
        app(AuthLayer::builder()
            .static_token(STATIC)
            .oauth(v)
            .sources([
                CredentialSource::authorization_bearer(),
                CredentialSource::Raw(HeaderName::from_static("x-api-key")),
            ])
            .build()
            .unwrap())
    }

    #[tokio::test]
    async fn a_bad_authorization_header_does_not_mask_a_good_raw_header() {
        let jwks = testing::spawn_jwks_server("200 OK", testing::jwks_body()).await;
        let app = multi_source_app(validator(&jwks.url));
        let foreign = format!("Bearer {}", expired_token());
        for authorization in [foreign.as_str(), "Bearer garbage", "Basic abc"] {
            let resp = send(
                &app,
                &[("authorization", authorization), ("x-api-key", STATIC)],
            )
            .await;
            assert_eq!(resp.status(), StatusCode::OK, "{authorization:.30}");
        }
    }

    #[tokio::test]
    async fn a_bad_raw_header_does_not_mask_a_good_authorization_header() {
        let jwks = testing::spawn_jwks_server("200 OK", testing::jwks_body()).await;
        let app = multi_source_app(validator(&jwks.url));
        let valid = format!("Bearer {}", testing::valid_token());
        for authorization in ["Bearer secret", valid.as_str()] {
            let resp = send(
                &app,
                &[("authorization", authorization), ("x-api-key", "garbage")],
            )
            .await;
            assert_eq!(resp.status(), StatusCode::OK, "{authorization:.30}");
        }
        // An OAuth token in the raw header works too.
        let resp = send(&app, &[("x-api-key", &testing::valid_token())]).await;
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn multi_source_refusals() {
        let jwks = testing::spawn_jwks_server("200 OK", testing::jwks_body()).await;
        let v = validator(&jwks.url);
        let app = multi_source_app(Arc::clone(&v));

        let resp = send(
            &app,
            &[
                ("authorization", "Bearer garbage"),
                ("x-api-key", "also-garbage"),
            ],
        )
        .await;
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(www_authenticate(&resp), v.invalid_token_challenge());

        // A scope-lacking valid token in either place outranks garbage elsewhere.
        let unscoped = unscoped_token();
        let resp = send(
            &app,
            &[
                ("authorization", "Bearer garbage"),
                ("x-api-key", &unscoped),
            ],
        )
        .await;
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
        assert_eq!(www_authenticate(&resp), v.insufficient_scope_challenge());

        // The raw header is taken verbatim: a `Bearer ` prefix there is part of
        // the value, not a scheme.
        let resp = send(&app, &[("x-api-key", "Bearer secret")]).await;
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);

        let resp = send(&app, &[]).await;
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn a_raw_only_layer_ignores_the_authorization_header() {
        let layer = AuthLayer::builder()
            .static_token(STATIC)
            .sources([CredentialSource::Raw(HeaderName::from_static("x-api-key"))])
            .build()
            .unwrap();
        let app = app(layer);
        assert_eq!(
            send(&app, &[("authorization", "Bearer secret")])
                .await
                .status(),
            StatusCode::UNAUTHORIZED
        );
        assert_eq!(
            send(&app, &[("x-api-key", STATIC)]).await.status(),
            StatusCode::OK
        );
    }

    // --- Extensions ---

    #[tokio::test]
    async fn the_credential_and_oauth_token_are_inserted_into_extensions() {
        let jwks = testing::spawn_jwks_server("200 OK", testing::jwks_body()).await;
        let layer = AuthLayer::builder()
            .static_token(STATIC)
            .oauth(validator(&jwks.url))
            .build()
            .unwrap();
        let app = Router::new()
            .route(
                "/test",
                get(
                    |Extension(credential): Extension<Credential>,
                     token: Option<Extension<AuthorizedToken>>| async move {
                        match (credential, token) {
                            (Credential::StaticToken, None) => "static".to_string(),
                            (Credential::OAuth(c), Some(Extension(t))) => {
                                assert_eq!(c, t);
                                format!(
                                    "oauth {} {}",
                                    t.subject.as_deref().unwrap_or_default(),
                                    t.has_scope("mcp:write")
                                )
                            }
                            other => panic!("inconsistent extensions: {other:?}"),
                        }
                    },
                ),
            )
            .route_layer(middleware::from_fn_with_state(layer, require_auth));

        let resp = get_with_auth(&app, Some("Bearer secret")).await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(body_bytes(resp).await, b"static");

        let header = format!("Bearer {}", testing::valid_token());
        let resp = get_with_auth(&app, Some(&header)).await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(body_bytes(resp).await, b"oauth user-1 true");
    }

    // --- tower::Layer ---

    /// `.route_layer(auth)` / `.layer(auth)` and `from_fn_with_state(auth,
    /// require_auth)` are one implementation: same statuses, challenges, bodies
    /// and extensions.
    #[tokio::test]
    async fn the_layer_behaves_exactly_like_the_middleware_function() {
        let jwks = testing::spawn_jwks_server("200 OK", testing::jwks_body()).await;
        let layer = AuthLayer::builder()
            .static_token(STATIC)
            .oauth(validator(&jwks.url))
            .on_reject(|cx: RejectContext<'_>| Response::new(Body::from(cx.status.to_string())))
            .build()
            .unwrap();
        let handler = get(|c: Option<Extension<Credential>>| async move {
            match c {
                Some(Extension(Credential::StaticToken)) => "static",
                Some(Extension(Credential::OAuth(_))) => "oauth",
                None => "none",
            }
        });
        let via_fn = Router::new()
            .route("/test", handler.clone())
            .route_layer(middleware::from_fn_with_state(layer.clone(), require_auth));
        let via_route_layer = Router::new()
            .route("/test", handler.clone())
            .route_layer(layer.clone());
        let via_layer = Router::new().route("/test", handler).layer(layer);

        let valid = format!("Bearer {}", testing::valid_token());
        let unscoped = format!("Bearer {}", unscoped_token());
        for header in [
            None,
            Some("Bearer secret"),
            Some("Bearer wrong"),
            Some(valid.as_str()),
            Some(unscoped.as_str()),
        ] {
            let expected = get_with_auth(&via_fn, header).await;
            let (status, challenge) = (
                expected.status(),
                expected.headers().get(WWW_AUTHENTICATE).cloned(),
            );
            let expected_body = body_bytes(expected).await;
            for app in [&via_route_layer, &via_layer] {
                let resp = get_with_auth(app, header).await;
                assert_eq!(resp.status(), status, "{header:?}");
                assert_eq!(
                    resp.headers().get(WWW_AUTHENTICATE),
                    challenge.as_ref(),
                    "{header:?}"
                );
                assert_eq!(body_bytes(resp).await, expected_body, "{header:?}");
            }
        }
    }

    // --- from_decision ---

    #[tokio::test]
    async fn from_decision_maps_every_decision_and_refuses_a_mismatch() {
        use StaticTokenDecision::*;

        let jwks = testing::spawn_jwks_server("200 OK", testing::jwks_body()).await;
        let v = validator(&jwks.url);
        let valid = format!("Bearer {}", testing::valid_token());
        let status = |layer: AuthLayer, header: &'static str| async move {
            get_with_auth(&app(layer), Some(header)).await.status()
        };
        let valid: &'static str = Box::leak(valid.into_boxed_str());

        // The explicit opt-out.
        let open = AuthLayer::from_decision(Unauthenticated, None).unwrap();
        assert!(open.allows_unauthenticated());

        // Static only.
        let layer = AuthLayer::from_decision(StaticOnly(STATIC.into()), None).unwrap();
        assert!(!layer.allows_unauthenticated());
        assert_eq!(status(layer.clone(), "Bearer secret").await, StatusCode::OK);
        assert_eq!(status(layer, valid).await, StatusCode::UNAUTHORIZED);

        // Dual mode.
        let layer =
            AuthLayer::from_decision(StaticAndOAuth(STATIC.into()), Some(Arc::clone(&v))).unwrap();
        assert_eq!(status(layer.clone(), "Bearer secret").await, StatusCode::OK);
        assert_eq!(status(layer, valid).await, StatusCode::OK);

        // OAuth only, and a static token dropped by `accept_static_bearer: false`.
        for decision in [OAuthOnly, StaticIgnored] {
            let layer = AuthLayer::from_decision(decision, Some(Arc::clone(&v))).unwrap();
            assert_eq!(
                status(layer.clone(), "Bearer secret").await,
                StatusCode::UNAUTHORIZED
            );
            assert_eq!(status(layer, valid).await, StatusCode::OK);
        }

        // The decision and the validator must agree.
        for decision in [StaticAndOAuth(STATIC.into()), OAuthOnly, StaticIgnored] {
            assert_eq!(
                AuthLayer::from_decision(decision, None).unwrap_err(),
                AuthLayerError::DecisionNeedsOAuth
            );
        }
        for decision in [StaticOnly(STATIC.into()), Unauthenticated] {
            assert_eq!(
                AuthLayer::from_decision(decision, Some(Arc::clone(&v))).unwrap_err(),
                AuthLayerError::DecisionWithoutOAuth
            );
        }
    }

    #[tokio::test]
    async fn build_with_decision_keeps_the_builders_sources_and_replaces_its_token() {
        let layer = AuthLayer::builder()
            .static_token("builder-token")
            .sources([CredentialSource::Raw(HeaderName::from_static("x-api-key"))])
            .build_with_decision(StaticTokenDecision::StaticOnly(STATIC.into()))
            .unwrap();
        let app = app(layer);
        assert_eq!(
            send(&app, &[("x-api-key", STATIC)]).await.status(),
            StatusCode::OK
        );
        assert_eq!(
            send(&app, &[("x-api-key", "builder-token")]).await.status(),
            StatusCode::UNAUTHORIZED
        );
        assert_eq!(
            send(&app, &[("authorization", "Bearer secret")])
                .await
                .status(),
            StatusCode::UNAUTHORIZED
        );
    }

    // --- Metadata routes ---

    async fn get_path(app: &Router, path: &str) -> Response {
        app.clone()
            .oneshot(Request::builder().uri(path).body(Body::empty()).unwrap())
            .await
            .unwrap()
    }

    const MCP_METADATA_PATH: &str = "/.well-known/oauth-protected-resource/mcp";

    #[tokio::test]
    async fn metadata_routes_for_a_resource_with_a_path() {
        let v = unreachable_validator();
        assert_eq!(v.metadata_path(), MCP_METADATA_PATH);
        let app: Router = metadata_router(Some(Arc::clone(&v)));
        for path in [MCP_METADATA_PATH, PROTECTED_RESOURCE_METADATA_PREFIX] {
            let resp = get_path(&app, path).await;
            assert_eq!(resp.status(), StatusCode::OK, "{path}");
            assert_eq!(resp.headers()["content-type"], "application/json", "{path}");
            let body = body_bytes(resp).await;
            // Byte-identical to what `Json(v.metadata())` serialized before.
            assert_eq!(body, serde_json::to_vec(&v.metadata()).unwrap(), "{path}");
            let doc: serde_json::Value = serde_json::from_slice(&body).unwrap();
            assert_eq!(doc["resource"], testing::RESOURCE);
            assert_eq!(doc["authorization_servers"][0], testing::ISSUER);
            assert_eq!(
                doc["scopes_supported"],
                serde_json::json!(["mcp:read", "mcp:write"])
            );
            assert_eq!(
                doc["bearer_methods_supported"],
                serde_json::json!(["header"])
            );
        }
        for path in [
            "/.well-known/oauth-protected-resource/other",
            "/.well-known/oauth-protected-resource/mcp/deeper",
        ] {
            assert_eq!(
                get_path(&app, path).await.status(),
                StatusCode::NOT_FOUND,
                "{path}"
            );
        }
    }

    async fn post_path(app: &Router, path: &str) -> Response {
        app.clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri(path)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap()
    }

    #[tokio::test]
    async fn metadata_routes_answer_other_methods_by_whether_the_path_is_served() {
        // A served path is GET-only (405 for anything else); an unserved suffix
        // is 404 for every method, as it would be with no route at all.
        let app: Router = metadata_router(Some(unreachable_validator()));
        for path in [MCP_METADATA_PATH, PROTECTED_RESOURCE_METADATA_PREFIX] {
            assert_eq!(
                post_path(&app, path).await.status(),
                StatusCode::METHOD_NOT_ALLOWED,
                "{path}"
            );
        }
        for path in [
            "/.well-known/oauth-protected-resource/other",
            "/.well-known/oauth-protected-resource/mcp/deeper",
        ] {
            let resp = post_path(&app, path).await;
            assert_eq!(resp.status(), StatusCode::NOT_FOUND, "{path}");
            assert!(!resp.headers().contains_key("allow"), "{path}");
        }
        let app: Router = metadata_router(None);
        assert_eq!(
            post_path(&app, MCP_METADATA_PATH).await.status(),
            StatusCode::NOT_FOUND
        );
    }

    #[tokio::test]
    async fn metadata_routes_for_a_root_resource() {
        let mut cfg = testing::resolved_config("http://127.0.0.1:1/jwks");
        cfg.resource = "https://api.example.test/".to_string();
        let v = Arc::new(OAuthValidator::new(&cfg).unwrap());
        assert_eq!(v.metadata_path(), PROTECTED_RESOURCE_METADATA_PREFIX);
        let app: Router = metadata_router(Some(v));
        let resp = get_path(&app, PROTECTED_RESOURCE_METADATA_PREFIX).await;
        assert_eq!(resp.status(), StatusCode::OK);
        let doc: serde_json::Value = serde_json::from_slice(&body_bytes(resp).await).unwrap();
        assert_eq!(doc["resource"], "https://api.example.test/");
        assert_eq!(
            get_path(&app, MCP_METADATA_PATH).await.status(),
            StatusCode::NOT_FOUND
        );
    }

    #[tokio::test]
    async fn metadata_routes_with_a_nested_and_a_brace_bearing_path() {
        for (resource, path) in [
            (
                "https://api.example.test/v1/things",
                "/.well-known/oauth-protected-resource/v1/things",
            ),
            // RFC 9728 §3.1: a path's own trailing slash is kept.
            (
                "https://api.example.test/v1/",
                "/.well-known/oauth-protected-resource/v1/",
            ),
            (
                "https://api.example.test/a{b}",
                "/.well-known/oauth-protected-resource/a{b}",
            ),
        ] {
            let mut cfg = testing::resolved_config("http://127.0.0.1:1/jwks");
            cfg.resource = resource.to_string();
            let v = Arc::new(OAuthValidator::new(&cfg).unwrap());
            assert_eq!(v.metadata_path(), path);
            let app: Router = metadata_router(Some(v));
            let resp = get_path(&app, path).await;
            assert_eq!(resp.status(), StatusCode::OK, "{resource}");
        }
    }

    /// A resource path whose segments axum would read as route syntax — `:x`
    /// and `*x` panic at registration if used as a route pattern — is accepted
    /// by `resolve`, so the router must serve it without ever registering it.
    #[tokio::test]
    async fn metadata_routes_for_a_path_axum_would_read_as_route_syntax() {
        for (resource, path) in [
            (
                "https://api.example.test/a/:id",
                "/.well-known/oauth-protected-resource/a/:id",
            ),
            (
                "https://api.example.test/a/*x",
                "/.well-known/oauth-protected-resource/a/*x",
            ),
            (
                "https://api.example.test/:id",
                "/.well-known/oauth-protected-resource/:id",
            ),
            (
                "https://api.example.test/*",
                "/.well-known/oauth-protected-resource/*",
            ),
            (
                "https://api.example.test/{x}",
                "/.well-known/oauth-protected-resource/{x}",
            ),
            (
                "https://api.example.test/%7Bx%7D",
                "/.well-known/oauth-protected-resource/%7Bx%7D",
            ),
            (
                "https://api.example.test//mcp",
                "/.well-known/oauth-protected-resource//mcp",
            ),
        ] {
            let resolved = crate::OAuthConfig {
                enabled: true,
                issuer: testing::ISSUER.to_string(),
                jwks_uri: Some("http://127.0.0.1:1/jwks".to_string()),
                audience: testing::AUDIENCE.to_string(),
                resource: resource.to_string(),
                required_scope: Some("mcp:read".to_string()),
                ..crate::OAuthConfig::default()
            }
            .resolve(crate::KeyNaming::Dotted("oauth"))
            .unwrap_or_else(|e| panic!("{resource}: {e}"))
            .expect("enabled");
            let v = Arc::new(OAuthValidator::new(&resolved).unwrap());
            assert_eq!(v.metadata_path(), path, "{resource}");
            let app: Router = metadata_router(Some(Arc::clone(&v)));
            for served in [path, PROTECTED_RESOURCE_METADATA_PREFIX] {
                let resp = get_path(&app, served).await;
                assert_eq!(resp.status(), StatusCode::OK, "{resource} {served}");
                assert_eq!(
                    body_bytes(resp).await,
                    serde_json::to_vec(&v.metadata()).unwrap(),
                    "{resource} {served}"
                );
            }
            // Route syntax in the configured path matches only itself.
            for other in [
                "/.well-known/oauth-protected-resource/a/other",
                "/.well-known/oauth-protected-resource/a/:id/x",
                "/.well-known/oauth-protected-resource/other",
                "/.well-known/oauth-protected-resource/mcp",
            ] {
                assert_eq!(
                    get_path(&app, other).await.status(),
                    StatusCode::NOT_FOUND,
                    "{resource} {other}"
                );
            }
        }
    }

    /// The catch-all serves the resource's path by hand, so it must answer
    /// exactly as the axum `get` route serving the bare prefix does: same 405
    /// and `Allow` for another method, same headers and an empty body for HEAD.
    #[tokio::test]
    async fn metadata_path_answers_methods_exactly_like_the_bare_prefix_route() {
        let app: Router = metadata_router(Some(unreachable_validator()));
        let send = |method: &'static str, path: &'static str| {
            app.clone().oneshot(
                Request::builder()
                    .method(method)
                    .uri(path)
                    .body(Body::empty())
                    .unwrap(),
            )
        };
        for method in ["GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"] {
            let bare = send(method, PROTECTED_RESOURCE_METADATA_PREFIX)
                .await
                .unwrap();
            let suffixed = send(method, MCP_METADATA_PATH).await.unwrap();
            assert_eq!(bare.status(), suffixed.status(), "{method}");
            assert_eq!(bare.headers(), suffixed.headers(), "{method}");
            let (bare, suffixed) = (body_bytes(bare).await, body_bytes(suffixed).await);
            assert_eq!(bare, suffixed, "{method}");
            if method == "HEAD" {
                assert!(suffixed.is_empty());
            }
        }
    }

    #[tokio::test]
    async fn metadata_routes_404_when_oauth_is_not_configured() {
        // A catch-all fallback in the app must not answer for them either.
        let app: Router = metadata_router(None).fallback(|| async { "spa shell" });
        for path in [MCP_METADATA_PATH, PROTECTED_RESOURCE_METADATA_PREFIX] {
            let resp = get_path(&app, path).await;
            assert_eq!(resp.status(), StatusCode::NOT_FOUND, "{path}");
            assert!(body_bytes(resp).await.is_empty(), "{path}");
        }
    }

    #[tokio::test]
    async fn metadata_routes_are_reachable_outside_the_auth_layer() {
        let v = unreachable_validator();
        let layer = AuthLayer::builder().oauth(Arc::clone(&v)).build().unwrap();
        let app = Router::new()
            .route("/mcp", get(|| async { "ok" }))
            .route_layer(middleware::from_fn_with_state(layer, require_auth))
            .merge(metadata_router(Some(v)));
        assert_eq!(
            get_path(&app, "/mcp").await.status(),
            StatusCode::UNAUTHORIZED
        );
        for path in [MCP_METADATA_PATH, PROTECTED_RESOURCE_METADATA_PREFIX] {
            assert_eq!(
                get_path(&app, path).await.status(),
                StatusCode::OK,
                "{path}"
            );
        }
    }

    #[tokio::test]
    async fn metadata_router_works_with_app_state() {
        #[derive(Clone)]
        struct AppState;
        let app: Router = Router::new()
            .route("/x", get(|State(_): State<AppState>| async { "x" }))
            .merge(metadata_router(Some(unreachable_validator())))
            .with_state(AppState);
        assert_eq!(
            get_path(&app, MCP_METADATA_PATH).await.status(),
            StatusCode::OK
        );
    }

    // --- Extractors and optional authentication ---

    /// Everything about a response a caller can observe, for byte-for-byte
    /// comparisons: status, every header (in order), body.
    async fn observed(resp: Response) -> (StatusCode, Vec<(String, Vec<u8>)>, Vec<u8>) {
        let status = resp.status();
        let headers = resp
            .headers()
            .iter()
            .map(|(k, v)| (k.to_string(), v.as_bytes().to_vec()))
            .collect();
        (status, headers, body_bytes(resp).await)
    }

    fn json_reject(cx: RejectContext<'_>) -> Response {
        Response::new(Body::from(format!("refused {}", cx.status.as_u16())))
    }

    /// A router whose one handler reads `Option<Credential>` and
    /// `Option<AuthorizedToken>` through the extractors, counting its runs.
    fn optional_extractor_app(
        layer: AuthLayer,
        runs: Arc<std::sync::atomic::AtomicUsize>,
    ) -> Router {
        let handler = move |credential: Option<Credential>, token: Option<AuthorizedToken>| {
            let runs = Arc::clone(&runs);
            async move {
                runs.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                match (credential, token) {
                    (None, None) => "none".to_string(),
                    (Some(Credential::StaticToken), None) => "static".to_string(),
                    (Some(Credential::OAuth(c)), Some(t)) => {
                        assert_eq!(c, t);
                        format!("oauth {}", t.subject.as_deref().unwrap_or_default())
                    }
                    other => panic!("inconsistent extraction: {other:?}"),
                }
            }
        };
        Router::new()
            .route("/test", get(handler))
            .route_layer(layer)
    }

    /// Request headers as raw bytes, so a test can send a non-ASCII value.
    type Headers<'a> = Vec<(&'a str, &'a [u8])>;

    async fn send_raw(app: &Router, headers: &[(&str, &[u8])]) -> Response {
        let mut req = Request::builder().uri("/test");
        for (name, value) in headers {
            req = req.header(*name, HeaderValue::from_bytes(value).unwrap());
        }
        app.clone()
            .oneshot(req.body(Body::empty()).unwrap())
            .await
            .unwrap()
    }

    /// The kind an extractor's refusal carries reaches `on_reject`: a static
    /// token where a handler needs an OAuth token is `OAuthTokenRequired`,
    /// and the status stays 401.
    #[tokio::test]
    async fn an_oauth_extractor_refusing_a_static_token_names_its_kind() {
        let jwks = testing::spawn_jwks_server("200 OK", testing::jwks_body()).await;
        let v = validator(&jwks.url);
        let layer = AuthLayer::builder()
            .static_token(STATIC)
            .oauth(Arc::clone(&v))
            .on_reject(|cx: RejectContext<'_>| {
                let label = match cx.rejection {
                    TokenRejection::Invalid(invalid) => invalid.kind().as_str(),
                    _ => "not invalid",
                };
                Response::new(Body::from(label))
            })
            .build()
            .unwrap();
        let app = Router::new()
            .route("/test", get(|_: AuthorizedToken| async { "ok" }))
            .route("/static", get(|_: StaticTokenMatch| async { "ok" }))
            .route_layer(layer);
        let resp = get_with_auth(&app, Some("Bearer secret")).await;
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(www_authenticate(&resp), v.invalid_token_challenge());
        assert_eq!(body_bytes(resp).await, b"oauth_token_required");
        let resp = get_with_auth(&app, Some("Bearer wrong")).await;
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(body_bytes(resp).await, b"not_jwt");
        // An OAuth token where a handler needs the static token.
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/static")
                    .header(
                        "authorization",
                        format!("Bearer {}", testing::valid_token()),
                    )
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(www_authenticate(&resp), v.invalid_token_challenge());
        assert_eq!(body_bytes(resp).await, b"static_token_required");
    }

    #[tokio::test]
    async fn the_extractors_read_a_valid_token_and_the_static_token() {
        let jwks = testing::spawn_jwks_server("200 OK", testing::jwks_body()).await;
        let v = validator(&jwks.url);
        let layer = AuthLayer::builder()
            .static_token(STATIC)
            .oauth(Arc::clone(&v))
            .build()
            .unwrap();
        let app = Router::new()
            .route(
                "/credential",
                get(|credential: Credential| async move {
                    match credential {
                        Credential::StaticToken => "static".to_string(),
                        Credential::OAuth(t) => format!("oauth {}", t.subject.unwrap_or_default()),
                    }
                }),
            )
            .route(
                "/token",
                get(|token: AuthorizedToken| async move {
                    format!(
                        "{} {}",
                        token.subject.as_deref().unwrap_or_default(),
                        token.has_scope("mcp:read")
                    )
                }),
            )
            .route_layer(layer);
        let get_at = |path: &'static str, header: String| {
            let app = app.clone();
            async move {
                app.oneshot(
                    Request::builder()
                        .uri(path)
                        .header("authorization", header)
                        .body(Body::empty())
                        .unwrap(),
                )
                .await
                .unwrap()
            }
        };

        let valid = format!("Bearer {}", testing::valid_token());
        let resp = get_at("/credential", valid.clone()).await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(body_bytes(resp).await, b"oauth user-1");
        let resp = get_at("/token", valid).await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(body_bytes(resp).await, b"user-1 true");

        let resp = get_at("/credential", "Bearer secret".into()).await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(body_bytes(resp).await, b"static");
        // A static-token request has no OAuth token: the layer's own 401 and
        // challenge, never a 500 or a pass.
        let resp = get_at("/token", "Bearer secret".into()).await;
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(www_authenticate(&resp), v.invalid_token_challenge());
    }

    #[tokio::test]
    async fn an_extractor_outside_every_layer_fails_closed_with_500() {
        let runs = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let count = |runs: &Arc<std::sync::atomic::AtomicUsize>| {
            runs.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        };
        let (r1, r2, r3, r4) = (
            Arc::clone(&runs),
            Arc::clone(&runs),
            Arc::clone(&runs),
            Arc::clone(&runs),
        );
        let app = Router::new()
            .route(
                "/credential",
                get(move |_: Credential| async move { count(&r1) }),
            )
            .route(
                "/token",
                get(move |_: AuthorizedToken| async move { count(&r2) }),
            )
            .route(
                "/opt-credential",
                get(move |_: Option<Credential>| async move { count(&r3) }),
            )
            .route(
                "/opt-token",
                get(move |_: Option<AuthorizedToken>| async move { count(&r4) }),
            );
        for path in ["/credential", "/token", "/opt-credential", "/opt-token"] {
            for header in [None, Some("Bearer secret")] {
                let mut req = Request::builder().uri(path);
                if let Some(h) = header {
                    req = req.header("authorization", h);
                }
                let resp = app
                    .clone()
                    .oneshot(req.body(Body::empty()).unwrap())
                    .await
                    .unwrap();
                assert_eq!(
                    resp.status(),
                    StatusCode::INTERNAL_SERVER_ERROR,
                    "{path} {header:?}"
                );
                assert!(resp.headers().get(WWW_AUTHENTICATE).is_none());
                assert!(body_bytes(resp).await.is_empty(), "{path}");
            }
        }
        assert_eq!(runs.load(std::sync::atomic::Ordering::SeqCst), 0);
    }

    #[test]
    fn optional_still_needs_a_credential_to_build() {
        assert_eq!(
            AuthLayer::builder().optional().build().unwrap_err(),
            AuthLayerError::NoCredential
        );
        assert_eq!(
            AuthLayer::builder()
                .static_token("")
                .optional()
                .build()
                .unwrap_err(),
            AuthLayerError::NoCredential
        );
        assert_eq!(
            AuthLayer::builder()
                .static_token(STATIC)
                .optional()
                .sources([])
                .build()
                .unwrap_err(),
            AuthLayerError::NoSources
        );
        let layer = AuthLayer::builder()
            .static_token("hunter2")
            .optional()
            .build()
            .unwrap();
        assert!(!layer.allows_unauthenticated());
        let rendered = format!("{layer:?}");
        assert!(!rendered.contains("hunter2") && rendered.contains("optional: true"));
    }

    /// Every refusal an `optional()` layer sends is byte-identical to the one
    /// the same layer without `optional()` sends, and the handler never runs;
    /// only a request presenting nothing passes, as `None`.
    #[tokio::test]
    async fn an_optional_layer_passes_only_a_request_with_no_credential() {
        let jwks = testing::spawn_jwks_server("200 OK", testing::jwks_body()).await;
        let v = validator(&jwks.url);
        let builder = || {
            AuthLayer::builder()
                .static_token(STATIC)
                .oauth(Arc::clone(&v))
                .sources([
                    CredentialSource::authorization_bearer(),
                    CredentialSource::Raw(HeaderName::from_static("x-api-key")),
                ])
                .on_reject(json_reject)
        };
        let runs = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let optional =
            optional_extractor_app(builder().optional().build().unwrap(), Arc::clone(&runs));
        let strict =
            optional_extractor_app(builder().build().unwrap(), Arc::new(Default::default()));
        let ran = || runs.load(std::sync::atomic::Ordering::SeqCst);

        // No credential, and blank ones: the handler runs with `None`.
        let blanks: &[&[(&str, &[u8])]] = &[
            &[],
            &[("authorization", b"")],
            &[("authorization", b"Bearer ")],
            &[("authorization", b"bearer    ")],
            // Another scheme carries no bearer credential at all.
            &[("authorization", b"Basic c2VjcmV0")],
            &[("x-api-key", b"   ")],
            &[("authorization", b"Bearer "), ("x-api-key", b"")],
            &[("authorization", b"Bearer "), ("authorization", b" ")],
        ];
        for headers in blanks {
            let before = ran();
            let resp = send_raw(&optional, headers).await;
            assert_eq!(resp.status(), StatusCode::OK, "{headers:?}");
            assert!(resp.headers().get(WWW_AUTHENTICATE).is_none());
            assert_eq!(body_bytes(resp).await, b"none", "{headers:?}");
            assert_eq!(ran(), before + 1);
            // The same request is refused by the non-optional layer.
            let resp = send_raw(&strict, headers).await;
            assert_eq!(resp.status(), StatusCode::UNAUTHORIZED, "{headers:?}");
            assert_eq!(www_authenticate(&resp), v.invalid_token_challenge());
        }

        // Anything presented but not accepted: refused exactly as without
        // `optional()`, and the handler never runs.
        let invalid = format!("Bearer {}", testing::valid_token().replace('.', "x."));
        let expired = format!("Bearer {}", expired_token());
        let unscoped = format!("Bearer {}", unscoped_token());
        let refused: Vec<(Headers<'_>, StatusCode, String)> = vec![
            (
                vec![("authorization", b"Bearer not-a-jwt")],
                StatusCode::UNAUTHORIZED,
                v.invalid_token_challenge(),
            ),
            (
                vec![("authorization", invalid.as_bytes())],
                StatusCode::UNAUTHORIZED,
                v.invalid_token_challenge(),
            ),
            (
                vec![("authorization", expired.as_bytes())],
                StatusCode::UNAUTHORIZED,
                v.invalid_token_challenge(),
            ),
            (
                vec![("x-api-key", b"wrong-key")],
                StatusCode::UNAUTHORIZED,
                v.invalid_token_challenge(),
            ),
            // A blank source never hides a bad one.
            (
                vec![("authorization", b"Bearer "), ("x-api-key", b"wrong-key")],
                StatusCode::UNAUTHORIZED,
                v.invalid_token_challenge(),
            ),
            // Only the first value is authenticated, but a non-blank later one
            // is still something presented, not nothing.
            (
                vec![
                    ("authorization", b"Bearer "),
                    ("authorization", b"Bearer junk"),
                ],
                StatusCode::UNAUTHORIZED,
                v.invalid_token_challenge(),
            ),
            // Not visible ASCII: unreadable, so not provably blank.
            (
                vec![("authorization", b"Bearer \xff")],
                StatusCode::UNAUTHORIZED,
                v.invalid_token_challenge(),
            ),
            (
                vec![("authorization", unscoped.as_bytes())],
                StatusCode::FORBIDDEN,
                v.insufficient_scope_challenge(),
            ),
        ];
        for (headers, status, challenge) in &refused {
            let before = ran();
            let resp = send_raw(&optional, headers).await;
            assert_eq!(resp.status(), *status, "{headers:?}");
            assert_eq!(&www_authenticate(&resp), challenge, "{headers:?}");
            let got = observed(resp).await;
            assert_eq!(got.2, format!("refused {}", status.as_u16()).as_bytes());
            assert_eq!(
                got,
                observed(send_raw(&strict, headers).await).await,
                "{headers:?}"
            );
            assert_eq!(ran(), before, "the handler ran for {headers:?}");
        }

        // Accepted credentials are inserted as usual.
        let valid = format!("Bearer {}", testing::valid_token());
        let resp = send_raw(&optional, &[("authorization", valid.as_bytes())]).await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(body_bytes(resp).await, b"oauth user-1");
        let resp = send_raw(&optional, &[("x-api-key", STATIC.as_bytes())]).await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(body_bytes(resp).await, b"static");
    }

    /// The marker path: a required extractor behind an `optional()` layer that
    /// passed a request through answers with the response the non-optional
    /// layer gives the same request, byte for byte (`on_reject` body included).
    #[tokio::test]
    async fn a_required_extractor_behind_an_optional_layer_gets_the_layers_own_refusal() {
        let v = unreachable_validator();
        let builder = || {
            AuthLayer::builder()
                .static_token(STATIC)
                .oauth(Arc::clone(&v))
                .on_reject(json_reject)
        };
        let runs = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let make = |layer: AuthLayer| {
            let (r1, r2) = (Arc::clone(&runs), Arc::clone(&runs));
            Router::new()
                .route(
                    "/test",
                    get(move |_: Credential| async move {
                        r1.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                    }),
                )
                .route(
                    "/token",
                    get(move |_: AuthorizedToken| async move {
                        r2.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                    }),
                )
                .route_layer(layer)
        };
        let optional = make(builder().optional().build().unwrap());
        let strict = make(builder().build().unwrap());
        for path in ["/test", "/token"] {
            let request = || Request::builder().uri(path).body(Body::empty()).unwrap();
            let got = observed(optional.clone().oneshot(request()).await.unwrap()).await;
            let want = observed(strict.clone().oneshot(request()).await.unwrap()).await;
            assert_eq!(got.0, StatusCode::UNAUTHORIZED, "{path}");
            assert_eq!(got, want, "{path}");
            assert!(
                got.1.iter().any(|(k, val)| k == "www-authenticate"
                    && val == v.invalid_token_challenge().as_bytes()),
                "{path}"
            );
        }
        assert_eq!(runs.load(std::sync::atomic::Ordering::SeqCst), 0);

        // Without OAuth, the static challenge — the same code path again.
        let optional = make(
            AuthLayer::builder()
                .static_token(STATIC)
                .optional()
                .build()
                .unwrap(),
        );
        let resp = optional
            .oneshot(Request::builder().uri("/test").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(resp.headers()[WWW_AUTHENTICATE], DEFAULT_STATIC_CHALLENGE);
    }

    #[tokio::test]
    async fn the_extractors_under_allow_unauthenticated() {
        let app = Router::new()
            .route(
                "/test",
                get(
                    |c: Option<Credential>, t: Option<AuthorizedToken>| async move {
                        assert!(c.is_none() && t.is_none());
                        "none"
                    },
                ),
            )
            .route("/required", get(|_: Credential| async { "unreachable" }))
            .route_layer(AuthLayer::allow_unauthenticated());
        let resp = get_with_auth(&app, Some("Bearer anything")).await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(body_bytes(resp).await, b"none");
        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/required")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(resp.headers()[WWW_AUTHENTICATE], DEFAULT_STATIC_CHALLENGE);
    }

    /// A non-optional layer with the extractors answers exactly as with
    /// `Extension<..>`: the extractor only ever sees what the layer passed.
    #[tokio::test]
    async fn a_non_optional_layer_with_extractors_matches_extension_handlers() {
        let jwks = testing::spawn_jwks_server("200 OK", testing::jwks_body()).await;
        let layer = AuthLayer::builder()
            .static_token(STATIC)
            .oauth(validator(&jwks.url))
            .build()
            .unwrap();
        let via_extension = Router::new()
            .route(
                "/test",
                get(|Extension(c): Extension<Credential>| async move { format!("{c:?}") }),
            )
            .route_layer(layer.clone());
        let via_extractor = Router::new()
            .route(
                "/test",
                get(|c: Credential| async move { format!("{c:?}") }),
            )
            .route_layer(layer);
        let valid = format!("Bearer {}", testing::valid_token());
        let unscoped = format!("Bearer {}", unscoped_token());
        let expired = format!("Bearer {}", expired_token());
        for header in [
            None,
            Some("Bearer "),
            Some("Bearer secret"),
            Some("Bearer wrong"),
            Some(valid.as_str()),
            Some(unscoped.as_str()),
            Some(expired.as_str()),
        ] {
            assert_eq!(
                observed(get_with_auth(&via_extractor, header).await).await,
                observed(get_with_auth(&via_extension, header).await).await,
                "{header:?}"
            );
        }
    }

    fn claims_with(extra: serde_json::Value) -> serde_json::Value {
        let mut claims = serde_json::json!({
            "iss": testing::ISSUER, "aud": testing::AUDIENCE,
            "exp": testing::now() + 3600, "scope": "mcp:read mcp:write", "sub": "user-1",
        });
        for (k, v) in extra.as_object().unwrap() {
            claims[k] = v.clone();
        }
        claims
    }

    #[test]
    fn names_a_token_only_for_dpop_and_tab_separated_bearer() {
        for value in [
            "DPoP x",
            "dpop x",
            "DPoP",
            "Bearer\tx",
            "bearer\t x",
            " Bearer x",
            "\tBEARER\tx",
        ] {
            assert!(names_a_token(value), "{value:?}");
        }
        for value in [
            "",
            "Bearer",
            "Bearer ",
            "Bearer\t",
            "Bearer \t ",
            "Basic x",
            "x",
        ] {
            assert!(!names_a_token(value), "{value:?}");
        }
        // The strict parsing is untouched.
        assert_eq!(bearer_credential("Bearer\tx"), "");
        assert_eq!(bearer_credential("DPoP x"), "");
    }

    /// Every presented-but-unacceptable shape the security review listed is
    /// refused by an `optional()` layer exactly as by the same layer without
    /// it — status, every header and body, byte for byte — and the handler
    /// never runs.
    #[tokio::test]
    async fn an_optional_layer_refuses_every_presented_shape_like_the_strict_layer() {
        use base64::Engine;
        use base64::engine::general_purpose::URL_SAFE_NO_PAD;

        let jwks = testing::spawn_jwks_server("200 OK", testing::jwks_body()).await;
        let v = validator(&jwks.url);
        let builder = || {
            AuthLayer::builder()
                .static_token(STATIC)
                .oauth(Arc::clone(&v))
                .sources([
                    CredentialSource::authorization_bearer(),
                    CredentialSource::Raw(HeaderName::from_static("x-api-key")),
                ])
                .on_reject(json_reject)
        };
        let runs = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let optional =
            optional_extractor_app(builder().optional().build().unwrap(), Arc::clone(&runs));
        let strict =
            optional_extractor_app(builder().build().unwrap(), Arc::new(Default::default()));

        let forged = testing::mint(
            testing::KEY_B_PEM,
            testing::KID_A,
            &claims_with(serde_json::json!({})),
        );
        let wrong_aud = testing::mint(
            testing::KEY_A_PEM,
            testing::KID_A,
            &claims_with(serde_json::json!({ "aud": "some-other-client" })),
        );
        let cnf = testing::mint(
            testing::KEY_A_PEM,
            testing::KID_A,
            &claims_with(serde_json::json!({ "cnf": { "jkt": "abc" } })),
        );
        let valid = testing::valid_token();
        let crit = {
            let mut parts: Vec<String> = valid.split('.').map(str::to_string).collect();
            parts[0] =
                URL_SAFE_NO_PAD.encode(br#"{"alg":"RS256","kid":"test-key-a","crit":["exp"]}"#);
            parts.join(".")
        };

        let cases: Vec<(&str, Vec<(&str, String)>)> = vec![
            (
                "forged",
                vec![("authorization", format!("Bearer {forged}"))],
            ),
            (
                "wrong aud",
                vec![("authorization", format!("Bearer {wrong_aud}"))],
            ),
            (
                "cnf bearer",
                vec![("authorization", format!("Bearer {cnf}"))],
            ),
            ("crit", vec![("authorization", format!("Bearer {crit}"))]),
            (
                "BEARER forged",
                vec![("authorization", format!("BEARER {forged}"))],
            ),
            (
                "bearer bad",
                vec![("authorization", "bearer not-a-jwt".to_string())],
            ),
            (
                "Bearer<TAB>forged",
                vec![("authorization", format!("Bearer\t{forged}"))],
            ),
            (
                "Bearer<TAB>valid",
                vec![("authorization", format!("Bearer\t{valid}"))],
            ),
            (
                " Bearer forged",
                vec![("authorization", format!(" Bearer {forged}"))],
            ),
            ("DPoP cnf", vec![("authorization", format!("DPoP {cnf}"))]),
            (
                "DPoP forged",
                vec![("authorization", format!("DPoP {forged}"))],
            ),
            (
                "Basic, then Bearer forged",
                vec![
                    ("authorization", "Basic x".to_string()),
                    ("authorization", format!("Bearer {forged}")),
                ],
            ),
            (
                "blank Bearer, then Bearer forged",
                vec![
                    ("authorization", "Bearer ".to_string()),
                    ("authorization", format!("Bearer {forged}")),
                ],
            ),
        ];
        for (name, headers) in &cases {
            let headers: Vec<(&str, &[u8])> =
                headers.iter().map(|(n, v)| (*n, v.as_bytes())).collect();
            let before = runs.load(std::sync::atomic::Ordering::SeqCst);
            let got = observed(send_raw(&optional, &headers).await).await;
            let want = observed(send_raw(&strict, &headers).await).await;
            assert_eq!(got.0, StatusCode::UNAUTHORIZED, "{name}");
            assert!(
                got.1.iter().any(|(k, val)| k == "www-authenticate"
                    && val == v.invalid_token_challenge().as_bytes()),
                "{name}"
            );
            assert_eq!(got, want, "{name}");
            assert_eq!(
                runs.load(std::sync::atomic::Ordering::SeqCst),
                before,
                "the handler ran for {name}"
            );
        }
    }

    /// An inner `optional()` layer extracts only what IT accepted: the outer
    /// strict OAuth layer's token and credential are not visible behind it.
    #[tokio::test]
    async fn an_inner_optional_layer_does_not_leak_an_outer_layers_credential() {
        let jwks = testing::spawn_jwks_server("200 OK", testing::jwks_body()).await;
        let outer = AuthLayer::builder()
            .oauth(validator(&jwks.url))
            .build()
            .unwrap();
        let inner = AuthLayer::builder()
            .static_token("inner-key")
            .sources([CredentialSource::Raw(HeaderName::from_static("x-inner"))])
            .optional()
            .build()
            .unwrap();
        let runs = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let app = optional_extractor_app(inner, Arc::clone(&runs)).layer(outer);
        let valid = format!("Bearer {}", testing::valid_token());

        let resp = send_raw(&app, &[("authorization", valid.as_bytes())]).await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(body_bytes(resp).await, b"none");

        // The inner layer's own acceptance is all the handler sees.
        let resp = send_raw(
            &app,
            &[
                ("authorization", valid.as_bytes()),
                ("x-inner", b"inner-key"),
            ],
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(body_bytes(resp).await, b"static");
        assert_eq!(runs.load(std::sync::atomic::Ordering::SeqCst), 2);
    }

    /// Strict nested layers keep accumulating, as documented: `Credential` is
    /// the innermost acceptance, `AuthorizedToken` the outer layer's.
    #[tokio::test]
    async fn strict_nested_layers_accumulate_extensions_as_documented() {
        let jwks = testing::spawn_jwks_server("200 OK", testing::jwks_body()).await;
        let outer = AuthLayer::builder()
            .oauth(validator(&jwks.url))
            .build()
            .unwrap();
        let inner = AuthLayer::builder()
            .static_token("inner-key")
            .sources([CredentialSource::Raw(HeaderName::from_static("x-inner"))])
            .build()
            .unwrap();
        let app = Router::new()
            .route(
                "/test",
                get(|c: Credential, t: AuthorizedToken| async move {
                    format!(
                        "{} {}",
                        matches!(c, Credential::StaticToken),
                        t.subject.unwrap_or_default()
                    )
                }),
            )
            .route_layer(inner)
            .layer(outer);
        let valid = format!("Bearer {}", testing::valid_token());

        let resp = send_raw(
            &app,
            &[
                ("authorization", valid.as_bytes()),
                ("x-inner", b"inner-key"),
            ],
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(body_bytes(resp).await, b"true user-1");

        // The inner strict layer still refuses on its own terms.
        let resp = send_raw(&app, &[("authorization", valid.as_bytes())]).await;
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(resp.headers()[WWW_AUTHENTICATE], DEFAULT_STATIC_CHALLENGE);
    }
}

/// The shared refusal mapping: [`crate::refusal()`] against this layer's own
/// [`Enforce::reject`], and this layer against the `tower` feature's
/// `HttpAuthLayer`, request for request.
#[cfg(test)]
mod shared_refusal_tests {
    use ::tower::{ServiceExt, service_fn};

    use super::*;
    use crate::http_layer::HttpAuthLayer;
    use crate::testing;
    use crate::{Refusal, refusal, refusal_with_static_challenge};

    const STATIC: &str = "secret";
    const CUSTOM: &str = "ApiKey realm=\"example\"";

    fn validator(jwks_uri: &str) -> Arc<OAuthValidator> {
        Arc::new(OAuthValidator::new(&testing::resolved_config(jwks_uri)).unwrap())
    }

    /// The layer's `static_challenge` setting, and the `&str` form
    /// `refusal_with_static_challenge` takes for it.
    #[derive(Clone, Copy, Debug)]
    enum Static {
        Unset,
        Custom,
        Off,
    }

    fn what_the_axum_layer_sends(
        oauth: Option<Arc<OAuthValidator>>,
        setting: Static,
        rejection: &TokenRejection,
    ) -> (u16, Vec<String>) {
        let mut builder = AuthLayer::builder()
            .static_token(STATIC)
            .optional_oauth(oauth)
            // A callback that sets its own challenge, to show it is replaced
            // exactly when `refusal()` names one.
            .on_reject(|_| {
                (StatusCode::IM_A_TEAPOT, [(WWW_AUTHENTICATE, "Callback x")]).into_response()
            });
        builder = match setting {
            Static::Unset => builder,
            Static::Custom => builder.static_challenge(Some(HeaderValue::from_static(CUSTOM))),
            Static::Off => builder.static_challenge(None),
        };
        let layer = builder.build().unwrap();
        let Mode::Enforce(enforce) = &*layer.inner else {
            unreachable!("an enforcing layer was built")
        };
        let (parts, ()) = Request::builder()
            .uri("/test")
            .body(())
            .unwrap()
            .into_parts();
        let response = enforce.reject(rejection, &parts);
        let challenges = response
            .headers()
            .get_all(WWW_AUTHENTICATE)
            .iter()
            .map(|v| v.to_str().unwrap().to_string())
            .collect();
        (response.status().as_u16(), challenges)
    }

    #[test]
    fn refusal_gives_exactly_what_enforce_reject_gives() {
        let v = validator("http://127.0.0.1:1/jwks");
        let rejections = [
            TokenRejection::Missing,
            TokenRejection::Invalid("any reason".into()),
            TokenRejection::InsufficientScope,
        ];
        let mut rows = 0;
        for oauth in [None, Some(Arc::clone(&v))] {
            for setting in [Static::Unset, Static::Custom, Static::Off] {
                for rejection in &rejections {
                    let static_str = match setting {
                        Static::Unset => Some(DEFAULT_STATIC_CHALLENGE),
                        Static::Custom => Some(CUSTOM),
                        Static::Off => None,
                    };
                    let ours =
                        refusal_with_static_challenge(rejection, oauth.as_deref(), static_str);
                    if let Static::Unset = setting {
                        assert_eq!(ours, refusal(rejection, oauth.as_deref()));
                    }
                    let (status, challenges) =
                        what_the_axum_layer_sends(oauth.clone(), setting, rejection);
                    let context = format!("oauth={} {setting:?} {rejection:?}", oauth.is_some());
                    assert_eq!(ours.status, status, "{context}");
                    // `None` leaves the callback's own header in place, as the
                    // layer documents; `Some` replaces it.
                    let expected = match &ours {
                        Refusal {
                            www_authenticate: Some(c),
                            ..
                        } => vec![c.clone()],
                        _ => vec!["Callback x".to_string()],
                    };
                    assert_eq!(challenges, expected, "{context}");
                    rows += 1;
                }
            }
        }
        assert_eq!(rows, 18);
    }

    #[test]
    fn the_status_and_challenge_are_what_rfc_6750_asks_for() {
        let v = validator("http://127.0.0.1:1/jwks");
        let r = refusal(&TokenRejection::Missing, Some(&v));
        assert_eq!(r.status, 401);
        assert_eq!(r.www_authenticate, Some(v.invalid_token_challenge()));
        let r = refusal(&TokenRejection::Invalid("x".into()), Some(&v));
        assert_eq!(r.status, 401);
        assert_eq!(r.www_authenticate, Some(v.invalid_token_challenge()));
        let r = refusal(&TokenRejection::InsufficientScope, Some(&v));
        assert_eq!(r.status, 403);
        assert_eq!(r.www_authenticate, Some(v.insufficient_scope_challenge()));
        // With OAuth, the static setting is ignored.
        assert_eq!(
            refusal_with_static_challenge(&TokenRejection::Missing, Some(&v), None),
            refusal(&TokenRejection::Missing, Some(&v))
        );
    }

    /// Status, every `WWW-Authenticate` value, and the handler's body.
    type Seen = (u16, Vec<String>, String);

    async fn through_axum(layer: AuthLayer, headers: &[(&str, &str)]) -> Seen {
        let app: Router = Router::new()
            .route(
                "/test",
                get(|credential: Option<Credential>| async move { format!("{credential:?}") }),
            )
            .route_layer(layer);
        let mut request = Request::builder().uri("/test");
        for (name, value) in headers {
            request = request.header(*name, *value);
        }
        let response = app
            .oneshot(request.body(Body::empty()).unwrap())
            .await
            .unwrap();
        let status = response.status().as_u16();
        let challenges = response
            .headers()
            .get_all(WWW_AUTHENTICATE)
            .iter()
            .map(|v| v.to_str().unwrap().to_string())
            .collect();
        let body = ::axum::body::to_bytes(response.into_body(), 64 * 1024)
            .await
            .unwrap();
        (
            status,
            challenges,
            String::from_utf8(body.to_vec()).unwrap(),
        )
    }

    async fn through_tower(layer: HttpAuthLayer, headers: &[(&str, &str)]) -> Seen {
        let service = tower_layer::Layer::layer(
            &layer,
            service_fn(|request: http::Request<String>| async move {
                let credential = request.extensions().get::<Credential>().cloned();
                Ok::<_, std::convert::Infallible>(http::Response::new(format!("{credential:?}")))
            }),
        );
        let mut request = http::Request::builder().uri("/test");
        for (name, value) in headers {
            request = request.header(*name, *value);
        }
        let response = service
            .oneshot(request.body(String::new()).unwrap())
            .await
            .unwrap();
        let challenges = response
            .headers()
            .get_all(WWW_AUTHENTICATE)
            .iter()
            .map(|v| v.to_str().unwrap().to_string())
            .collect();
        (response.status().as_u16(), challenges, response.into_body())
    }

    #[tokio::test]
    async fn the_axum_and_tower_layers_answer_every_request_identically() {
        let jwks = testing::spawn_jwks_server("200 OK", testing::jwks_body()).await;
        let v = validator(&jwks.url);
        let mint = |scope: &str, exp_offset: i64| {
            testing::mint(
                testing::KEY_A_PEM,
                testing::KID_A,
                &serde_json::json!({
                    "iss": testing::ISSUER, "aud": testing::AUDIENCE, "sub": "user-1",
                    "exp": testing::now() as i64 + exp_offset, "scope": scope,
                }),
            )
        };
        let valid = format!("Bearer {}", mint("mcp:read", 3600));
        let expired = format!("Bearer {}", mint("mcp:read", -3600));
        let unscoped = format!("Bearer {}", mint("openid", 3600));
        let requests: Vec<Vec<(&str, &str)>> = vec![
            vec![],
            vec![("authorization", valid.as_str())],
            vec![("authorization", expired.as_str())],
            vec![("authorization", unscoped.as_str())],
            vec![("authorization", "Bearer not-a-jwt")],
            vec![("authorization", "Bearer secret")],
            vec![("authorization", "bearer secret")],
            vec![("authorization", "Bearer ")],
            vec![("authorization", "Basic abc")],
            vec![("authorization", "DPoP abc")],
            vec![("x-api-key", "secret")],
            vec![("authorization", "Bearer wrong"), ("x-api-key", "secret")],
        ];

        // (static token, oauth, static_challenge, optional, x-api-key source)
        type Config = (
            Option<&'static str>,
            bool,
            Option<Option<&'static str>>,
            bool,
            bool,
        );
        let configs: [Config; 7] = [
            (None, true, None, false, false),
            (Some(STATIC), true, None, false, true),
            (Some(STATIC), false, None, false, false),
            (Some(STATIC), false, Some(None), false, false),
            (Some(STATIC), false, Some(Some(CUSTOM)), false, true),
            (Some(STATIC), true, None, true, false),
            (Some(STATIC), false, None, true, true),
        ];
        for (static_token, with_oauth, static_challenge, optional, api_key) in configs {
            let oauth = with_oauth.then(|| Arc::clone(&v));
            let sources = if api_key {
                vec![
                    CredentialSource::authorization_bearer(),
                    CredentialSource::Raw(HeaderName::from_static("x-api-key")),
                ]
            } else {
                vec![CredentialSource::authorization_bearer()]
            };
            let challenge = static_challenge.map(|c| c.map(HeaderValue::from_static));
            let mut axum_builder = AuthLayer::builder()
                .optional_static_token(static_token.map(str::to_string))
                .optional_oauth(oauth.clone())
                .sources(sources.clone());
            let mut tower_builder = HttpAuthLayer::builder()
                .optional_static_token(static_token.map(str::to_string))
                .optional_oauth(oauth.clone())
                .sources(sources);
            if let Some(c) = challenge {
                axum_builder = axum_builder.static_challenge(c.clone());
                tower_builder = tower_builder.static_challenge(c);
            }
            if optional {
                axum_builder = axum_builder.optional();
                tower_builder = tower_builder.optional();
            }
            let axum_layer = axum_builder.build().unwrap();
            let tower_layer = tower_builder.build().unwrap();
            for headers in &requests {
                let a = through_axum(axum_layer.clone(), headers).await;
                let t = through_tower(tower_layer.clone(), headers).await;
                assert_eq!(
                    a, t,
                    "config {static_token:?} oauth={with_oauth} {static_challenge:?} \
                     optional={optional} api_key={api_key}, request {headers:?}"
                );
            }
        }
    }

    /// Status, every `WWW-Authenticate` value, `Content-Type`, and the body.
    type SeenFull = (u16, Vec<String>, Option<String>, String);

    fn seen_parts(headers: &HeaderMap, status: u16, body: String) -> SeenFull {
        let challenges = headers
            .get_all(WWW_AUTHENTICATE)
            .iter()
            .map(|v| v.to_str().unwrap().to_string())
            .collect();
        let content_type = headers
            .get(http::header::CONTENT_TYPE)
            .map(|v| v.to_str().unwrap().to_string());
        (status, challenges, content_type, body)
    }

    /// What the handler behind both stacks reports: the credential, the
    /// token and the static match the layers left in the extensions.
    fn describe(extensions: &http::Extensions) -> String {
        format!(
            "{:?} token={} {:?}",
            extensions.get::<Credential>(),
            extensions.get::<AuthorizedToken>().is_some(),
            extensions.get::<StaticTokenMatch>()
        )
    }

    /// Headers as raw `HeaderValue`s, so a test can send a repeated header or
    /// bytes that are not visible ASCII.
    type RawHeaders = Vec<(&'static str, HeaderValue)>;

    async fn axum_full(app: Router, headers: &RawHeaders) -> SeenFull {
        let mut request = Request::builder().uri("/test");
        for (name, value) in headers {
            request = request.header(*name, value.clone());
        }
        let response = app
            .oneshot(request.body(Body::empty()).unwrap())
            .await
            .unwrap();
        let (parts, body) = response.into_parts();
        let body = ::axum::body::to_bytes(body, 64 * 1024).await.unwrap();
        seen_parts(
            &parts.headers,
            parts.status.as_u16(),
            String::from_utf8(body.to_vec()).unwrap(),
        )
    }

    async fn tower_full<S>(service: S, headers: &RawHeaders) -> SeenFull
    where
        S: tower_service::Service<
                http::Request<String>,
                Response = http::Response<String>,
                Error = std::convert::Infallible,
            >,
    {
        let mut request = http::Request::builder().uri("/test");
        for (name, value) in headers {
            request = request.header(*name, value.clone());
        }
        let response = service
            .oneshot(request.body(String::new()).unwrap())
            .await
            .unwrap();
        let (parts, body) = response.into_parts();
        seen_parts(&parts.headers, parts.status.as_u16(), body)
    }

    fn axum_app(layer: AuthLayer) -> Router {
        Router::new()
            .route(
                "/test",
                get(|request: Request| async move { describe(request.extensions()) }),
            )
            .route_layer(layer)
    }

    fn tower_handler(
        request: http::Request<String>,
    ) -> std::future::Ready<Result<http::Response<String>, std::convert::Infallible>> {
        // The content type axum gives a `String` handler response, so only
        // the layers' own differences could make the two stacks disagree.
        let mut response = http::Response::new(describe(request.extensions()));
        response.headers_mut().insert(
            http::header::CONTENT_TYPE,
            HeaderValue::from_static("text/plain; charset=utf-8"),
        );
        std::future::ready(Ok(response))
    }

    #[tokio::test]
    async fn the_layers_agree_on_callbacks_repeated_and_unreadable_headers() {
        let jwks = testing::spawn_jwks_server("200 OK", testing::jwks_body()).await;
        let v = validator(&jwks.url);
        let valid = HeaderValue::from_str(&format!("Bearer {}", testing::valid_token())).unwrap();
        let requests: Vec<RawHeaders> = vec![
            vec![],
            vec![("authorization", valid.clone())],
            vec![("authorization", HeaderValue::from_static("Bearer wrong"))],
            // Repeated: only the first value is authenticated, and an optional
            // layer counts a non-blank later value as presented.
            vec![
                ("authorization", valid.clone()),
                ("authorization", HeaderValue::from_static("Bearer wrong")),
            ],
            vec![
                ("authorization", HeaderValue::from_static("Bearer ")),
                ("authorization", HeaderValue::from_static("Bearer secret")),
            ],
            vec![
                ("x-api-key", HeaderValue::from_static("wrong")),
                ("x-api-key", HeaderValue::from_static("secret")),
            ],
            // Not visible ASCII: no candidate, but presented.
            vec![(
                "authorization",
                HeaderValue::from_bytes(b"Bearer s\xe9cret").unwrap(),
            )],
            vec![("x-api-key", HeaderValue::from_bytes(b"\xff").unwrap())],
            // The labeled key both layers also hold.
            vec![("x-api-key", HeaderValue::from_static("key-next"))],
        ];
        let next = || {
            crate::StaticTokens::new()
                .with(Some("next"), "key-next")
                .unwrap()
        };
        for with_oauth in [false, true] {
            for optional in [false, true] {
                for static_challenge in [None, Some(None)] {
                    let sources = [
                        CredentialSource::authorization_bearer(),
                        CredentialSource::Raw(HeaderName::from_static("x-api-key")),
                    ];
                    let oauth = with_oauth.then(|| Arc::clone(&v));
                    // Both callbacks set their own challenge, content type and
                    // body; the layers must treat them identically.
                    let mut a = AuthLayer::builder()
                        .static_token(STATIC)
                        .static_tokens(next())
                        .optional_oauth(oauth.clone())
                        .sources(sources.clone())
                        .on_reject(|cx| {
                            (
                                StatusCode::IM_A_TEAPOT,
                                [
                                    (WWW_AUTHENTICATE, "Callback x"),
                                    (http::header::CONTENT_TYPE, "application/json"),
                                ],
                                format!("{{\"status\":{}}}", cx.status.as_u16()),
                            )
                                .into_response()
                        });
                    let mut t = HttpAuthLayer::builder()
                        .static_token(STATIC)
                        .static_tokens(next())
                        .optional_oauth(oauth)
                        .sources(sources)
                        .on_reject(|cx: RejectContext<'_>| {
                            http::Response::builder()
                                .status(StatusCode::IM_A_TEAPOT)
                                .header(WWW_AUTHENTICATE, "Callback x")
                                .header(http::header::CONTENT_TYPE, "application/json")
                                .body(format!("{{\"status\":{}}}", cx.status.as_u16()))
                                .unwrap()
                        });
                    if let Some(c) = &static_challenge {
                        a = a.static_challenge(c.clone());
                        t = t.static_challenge(c.clone());
                    }
                    if optional {
                        a = a.optional();
                        t = t.optional();
                    }
                    let (a, t) = (a.build().unwrap(), t.build().unwrap());
                    for headers in &requests {
                        let service = tower_layer::Layer::layer(&t, service_fn(tower_handler));
                        assert_eq!(
                            axum_full(axum_app(a.clone()), headers).await,
                            tower_full(service, headers).await,
                            "oauth={with_oauth} optional={optional} \
                             static_challenge={static_challenge:?} {headers:?}"
                        );
                    }
                }
            }
        }
    }

    #[tokio::test]
    async fn the_layers_agree_that_optional_clears_an_outer_layers_credential() {
        let jwks = testing::spawn_jwks_server("200 OK", testing::jwks_body()).await;
        let v = validator(&jwks.url);
        let bearer = HeaderValue::from_str(&format!("Bearer {}", testing::valid_token())).unwrap();
        // An outer strict layer accepts an OAuth token from `X-Outer`; the
        // inner optional layer reads only `Authorization`.
        let outer_sources = [CredentialSource::Bearer(HeaderName::from_static("x-outer"))];
        let requests: Vec<RawHeaders> = vec![
            vec![("x-outer", bearer.clone())],
            vec![
                ("x-outer", bearer.clone()),
                ("authorization", HeaderValue::from_static("Bearer secret")),
            ],
            vec![
                ("x-outer", bearer.clone()),
                ("authorization", HeaderValue::from_static("Bearer wrong")),
            ],
        ];
        let axum_outer = AuthLayer::builder()
            .oauth(Arc::clone(&v))
            .sources(outer_sources.clone())
            .build()
            .unwrap();
        let axum_inner = AuthLayer::builder()
            .static_token(STATIC)
            .optional()
            .build()
            .unwrap();
        let tower_outer = HttpAuthLayer::builder()
            .oauth(Arc::clone(&v))
            .sources(outer_sources)
            .build()
            .unwrap();
        let tower_inner = HttpAuthLayer::builder()
            .static_token(STATIC)
            .optional()
            .build()
            .unwrap();
        let mut outcomes = Vec::new();
        for headers in &requests {
            let app = axum_app(axum_inner.clone()).layer(axum_outer.clone());
            let service = ::tower::ServiceBuilder::new()
                .layer(tower_outer.clone())
                .layer(tower_inner.clone())
                .service(service_fn(tower_handler));
            let a = axum_full(app, headers).await;
            assert_eq!(a, tower_full(service, headers).await, "{headers:?}");
            outcomes.push(a);
        }
        // The pass-through left nothing of the outer layer's token.
        assert_eq!(outcomes[0].3, "None token=false None");
        assert_eq!(
            outcomes[1].3,
            "Some(StaticToken) token=false Some(StaticTokenMatch { label: None })"
        );
        assert_eq!(outcomes[2].0, 401);
    }
}

/// Several static tokens (`AuthLayerBuilder::static_tokens`) and the
/// `StaticTokenMatch` extensions and extractors.
#[cfg(test)]
mod static_tokens_tests {
    use ::tower::ServiceExt;

    use super::*;
    use crate::testing;
    use http::HeaderName;

    const STATIC: &str = "secret";

    fn rotation() -> StaticTokens {
        StaticTokens::new()
            .with(Some("current"), "key-current")
            .and_then(|t| t.with(Some("next"), "key-next"))
            .unwrap()
    }

    fn validator(jwks_uri: &str) -> Arc<OAuthValidator> {
        Arc::new(OAuthValidator::new(&testing::resolved_config(jwks_uri)).unwrap())
    }

    /// A handler reporting the credential and the static match it extracts.
    async fn report(credential: Option<Credential>, matched: Option<StaticTokenMatch>) -> String {
        format!("{credential:?} {matched:?}")
    }

    fn app(layer: AuthLayer) -> Router {
        Router::new()
            .route("/test", get(report))
            .route(
                "/required",
                get(|m: StaticTokenMatch| async move { format!("{:?}", m.label()) }),
            )
            .route_layer(layer)
    }

    async fn send(app: &Router, path: &str, headers: &[(&str, &str)]) -> Response {
        let mut request = Request::builder().uri(path);
        for (name, value) in headers {
            request = request.header(*name, *value);
        }
        app.clone()
            .oneshot(request.body(Body::empty()).unwrap())
            .await
            .unwrap()
    }

    /// Status, every header, and the body.
    async fn observed(resp: Response) -> (u16, Vec<(String, Vec<u8>)>, String) {
        let status = resp.status().as_u16();
        let headers = resp
            .headers()
            .iter()
            .map(|(k, v)| (k.to_string(), v.as_bytes().to_vec()))
            .collect();
        let body = ::axum::body::to_bytes(resp.into_body(), 64 * 1024)
            .await
            .unwrap();
        (status, headers, String::from_utf8(body.to_vec()).unwrap())
    }

    fn json_reject(cx: RejectContext<'_>) -> Response {
        (
            cx.status,
            Json(serde_json::json!({ "status": cx.status.as_u16() })),
        )
            .into_response()
    }

    #[tokio::test]
    async fn a_one_entry_set_answers_exactly_like_static_token() {
        let jwks = testing::spawn_jwks_server("200 OK", testing::jwks_body()).await;
        let v = validator(&jwks.url);
        let valid = format!("Bearer {}", testing::valid_token());
        let requests: Vec<Vec<(&str, &str)>> = vec![
            vec![],
            vec![("authorization", "Bearer secret")],
            vec![("authorization", "bearer secret")],
            vec![("authorization", "Bearer wrong")],
            vec![("authorization", "Bearer ")],
            vec![("authorization", "DPoP secret")],
            vec![("x-api-key", "secret")],
            vec![("authorization", "Bearer wrong"), ("x-api-key", "secret")],
            vec![("authorization", valid.as_str())],
        ];
        // (oauth, optional, static_challenge(None), on_reject)
        let configs = [
            (false, false, false, false),
            (false, false, true, false),
            (true, false, false, true),
            (false, true, false, true),
            (true, true, false, false),
        ];
        for (with_oauth, optional, no_challenge, callback) in configs {
            let build = |use_set: bool| {
                let mut b = AuthLayer::builder()
                    .optional_oauth(with_oauth.then(|| Arc::clone(&v)))
                    .sources([
                        CredentialSource::authorization_bearer(),
                        CredentialSource::Raw(HeaderName::from_static("x-api-key")),
                    ]);
                b = if use_set {
                    b.static_tokens(StaticTokens::single(STATIC).unwrap())
                } else {
                    b.static_token(STATIC)
                };
                if optional {
                    b = b.optional();
                }
                if no_challenge {
                    b = b.static_challenge(None);
                }
                if callback {
                    b = b.on_reject(json_reject);
                }
                app(b.build().unwrap())
            };
            let (old, new) = (build(false), build(true));
            for headers in &requests {
                for path in ["/test", "/required"] {
                    let a = observed(send(&old, path, headers).await).await;
                    let b = observed(send(&new, path, headers).await).await;
                    assert_eq!(
                        a,
                        b,
                        "config {:?} {path} {headers:.40?}",
                        (with_oauth, optional, no_challenge, callback)
                    );
                }
            }
        }
    }

    #[tokio::test]
    async fn the_extractors_name_the_matching_key() {
        let app = app(AuthLayer::builder()
            .static_tokens(rotation())
            .build()
            .unwrap());
        for (secret, label) in [("key-current", "current"), ("key-next", "next")] {
            let bearer = format!("Bearer {secret}");
            let (status, _, body) =
                observed(send(&app, "/test", &[("authorization", &bearer)]).await).await;
            assert_eq!(status, 200);
            assert_eq!(
                body,
                format!("Some(StaticToken) Some(StaticTokenMatch {{ label: Some({label:?}) }})")
            );
            let (status, _, body) =
                observed(send(&app, "/required", &[("authorization", &bearer)]).await).await;
            assert_eq!((status, body), (200, format!("Some({label:?})")));
        }
        let (status, headers, _) =
            observed(send(&app, "/test", &[("authorization", "Bearer key-old")]).await).await;
        assert_eq!(status, 401);
        assert!(headers.contains(&(
            "www-authenticate".to_string(),
            DEFAULT_STATIC_CHALLENGE.as_bytes().to_vec()
        )));
    }

    #[tokio::test]
    async fn the_extractor_refuses_an_oauth_request_and_a_route_outside_every_layer() {
        let jwks = testing::spawn_jwks_server("200 OK", testing::jwks_body()).await;
        let v = validator(&jwks.url);
        let layer = AuthLayer::builder()
            .oauth(Arc::clone(&v))
            .static_tokens(rotation())
            .build()
            .unwrap();
        let router = app(layer);
        let valid = format!("Bearer {}", testing::valid_token());
        // An OAuth token: the optional form is `None`, the required one gets
        // the layer's own 401 and challenge.
        let (status, _, body) =
            observed(send(&router, "/test", &[("authorization", &valid)]).await).await;
        assert_eq!(status, 200);
        assert!(
            body.starts_with("Some(OAuth(") && body.ends_with(" None"),
            "{body}"
        );
        let resp = send(&router, "/required", &[("authorization", &valid)]).await;
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(
            resp.headers()[WWW_AUTHENTICATE],
            v.invalid_token_challenge().as_str()
        );

        // A layer with no static token at all: still the layer's own 401.
        let oauth_only = app(AuthLayer::builder().oauth(Arc::clone(&v)).build().unwrap());
        let resp = send(&oauth_only, "/required", &[("authorization", &valid)]).await;
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);

        // No layer: 500, never access, for both forms.
        let bare: Router = Router::new().route("/test", get(report)).route(
            "/required",
            get(|_: StaticTokenMatch| async { "unreachable" }),
        );
        for path in ["/test", "/required"] {
            let resp = send(&bare, path, &[("authorization", "Bearer key-current")]).await;
            assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR, "{path}");
        }
    }

    #[tokio::test]
    async fn an_optional_layer_with_several_tokens() {
        let app = app(AuthLayer::builder()
            .static_tokens(rotation())
            .optional()
            .build()
            .unwrap());
        let (status, _, body) = observed(send(&app, "/test", &[]).await).await;
        assert_eq!((status, body.as_str()), (200, "None None"));
        // Required extractor behind a pass-through: the layer's own 401.
        let (status, _, _) = observed(send(&app, "/required", &[]).await).await;
        assert_eq!(status, 401);
        for (secret, label) in [("key-current", "current"), ("key-next", "next")] {
            let (status, _, body) = observed(
                send(
                    &app,
                    "/required",
                    &[("authorization", &format!("Bearer {secret}"))],
                )
                .await,
            )
            .await;
            assert_eq!((status, body), (200, format!("Some({label:?})")));
        }
        let (status, _, _) =
            observed(send(&app, "/test", &[("authorization", "Bearer key-old")]).await).await;
        assert_eq!(status, 401);
    }

    #[tokio::test]
    async fn nested_layers_keep_the_match_paired_with_the_credential() {
        let jwks = testing::spawn_jwks_server("200 OK", testing::jwks_body()).await;
        let v = validator(&jwks.url);
        let valid = format!("Bearer {}", testing::valid_token());
        let outer_static = AuthLayer::builder()
            .static_tokens(rotation())
            .sources([CredentialSource::Raw(HeaderName::from_static("x-outer"))])
            .build()
            .unwrap();

        // An inner OAuth layer's acceptance removes the outer static match.
        let inner_oauth = AuthLayer::builder().oauth(Arc::clone(&v)).build().unwrap();
        let router = app(inner_oauth).layer(outer_static.clone());
        let (status, _, body) = observed(
            send(
                &router,
                "/test",
                &[("x-outer", "key-next"), ("authorization", &valid)],
            )
            .await,
        )
        .await;
        assert_eq!(status, 200);
        assert!(
            body.starts_with("Some(OAuth(") && body.ends_with(" None"),
            "{body}"
        );

        // An inner optional layer's pass-through clears it too.
        let inner_optional = AuthLayer::builder()
            .static_token("inner-key")
            .sources([CredentialSource::Raw(HeaderName::from_static("x-inner"))])
            .optional()
            .build()
            .unwrap();
        let router = app(inner_optional).layer(outer_static.clone());
        let (_, _, body) = observed(send(&router, "/test", &[("x-outer", "key-next")]).await).await;
        assert_eq!(body, "None None");

        // An inner strict static layer's match replaces the outer one.
        let inner_static = AuthLayer::builder()
            .static_token("inner-key")
            .sources([CredentialSource::Raw(HeaderName::from_static("x-inner"))])
            .build()
            .unwrap();
        let router = app(inner_static).layer(outer_static);
        let (_, _, body) = observed(
            send(
                &router,
                "/test",
                &[("x-outer", "key-next"), ("x-inner", "inner-key")],
            )
            .await,
        )
        .await;
        assert_eq!(
            body,
            "Some(StaticToken) Some(StaticTokenMatch { label: None })"
        );
    }

    #[test]
    fn build_with_decision_combines_the_set_as_documented() {
        let v = validator("http://127.0.0.1:1/jwks");
        assert!(
            AuthLayer::builder()
                .optional_oauth(Some(Arc::clone(&v)))
                .static_tokens(rotation())
                .build_with_decision(StaticTokenDecision::StaticAndOAuth("x".into()))
                .is_ok()
        );
        let dropped = AuthLayer::builder()
            .oauth(Arc::clone(&v))
            .static_tokens(rotation())
            .build_with_decision(StaticTokenDecision::StaticIgnored)
            .unwrap();
        assert!(
            format!("{dropped:?}").contains("static_tokens: None"),
            "{dropped:?}"
        );
        for (decision, oauth) in [
            (StaticTokenDecision::OAuthOnly, Some(Arc::clone(&v))),
            (StaticTokenDecision::Unauthenticated, None),
        ] {
            assert_eq!(
                AuthLayer::builder()
                    .optional_oauth(oauth)
                    .static_tokens(rotation())
                    .build_with_decision(decision)
                    .unwrap_err(),
                AuthLayerError::DecisionWithoutStaticToken
            );
        }
        // `from_decision` takes no set, so it behaves exactly as before.
        assert!(
            AuthLayer::from_decision(StaticTokenDecision::Unauthenticated, None)
                .unwrap()
                .allows_unauthenticated()
        );
        assert_eq!(
            AuthLayer::builder()
                .static_tokens(StaticTokens::new())
                .build()
                .unwrap_err(),
            AuthLayerError::NoCredential
        );
    }

    #[test]
    fn debug_never_prints_a_token_from_a_set() {
        let builder = AuthLayer::builder()
            .static_token("hunter2-single")
            .static_tokens(
                StaticTokens::new()
                    .with(Some("next"), "hunter2-next")
                    .unwrap(),
            );
        let rendered = format!("{builder:?}");
        assert!(
            !rendered.contains("hunter2") && rendered.contains("next"),
            "{rendered}"
        );
        let layer = builder.build().unwrap();
        let rendered = format!("{layer:?}");
        assert!(
            !rendered.contains("hunter2") && rendered.contains("<redacted>"),
            "{rendered}"
        );
    }
}