autumn-web 0.5.0

An opinionated, convention-over-configuration web framework for Rust
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
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
//! Router construction and configuration.
//!
//! This module handles assembling the final [`axum::Router`] from the various
//! components configured in [`AppBuilder`](crate::app::AppBuilder), including
//! user routes, static files, middleware, error pages, and framework endpoints
//! like actuators and probes.

use std::sync::Arc;
use std::time::Duration;

use crate::app::ScopedGroup;
use crate::config::AutumnConfig;
use crate::error_pages::{self, SharedRenderer};
use crate::extract::State;
use crate::idempotency::{IdempotencyLayer, IdempotencyStore, MemoryIdempotencyStore};
use crate::middleware::RequestIdLayer;
use crate::middleware::dev;
use crate::middleware::exception_filter::{
    ExceptionFilter, ExceptionFilterLayer, ProblemDetailsFilter,
};
use crate::route::Route;
use crate::state::AppState;
use axum::middleware::Next;
use axum::response::IntoResponse;
use http::{Request, StatusCode};
use thiserror::Error;

pub const DEFAULT_FAVICON_PATH: &str = "/favicon.ico";

/// Errors that can occur during the router build process.
///
/// These errors are typically fatal and represent configuration or routing
/// definition issues that must be fixed before the application can start.
#[derive(Debug, Error, PartialEq, Eq)]
pub enum RouterBuildError {
    /// The session backend configuration is invalid (e.g. Redis without a URL).
    #[error("invalid session backend configuration: {0}")]
    InvalidSessionBackend(#[from] crate::session::SessionBackendConfigError),
    /// The idempotency backend configuration is invalid.
    #[error("invalid idempotency backend configuration: {0}")]
    #[allow(dead_code)] // constructed only in the `redis` feature path
    InvalidIdempotencyBackend(String),
    /// A user-defined route conflicts with a framework-provided route.
    #[error("framework route overlap at {path}: {existing} conflicts with {incoming}")]
    FrameworkRouteOverlap {
        /// The HTTP path where the overlap occurred.
        path: String,
        /// The name of the existing framework route.
        existing: &'static str,
        /// The name of the incoming user route.
        incoming: &'static str,
    },
    /// An `OpenApiConfig` path (e.g. `openapi_json_path` or
    /// `swagger_ui_path`) is not a valid route path (must start with `/`
    /// and be non-empty).
    #[cfg(feature = "openapi")]
    #[error("invalid OpenAPI {field} path: {value:?} (must start with '/' and be non-empty)")]
    InvalidOpenApiPath {
        /// Which config field carried the invalid path.
        field: &'static str,
        /// The offending value from the user's config.
        value: String,
    },
    /// `openapi_json_path` and `swagger_ui_path` collide on the same
    /// URL. Mounting both would cause axum to panic on overlapping
    /// method routes at startup.
    #[cfg(feature = "openapi")]
    #[error(
        "openapi_json_path and swagger_ui_path both resolve to {path:?}; they must differ or `swagger_ui_path` must be `None`"
    )]
    DuplicateOpenApiPath {
        /// The path that both fields pointed at.
        path: String,
    },
    /// An `OpenAPI` mount path overlaps with an existing `GET` handler,
    /// which would panic at `axum::Router::merge` time.
    #[cfg(feature = "openapi")]
    #[error(
        "OpenAPI {field} path {path:?} collides with an existing GET route; choose a different `OpenApiConfig::{field}`"
    )]
    OpenApiPathCollision {
        /// Which config field carried the colliding path.
        field: &'static str,
        /// The colliding path.
        path: String,
    },
    /// A route is annotated with an API version that is not registered.
    #[error("route '{route_name}' uses unregistered API version '{version}'")]
    UnregisteredApiVersion { route_name: String, version: String },
    /// The MCP mount path (from [`AppBuilder::mount_mcp`](crate::app::AppBuilder::mount_mcp))
    /// is not a valid route path. axum requires paths to start with `/`, so an
    /// invalid path is surfaced here rather than panicking at mount time.
    #[cfg(feature = "mcp")]
    #[error("invalid MCP mount path: {value:?} (must start with '/' and be non-empty)")]
    InvalidMcpPath {
        /// The offending mount path.
        value: String,
    },
    /// The MCP mount path collides with an existing application route at the
    /// same path. Mounting the MCP endpoint there would panic at
    /// `axum::Router::merge` time on overlapping method routes, so this is
    /// surfaced as a recoverable error instead.
    #[cfg(feature = "mcp")]
    #[error(
        "MCP mount path {path:?} collides with an existing {method} route; choose a different `mount_mcp` path"
    )]
    McpPathCollision {
        /// The colliding mount path.
        path: String,
        /// The HTTP method of the existing route at that path.
        method: String,
    },
}

/// Build the fully-configured Axum router from routes, config, and state.
///
/// Extracted from `AppBuilder::run` so the router construction logic is
/// testable without binding a real TCP listener.
///
/// # Panics
///
/// Panics when framework router assembly encounters invalid configuration.
/// Use [`try_build_router`] to handle configuration errors explicitly.
#[allow(dead_code)]
pub fn build_router(
    route_list: Vec<Route>,
    config: &AutumnConfig,
    state: AppState,
) -> axum::Router {
    try_build_router(route_list, config, state)
        .unwrap_or_else(|error| panic!("invalid router configuration: {error}"))
}

/// Checked variant of [`build_router`] that returns configuration errors
/// instead of panicking.
///
/// # Errors
///
/// Returns [`RouterBuildError`] when router assembly encounters invalid
/// framework configuration, such as an unusable session backend.
pub struct RouterContext {
    pub exception_filters: Vec<Arc<dyn ExceptionFilter>>,
    pub scoped_groups: Vec<ScopedGroup>,
    pub merge_routers: Vec<axum::Router<AppState>>,
    pub nest_routers: Vec<(String, axum::Router<AppState>)>,
    /// Custom Tower layers registered via
    /// [`AppBuilder::layer`](crate::app::AppBuilder::layer). Applied inside
    /// [`RequestIdLayer`] and the session layer on the ingress path so user
    /// middleware observes the generated request ID and session context.
    ///
    /// **SSG/ISG mode trade-off**: when `dist_dir` is active, layers are
    /// moved outside the static-first middleware so they can process
    /// pre-rendered responses (e.g. compression).  As a side effect they also
    /// run *before* `RequestIdLayer`, session, `MetricsLayer`, and
    /// `ExceptionFilterLayer` for all requests (static and dynamic).  Layers
    /// that depend on extensions set by those framework layers — such as the
    /// request ID or session data — will not find them in SSG mode.
    pub custom_layers: Vec<crate::app::CustomLayerRegistration>,
    pub error_page_renderer: Option<SharedRenderer>,
    /// Custom session store installed via
    /// [`AppBuilder::with_session_store`](crate::app::AppBuilder::with_session_store).
    /// When `Some`, [`apply_session_layer`](crate::session::apply_session_layer)
    /// uses it directly and skips the config-driven backend selection.
    pub session_store: Option<Arc<dyn crate::session::BoxedSessionStore>>,
    /// `OpenAPI` generation configuration. When `Some`, the router mounts
    /// an `openapi.json` endpoint and (optionally) a Swagger UI page
    /// describing the application's routes.
    ///
    /// Gated behind the `openapi` feature.
    #[cfg(feature = "openapi")]
    pub openapi: Option<crate::openapi::OpenApiConfig>,
    /// MCP (Model Context Protocol) runtime config. When `Some`, the router
    /// mounts a Streamable-HTTP MCP endpoint that projects opted-in routes as
    /// agent-callable tools and dispatches `tools/call` through the real
    /// handler pipeline.
    ///
    /// Gated behind the `mcp` feature.
    #[cfg(feature = "mcp")]
    pub mcp: Option<crate::mcp::McpRuntime>,
}

/// Checked variant of [`build_router`] that returns configuration errors
/// instead of panicking.
///
/// # Errors
///
/// Returns [`RouterBuildError`] when router assembly encounters invalid
/// framework configuration, such as an unusable session backend.
pub fn try_build_router(
    route_list: Vec<Route>,
    config: &AutumnConfig,
    state: AppState,
) -> Result<axum::Router, RouterBuildError> {
    let startup_barrier_state = state.clone();
    let router = try_build_router_inner(
        route_list,
        config,
        state,
        RouterContext {
            exception_filters: Vec::new(),
            scoped_groups: Vec::new(),
            merge_routers: Vec::new(),
            nest_routers: Vec::new(),
            custom_layers: Vec::new(),
            error_page_renderer: None,
            session_store: None,
            #[cfg(feature = "openapi")]
            openapi: None,
            #[cfg(feature = "mcp")]
            mcp: None,
        },
    )?;
    Ok(apply_startup_barrier(
        router,
        config,
        &startup_barrier_state,
    ))
}

/// Build a router that includes user-supplied raw Axum routers.
///
/// Like [`build_router`], but also merges and nests additional raw
/// Axum routers. This is primarily useful for integration testing;
/// in production, use [`AppBuilder::merge`](crate::app::AppBuilder::merge) and [`AppBuilder::nest`](crate::app::AppBuilder::nest).
///
/// # Panics
///
/// Panics when framework router assembly encounters invalid configuration.
/// Use [`try_build_router_merged`] to handle configuration errors explicitly.
#[allow(dead_code)]
pub fn build_router_merged(
    route_list: Vec<Route>,
    config: &AutumnConfig,
    state: AppState,
    merge_routers: Vec<axum::Router<AppState>>,
    nest_routers: Vec<(String, axum::Router<AppState>)>,
) -> axum::Router {
    try_build_router_merged(route_list, config, state, merge_routers, nest_routers)
        .unwrap_or_else(|error| panic!("invalid router configuration: {error}"))
}

/// Checked variant of [`build_router_merged`] that returns configuration
/// errors instead of panicking.
///
/// # Errors
///
/// Returns [`RouterBuildError`] when router assembly encounters invalid
/// framework configuration, such as an unusable session backend.
#[allow(dead_code)]
pub fn try_build_router_merged(
    route_list: Vec<Route>,
    config: &AutumnConfig,
    state: AppState,
    merge_routers: Vec<axum::Router<AppState>>,
    nest_routers: Vec<(String, axum::Router<AppState>)>,
) -> Result<axum::Router, RouterBuildError> {
    let startup_barrier_state = state.clone();
    let router = try_build_router_inner(
        route_list,
        config,
        state,
        RouterContext {
            exception_filters: Vec::new(),
            scoped_groups: Vec::new(),
            merge_routers,
            nest_routers,
            custom_layers: Vec::new(),
            error_page_renderer: None,
            session_store: None,
            #[cfg(feature = "openapi")]
            openapi: None,
            #[cfg(feature = "mcp")]
            mcp: None,
        },
    )?;
    Ok(apply_startup_barrier(
        router,
        config,
        &startup_barrier_state,
    ))
}

pub fn try_build_router_inner(
    route_list: Vec<Route>,
    config: &AutumnConfig,
    state: AppState,
    ctx: RouterContext,
) -> Result<axum::Router, RouterBuildError> {
    let router = build_router_pre_state(route_list, config, &state, ctx, None)?;
    Ok(router.with_state(state))
}

/// Prepared MCP exposure carried through `build_router_pre_state`: the mount
/// path, the derived tool catalog, and the optional whole-endpoint auth layer.
#[cfg(feature = "mcp")]
type McpPrepared = (
    String,
    Vec<crate::mcp::McpToolInfo>,
    Option<crate::mcp::McpEndpointLayer>,
);

/// Like [`try_build_router_inner`] but returns `Router<AppState>` before
/// [`with_state`](axum::Router::with_state) is called.  Used by
/// [`try_build_router_with_static_inner`] so that user layers and the static
/// file middleware can be applied to the typed router before state is baked in.
#[allow(clippy::too_many_lines)]
fn build_router_pre_state(
    route_list: Vec<Route>,
    config: &AutumnConfig,
    state: &AppState,
    #[cfg_attr(not(feature = "mcp"), allow(unused_mut))] mut ctx: RouterContext,
    // When custom_layers are extracted from ctx before this call (SSG path),
    // the caller pre-computes the flag so the idempotency selector still sees
    // the real layer list even though ctx.custom_layers is empty.
    opaque_app_layers_override: Option<bool>,
) -> Result<axum::Router<AppState>, RouterBuildError> {
    // Verify registered API versions
    let versions = state.extension::<crate::app::RegisteredApiVersions>();
    let registered_versions: std::collections::HashSet<&str> = versions
        .as_ref()
        .map(|v| v.0.iter().map(|av| av.version.as_str()).collect())
        .unwrap_or_default();

    let check_route_version = |route: &Route| -> Result<(), RouterBuildError> {
        if let Some(version) = route
            .api_version
            .filter(|ver| !registered_versions.contains(*ver))
        {
            return Err(RouterBuildError::UnregisteredApiVersion {
                route_name: route.name.to_string(),
                version: version.to_string(),
            });
        }
        Ok(())
    };

    for route in &route_list {
        check_route_version(route)?;
    }
    for group in &ctx.scoped_groups {
        for route in &group.routes {
            check_route_version(route)?;
        }
    }

    // Fail-fast if an OpenAPI mount path collides with a user or
    // framework GET route — axum panics on overlapping method routes,
    // so surface this as a recoverable error before we start merging.
    #[cfg(feature = "openapi")]
    reject_openapi_path_collisions(
        ctx.openapi.as_ref(),
        &route_list,
        &ctx.scoped_groups,
        &ctx.merge_routers,
        &ctx.nest_routers,
        config,
    )?;

    // Build the OpenAPI spec BEFORE moving the routes into axum, because
    // group_and_mount_routes consumes the Route list.
    #[cfg(feature = "openapi")]
    let openapi_router = build_openapi_router(
        &route_list,
        &ctx.scoped_groups,
        ctx.openapi.as_ref(),
        &config.session.cookie_name,
        versions.as_ref().map_or(&[], |v| v.0.as_slice()),
    )?;

    // Prepare MCP exposure *before* `route_list` is moved into axum below.
    // Validate the mount path up front (a typo like `"mcp"` surfaces as a
    // recoverable error, mirroring the OpenAPI path validation, instead of an
    // axum panic), derive the tool catalog, and carry the optional endpoint
    // auth layer to be applied once the router is assembled.
    #[cfg(feature = "mcp")]
    let mcp_prepared: Option<McpPrepared> = if let Some(rt) = ctx.mcp.take() {
        let path = rt.mount_path.as_str();
        // The mount path must be a single static endpoint: reject empty,
        // non-absolute, doubled-slash, and dynamic (`{capture}` / `{*rest}`)
        // paths so MCP cannot shadow a whole path class and so the exact-path
        // collision preflight reserves the concrete URL it actually matches.
        // Colon-prefixed segments (`/:mcp`, axum 0.7 capture syntax) are also
        // rejected: axum 0.8's `Router::route` panics on them during assembly
        // (`validate_v07_paths`), so catching them here yields the recoverable
        // `InvalidMcpPath` error instead of a startup crash.
        if path.is_empty()
            || !path.starts_with('/')
            || path.contains("//")
            || path.contains('{')
            || path.contains('*')
            || path.split('/').any(|segment| segment.starts_with(':'))
        {
            return Err(RouterBuildError::InvalidMcpPath {
                value: rt.mount_path,
            });
        }
        // The MCP endpoint mounts GET+POST at `mount_path`. If a user, framework,
        // or OpenAPI route already owns that exact path, the later `merge` would
        // panic on overlapping method routes; surface it as a recoverable error
        // first (mirroring the OpenAPI collision preflight).
        reject_mcp_path_collisions(
            path,
            &route_list,
            &ctx.scoped_groups,
            config,
            ctx.openapi.as_ref(),
            &ctx.merge_routers,
            &ctx.nest_routers,
        )?;
        let docs = collect_openapi_docs(&route_list, &ctx.scoped_groups);
        // Pass the app's OpenAPI config (if any) so MCP tool `inputSchema`s
        // reuse the same registered component schemas as the served spec.
        let tools = crate::mcp::derive_tools(&docs, rt.expose_all, ctx.openapi.as_ref());
        Some((rt.mount_path, tools, rt.endpoint_layer))
    } else {
        None
    };

    let idempotency_layers = build_idempotency_layers(config, state)?;
    let opaque_app_layers_present = opaque_app_layers_override
        .unwrap_or_else(|| custom_layers_require_fail_closed_idempotency(&ctx.custom_layers));
    let mut router = group_and_mount_routes(
        route_list,
        idempotency_layers.as_ref(),
        opaque_app_layers_present,
        state,
    );

    let dev_reload_enabled = dev::is_enabled_with_env(&crate::config::OsEnv);

    router = mount_framework_routes(router, config, dev_reload_enabled);

    let (mounted_probe_paths, router_with_probes) = mount_probe_endpoints(router, config);
    router = router_with_probes;

    router = mount_actuator_endpoints(router, config, &mounted_probe_paths)?;

    #[cfg(feature = "openapi")]
    if let Some(openapi_router) = openapi_router {
        router = router.merge(openapi_router);
    }

    // Static file serving from project's static/ directory.
    // Fingerprinted assets (e.g. `autumn.a1b2c3d4.css`) are served with
    // `Cache-Control: public, max-age=31536000, immutable`; all other static
    // files use the default browser policy.
    let env = crate::config::OsEnv;
    let static_dir = crate::app::project_dir("static", &env);
    router = router.nest_service("/static", tower_http::services::ServeDir::new(&static_dir));
    router = router.layer(axum::middleware::from_fn(asset_cache_control));

    router = mount_scoped_groups(
        router,
        ctx.scoped_groups,
        idempotency_layers.as_ref(),
        state,
    );

    router = mount_raw_routers(
        router,
        ctx.merge_routers,
        ctx.nest_routers,
        idempotency_layers.as_ref(),
    );

    router = apply_middleware(
        router,
        config,
        state,
        ctx.exception_filters,
        ctx.custom_layers,
        ctx.error_page_renderer,
        ctx.session_store,
    )?;

    if dev_reload_enabled {
        router = router
            .layer(axum::middleware::from_fn(dev::disable_static_cache))
            .layer(axum::middleware::from_fn(dev::inject_live_reload));
    }

    // Dev request inspector: mount UI and apply recording middleware.
    // Only active when profile = "dev"; returns 404 for all other profiles.
    let is_dev_profile = matches!(config.profile.as_deref(), Some("dev" | "development"));
    if is_dev_profile {
        // Capture the matched route pattern for the dev error overlay.
        // Applied as a route_layer so MatchedPath is already set when this runs.
        router = router.route_layer(axum::middleware::from_fn(
            crate::middleware::dev::capture_matched_path_middleware,
        ));
    }
    if is_dev_profile {
        let buf = crate::inspector::InspectorBuffer::new(config.dev.inspector_capacity);
        let inspector_path = config.dev.inspector_path.clone();
        let threshold = config.dev.inspector_n_plus_one_threshold;

        // Mount the inspector UI routes.
        router = router.merge(crate::inspector::inspector_router(
            buf.clone(),
            &inspector_path,
        ));
        tracing::debug!(
            path = %inspector_path,
            "Mounted dev request inspector"
        );

        // Apply the recording middleware (outermost layer so it captures
        // all routes). Self-excludes inspector's own path prefix.
        let layer = crate::inspector::InspectorLayer::new(buf, threshold, inspector_path)
            .with_session_cookie_name(config.session.cookie_name.clone());
        router = router.layer(layer);
    }

    #[cfg(feature = "oauth2")]
    let router = router.layer(axum::middleware::from_fn_with_state(
        state.clone(),
        http_interceptor_middleware,
    ));

    // Mount the MCP endpoint last so its dispatch target — a clone of the
    // fully-assembled router with state applied — traverses the exact same
    // routes, layers, and middleware an HTTP request would. The clone is
    // taken *before* the MCP route is added, so `tools/call` never recurses
    // into the MCP endpoint itself.
    //
    // KNOWN LIMITATION (static/ISR mode): when an app has a `dist` manifest,
    // `try_build_router_with_static_inner` drains the global custom layers
    // (`AppBuilder::layer`) and applies them *outside* the static-first
    // middleware — i.e. after this builder returns. This dispatch clone is
    // built here, before that, so a `tools/call` replay does not pass through
    // those outer custom layers (it would in the non-static path, where they
    // are applied via `apply_middleware` before the clone is taken). Route-level
    // guards and `#[secured]` dispatch through this clone and so still apply;
    // only hand-rolled global `.layer(...)` middleware is skipped for MCP calls
    // in static mode. Restoring full parity would require making custom-layer
    // appliers re-usable (they are `FnOnce` today), so this is left documented
    // rather than fixed for that narrow combination.
    #[cfg(feature = "mcp")]
    let router = if let Some((mount_path, tools, endpoint_layer)) = mcp_prepared {
        let dispatch = router.clone().with_state(state.clone());
        // For header-based tenancy, forward the configured tenant header on
        // dispatch so tenant-scoped tools resolve the same tenant a direct HTTP
        // call would. Other sources key off already-forwarded headers/Host.
        let tenant_header = (config.tenancy.enabled && config.tenancy.source == "header")
            .then(|| config.tenancy.header_name.clone());
        let wiring = crate::mcp::McpWiring {
            // The CORS config drives the cross-origin Origin allowlist and the
            // endpoint's own OPTIONS preflight responses.
            cors: config.cors.clone(),
            // The same-origin shortcut is gated on the app's trusted-Host
            // policy so it can't be abused for DNS rebinding.
            trusted_hosts: TrustedHostPolicy::from_config(config),
            tenant_header,
            // Forward the configured CSRF header (default `x-csrf-token`) so
            // customized CsrfConfig::token_header deployments work via MCP.
            csrf_header: config.security.csrf.token_header.to_ascii_lowercase(),
            // The envelope is rate-limited below iff rate limiting is enabled;
            // when so, a tools/call is counted there and its replay is exempted
            // from the dispatch pipeline's limiter (avoiding double-counting).
            envelope_rate_limited: config.security.rate_limit.enabled,
        };
        let mut mcp_router =
            crate::mcp::build_mcp_router(&mount_path, tools, dispatch, wiring, endpoint_layer);
        // Gate the envelope under maintenance mode, mirroring the layer
        // `apply_middleware` installs for direct routes. The `/mcp` router is
        // merged after that layer, so without this `initialize`/`tools/list`
        // would keep serving the tool catalog during maintenance (the
        // `tools/call` replay is already gated — the dispatch clone carries the
        // layer). Applied before the `TrustedProxiesLayer` below so it is inner
        // to it: the maintenance IP allow-list then reads the proxy-resolved
        // identity, exactly as the direct-route layer does, instead of a
        // spoofable raw `X-Forwarded-For`.
        mcp_router = mcp_router.layer(build_maintenance_layer(config, state));
        // Stamp `ResolvedClientIdentity` on the *outer* `/mcp` request too. The
        // MCP route is merged after `apply_middleware`, so the centralized
        // `TrustedProxiesLayer` above does not wrap it; without this, the
        // endpoint's own DNS-rebinding / same-origin check would fall back to
        // the raw (possibly proxy-rewritten) `Host` and wrongly 403 a
        // same-origin browser client behind a TLS-terminating proxy. The
        // dispatch clone already carries its own copy of this layer.
        mcp_router = apply_trusted_proxies_middleware(mcp_router, config);
        // The MCP route is merged after `apply_upload_middleware`, so axum's
        // built-in 2 MiB `DefaultBodyLimit` — not the app's configured limit —
        // would otherwise govern the `tools/call` envelope's `Bytes` body. Apply
        // the same cap a direct JSON endpoint gets so larger-but-valid tool
        // payloads aren't rejected before dispatch.
        mcp_router = mcp_router.layer(axum::extract::DefaultBodyLimit::max(
            config.security.upload.max_request_size_bytes,
        ));
        // Rate-limit the envelope so `secure_mcp` auth rejections — which never
        // reach the dispatch clone's limiter — are throttled (credential
        // guessing otherwise consumes no per-client bucket). A successful
        // tools/call is counted once here and replayed with `RateLimitExempt`,
        // so it isn't double-counted by the dispatch pipeline's own limiter.
        // No-op when rate limiting is disabled (matching `envelope_rate_limited`).
        //
        // KNOWN LIMITATION (key_strategy = AuthenticatedPrincipal + session
        // auth): the envelope keys on the IP fallback because the session layer
        // — which `populate_rate_limit_principal` reads the principal from — is
        // applied inside `apply_middleware` and does not wrap this late-merged
        // router, so no `RateLimitPrincipal` is resolved here. Because the
        // tools/call replay is then exempted, the dispatch clone's
        // principal-aware limiter is skipped too, so a session-authenticated MCP
        // call does not consume the same per-user bucket a direct request would
        // (the framework only derives `RateLimitPrincipal` from the session).
        mcp_router = apply_rate_limit_middleware(mcp_router, config, state);
        // Security headers (HSTS/CSP/etc.), mirroring the `SecurityHeadersLayer`
        // `apply_middleware` installs for direct routes. The `/mcp` router is
        // merged after that layer, so without this the envelope's responses —
        // `initialize`/`tools/list`, auth 401/403, and rate-limit 429 — would
        // ship without the configured `security.headers` every direct route
        // carries. (The `tools/call` replay's headers are produced on the
        // dispatch clone and discarded when `serve_mcp` rebuilds the JSON-RPC
        // response, so the envelope needs its own copy.)
        mcp_router = mcp_router.layer(crate::security::SecurityHeadersLayer::from_config(
            &config.security.headers,
        ));
        // CORS grant outermost so every response — including auth 401/403, the
        // 413 body-limit rejection, and a 429 from the limiter above, all
        // produced before `serve_mcp` runs — is readable by an allowlisted
        // browser client instead of being masked as a CORS failure.
        mcp_router = crate::mcp::apply_mcp_cors_layer(mcp_router, &config.cors);
        router.merge(mcp_router)
    } else {
        router
    };

    Ok(router)
}

/// Parse `{name}` captures from a route path.
///
/// Mirrors the compile-time extractor in `autumn_macros::api_doc` so
/// runtime spec assembly (which sees scope prefixes that the macro
/// never does) produces consistent parameter lists.
#[cfg(feature = "openapi")]
pub fn extract_path_params(path: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut remaining = path;

    while let Some(start) = remaining.find('{') {
        let after_brace = &remaining[start + 1..];
        let Some(end_rel) = after_brace.find('}') else {
            break;
        };

        let inner = &after_brace[..end_rel];
        let name = inner.split(':').next().unwrap_or(inner).trim();
        if !name.is_empty() {
            out.push(name.to_owned());
        }

        remaining = &after_brace[end_rel + 1..];
    }

    out
}

/// Handler that dynamically constructs the `OpenAPI` specification document per request
/// so deprecation and sunset statuses do not go stale.
#[cfg(feature = "openapi")]
async fn serve_openapi_spec(
    state: axum::extract::State<AppState>,
    axum::extract::Extension(config): axum::extract::Extension<
        std::sync::Arc<crate::openapi::OpenApiConfig>,
    >,
    axum::extract::Extension(docs): axum::extract::Extension<
        std::sync::Arc<Vec<crate::openapi::ApiDoc>>,
    >,
) -> impl axum::response::IntoResponse {
    use axum::response::IntoResponse;
    let refs: Vec<&crate::openapi::ApiDoc> = docs.iter().collect();
    let now = state.clock().now();
    let spec = crate::openapi::generate_spec_at(&config, &refs, now);
    let spec_json = serde_json::to_string_pretty(&spec)
        .unwrap_or_else(|e| format!("{{\"error\": \"failed to serialize spec: {e}\"}}"));
    (
        [(http::header::CONTENT_TYPE, "application/json")],
        spec_json,
    )
        .into_response()
}

/// Build an Axum sub-router that serves the generated `OpenAPI` document
/// and (optionally) a Swagger UI HTML page.
///
/// Returns `None` when `OpenAPI` generation is disabled, i.e. the user
/// never called [`AppBuilder::openapi`](crate::app::AppBuilder::openapi).
///
/// The spec is dynamically generated on request to prevent lifecycle status from going stale.
#[cfg(feature = "openapi")]
fn build_openapi_router(
    route_list: &[Route],
    scoped_groups: &[ScopedGroup],
    openapi_config: Option<&crate::openapi::OpenApiConfig>,
    session_cookie_name: &str,
    api_versions: &[crate::app::ApiVersion],
) -> Result<Option<axum::Router<AppState>>, RouterBuildError> {
    let Some(config) = openapi_config else {
        return Ok(None);
    };
    let mut config = config.clone();
    session_cookie_name.clone_into(&mut config.session_cookie_name);
    config.api_versions = api_versions.to_vec();

    // Validate user-provided paths up front so a typo like
    // `"openapi.json"` surfaces as a recoverable RouterBuildError
    // rather than an axum panic (`Paths must start with a '/'`).
    validate_route_path("openapi_json_path", &config.openapi_json_path)?;
    if let Some(path) = &config.swagger_ui_path {
        validate_route_path("swagger_ui_path", path)?;
        // Registering two GET handlers on the same path would cause an
        // axum `Route::route` panic, so reject collisions as a
        // configuration error instead.
        if path == &config.openapi_json_path {
            return Err(RouterBuildError::DuplicateOpenApiPath { path: path.clone() });
        }
    }

    let docs = collect_openapi_docs(route_list, scoped_groups);

    let json_path = config.openapi_json_path.clone();
    let swagger_path = config.swagger_ui_path.clone();
    let title = config.title.clone();

    let mut router = axum::Router::<AppState>::new()
        .route(&json_path, axum::routing::get(serve_openapi_spec))
        .layer(axum::extract::Extension(std::sync::Arc::new(
            config.clone(),
        )))
        .layer(axum::extract::Extension(std::sync::Arc::new(docs)));

    if let Some(path) = swagger_path {
        router = mount_swagger_ui_routes(router, &path, &title, &json_path);
    }

    tracing::debug!(
        openapi_json = %json_path,
        swagger_ui = ?config.swagger_ui_path,
        swagger_ui_version = crate::openapi::SWAGGER_UI_VERSION,
        "Mounted OpenAPI endpoints"
    );

    Ok(Some(router))
}

/// Join a nest/scope prefix with a child route path, matching
/// `axum::Router::nest` normalization.
///
/// `nest("/api", r)` mounts r's `/` at `/api` (not `/api/`), and any
/// other child path `/foo` at `/api/foo`. The collision check and the
/// path emitted into the `OpenAPI` spec must use the same shape or we
/// end up either missing real collisions (the reviewer's case:
/// `/api` + `/` recorded as `/api/` but axum routes it at `/api`) or
/// generating a spec whose URLs don't match what axum serves.
#[allow(dead_code)]
pub fn join_nested_path(prefix: &str, child: &str) -> String {
    let prefix_trimmed = prefix.trim_end_matches('/');
    if child == "/" || child.is_empty() {
        if prefix_trimmed.is_empty() {
            "/".to_owned()
        } else {
            prefix_trimmed.to_owned()
        }
    } else if child.starts_with('/') {
        format!("{prefix_trimmed}{child}")
    } else {
        format!("{prefix_trimmed}/{child}")
    }
}

/// Shared validator for user-supplied `OpenAPI` mount paths.
///
/// Catches the common typos that would otherwise manifest as axum
/// panics inside `Router::route` at startup:
///
/// * empty or missing leading slash,
/// * unbalanced `{` / `}` pairs,
/// * any `{…}` / `{*…}` capture or wildcard syntax (the mount points
///   are static endpoints — a user that needs templated paths shouldn't
///   be using this field), and
/// * any `*` wildcard character (axum treats these as catch-alls).
///
/// The check intentionally stays conservative: rejecting a few valid-
/// but-weird paths is far better than letting a typo like
/// `"openapi.json"` or `"/docs/{id}"` crash boot.
#[cfg(feature = "openapi")]
fn validate_route_path(field: &'static str, value: &str) -> Result<(), RouterBuildError> {
    let reject = |reason_fragment: &str| {
        Err(RouterBuildError::InvalidOpenApiPath {
            field,
            value: format!("{value:?} {reason_fragment}"),
        })
    };

    if value.is_empty() {
        return reject("(must be non-empty)");
    }
    if !value.starts_with('/') {
        return reject("(must start with '/')");
    }
    // Double-slash inside the path is almost always a typo (e.g.
    // `//v3/api-docs`) and axum normalizes it away on match, so
    // treating it as invalid avoids surprising "route can't be hit"
    // reports in the field.
    if value.contains("//") {
        return reject("(must not contain '//')");
    }

    let mut depth: i32 = 0;
    for ch in value.chars() {
        match ch {
            '{' => depth += 1,
            '}' => {
                depth -= 1;
                if depth < 0 {
                    return reject("(unbalanced '}')");
                }
            }
            '*' => return reject("(wildcard '*' is not allowed in an OpenAPI mount path)"),
            _ => {}
        }
    }
    if depth != 0 {
        return reject("(unbalanced '{')");
    }
    if value.contains('{') {
        return reject("(OpenAPI mount paths must be static; `{…}` captures are not allowed)");
    }
    Ok(())
}

/// Gather every path that a `GET` (or `WS`, which mounts as a `GET`) handler
/// will already own by the time a late-merged sub-router (`OpenAPI` or MCP) is
/// added: user routes (top-level + scoped groups) plus framework-mounted `GET`s
/// (probes, actuator, htmx assets, dev live-reload, mail previews). Shared by
/// the `OpenAPI` and MCP mount-collision preflights so they stay in lockstep.
#[cfg(feature = "openapi")]
fn collect_claimed_get_paths(
    route_list: &[Route],
    scoped_groups: &[ScopedGroup],
    config: &AutumnConfig,
) -> std::collections::HashSet<String> {
    let mut claimed: std::collections::HashSet<String> = std::collections::HashSet::new();
    for route in route_list {
        if route.method == http::Method::GET || route.method.as_str() == "WS" {
            claimed.insert(route.path.to_owned());
        }
    }
    for group in scoped_groups {
        for route in &group.routes {
            if route.method == http::Method::GET || route.method.as_str() == "WS" {
                claimed.insert(join_nested_path(&group.prefix, route.path));
            }
        }
    }
    // Framework-mounted GETs.
    claimed.insert(config.health.path.clone());
    claimed.insert(config.health.live_path.clone());
    claimed.insert(config.health.ready_path.clone());
    claimed.insert(config.health.startup_path.clone());
    for path in crate::actuator::actuator_endpoint_paths(
        &config.actuator.prefix,
        config.actuator.sensitive,
        config.actuator.prometheus,
    ) {
        claimed.insert(path);
    }
    #[cfg(feature = "htmx")]
    {
        claimed.insert(crate::htmx::HTMX_JS_PATH.to_owned());
        claimed.insert(crate::htmx::HTMX_CSRF_JS_PATH.to_owned());
        claimed.insert(crate::htmx::AUTUMN_WIDGETS_JS_PATH.to_owned());
    }
    // Dev live-reload endpoints are only mounted when the env vars
    // that enable them are set, but reserving the paths regardless
    // makes the error message deterministic across dev/prod.
    if dev::is_enabled_with_env(&crate::config::OsEnv) {
        claimed.insert(dev::LIVE_RELOAD_PATH.to_owned());
        claimed.insert(dev::LIVE_RELOAD_SCRIPT_PATH.to_owned());
    }
    // The dev request inspector merges a GET at `config.dev.inspector_path`
    // (only under the dev profile), before the late-merged OpenAPI/MCP routers.
    // Reserve it so a mount path colliding with the inspector surfaces a
    // recoverable error instead of panicking in `router.merge`.
    if matches!(config.profile.as_deref(), Some("dev" | "development")) {
        claimed.insert(config.dev.inspector_path.clone());
    }
    #[cfg(feature = "mail")]
    if config
        .mail
        .preview_routes_enabled(config.profile.as_deref())
    {
        claimed.insert(crate::mail::MAIL_PREVIEW_PATH.to_owned());
        claimed.insert("/_autumn/mail/messages/{message_id}".to_owned());
        claimed.insert("/_autumn/mail/previews/{mailer}/{method}".to_owned());
    }
    claimed
}

/// Reject an MCP mount path that overlaps with a route already owning that
/// path. The MCP endpoint mounts `GET`+`POST` at `mount_path`; merging it would
/// panic in axum if a `GET` (any user/framework route) or `POST` (a user route)
/// already lives there. We surface a recoverable
/// [`RouterBuildError::McpPathCollision`] instead, reusing the same claimed-GET
/// gathering as the `OpenAPI` preflight so framework routes (health/probe,
/// actuator, htmx, dev) are covered too — e.g. `mount_mcp(config.health.path)`.
/// The configured `OpenAPI` JSON/UI/asset paths (which merge as `GET`s before
/// the MCP router) are checked as well.
#[cfg(feature = "mcp")]
fn reject_mcp_path_collisions(
    mount_path: &str,
    route_list: &[Route],
    scoped_groups: &[ScopedGroup],
    config: &AutumnConfig,
    openapi: Option<&crate::openapi::OpenApiConfig>,
    merge_routers: &[axum::Router<AppState>],
    nest_routers: &[(String, axum::Router<AppState>)],
) -> Result<(), RouterBuildError> {
    let mut claimed_get = collect_claimed_get_paths(route_list, scoped_groups, config);
    // The OpenAPI JSON/Swagger-UI endpoints (and UI assets) merge as GETs
    // before the MCP router, so a mount path colliding with them would panic.
    if let Some(openapi) = openapi {
        claimed_get.insert(openapi.openapi_json_path.clone());
        if let Some(ui_path) = &openapi.swagger_ui_path {
            claimed_get.insert(ui_path.clone());
            claimed_get.extend(crate::openapi::swagger_ui_asset_paths(ui_path));
        }
    }
    if claimed_get.contains(mount_path) {
        return Err(RouterBuildError::McpPathCollision {
            path: mount_path.to_owned(),
            method: "GET".to_owned(),
        });
    }
    // POST handlers come from user routes (framework routes are GETs).
    let post_owns_path = route_list
        .iter()
        .any(|route| route.method == http::Method::POST && route.path == mount_path)
        || scoped_groups.iter().any(|group| {
            group.routes.iter().any(|route| {
                route.method == http::Method::POST
                    && join_nested_path(&group.prefix, route.path) == mount_path
            })
        });
    if post_owns_path {
        return Err(RouterBuildError::McpPathCollision {
            path: mount_path.to_owned(),
            method: "POST".to_owned(),
        });
    }
    // A nest prefix P owns every route under P (`/P/...`), and those raw routers
    // are mounted before the MCP router. A mount path equal to P or falling
    // under `P/` would be shadowed by (or panic against) the nested router, so
    // reject it up front — mirroring the OpenAPI nest-collision preflight. The
    // framework unconditionally nests the static-file service at `/static`, so
    // reserve that prefix too.
    let nest_prefixes = nest_routers
        .iter()
        .map(|(prefix, _)| prefix.as_str())
        .chain(std::iter::once("/static"));
    for prefix in nest_prefixes {
        let prefix_slash = format!("{prefix}/");
        if mount_path == prefix || mount_path.starts_with(&prefix_slash) {
            return Err(RouterBuildError::McpPathCollision {
                path: mount_path.to_owned(),
                method: "nested router".to_owned(),
            });
        }
    }
    // Raw merged routers are opaque — axum does not expose their route table —
    // so an overlapping handler there would still panic at merge time. Warn so
    // operators know the check can't cover this case (mirrors the OpenAPI one).
    if !merge_routers.is_empty() {
        tracing::warn!(
            mcp_mount_path = %mount_path,
            merged_routers = merge_routers.len(),
            "MCP mount collision check skipped for AppBuilder::merge routers: \
             axum does not expose their route table, so an overlapping handler \
             will still panic at startup. Choose an MCP mount path that doesn't \
             overlap with any merged router's handlers."
        );
    }
    Ok(())
}

/// Reject `OpenAPI` mount paths that overlap with an existing `GET`
/// handler.
///
/// `axum::Router::merge` panics when the merged routers have method
/// handlers on the same path (e.g. two `GET` handlers on
/// `/v3/api-docs`). We surface that as a recoverable
/// [`RouterBuildError::OpenApiPathCollision`] so misconfiguration
/// produces an actionable error instead of a crash on startup.
///
/// We check against:
/// * user routes (top-level + scoped groups) that will be mounted
///   before the `OpenAPI` sub-router merges in,
/// * framework `GET`s: probes, actuator, htmx assets, and dev
///   live-reload when enabled,
/// * nest prefixes from [`AppBuilder::nest`](crate::app::AppBuilder::nest)
///   when the `OpenAPI` path falls under one.
///
/// Raw routers passed to [`AppBuilder::merge`](crate::app::AppBuilder::merge)
/// cannot be introspected — axum does not expose their route table.
/// We emit a `tracing::warn!` so operators know the check is
/// incomplete in that case.
#[cfg(feature = "openapi")]
fn reject_openapi_path_collisions(
    openapi_config: Option<&crate::openapi::OpenApiConfig>,
    route_list: &[Route],
    scoped_groups: &[ScopedGroup],
    merge_routers: &[axum::Router<AppState>],
    nest_routers: &[(String, axum::Router<AppState>)],
    config: &AutumnConfig,
) -> Result<(), RouterBuildError> {
    let Some(openapi) = openapi_config else {
        return Ok(());
    };

    // Gather every path a GET (or WS, which mounts as GET) will already
    // own by the time we merge.
    let claimed = collect_claimed_get_paths(route_list, scoped_groups, config);

    check_openapi_path_against(
        "openapi_json_path",
        &openapi.openapi_json_path,
        &claimed,
        nest_routers,
    )?;
    if let Some(path) = &openapi.swagger_ui_path {
        check_openapi_path_against("swagger_ui_path", path, &claimed, nest_routers)?;
        let mut claimed_with_openapi = claimed;
        claimed_with_openapi.insert(openapi.openapi_json_path.clone());
        for asset_path in crate::openapi::swagger_ui_asset_paths(path) {
            check_openapi_path_against(
                "swagger_ui_path",
                &asset_path,
                &claimed_with_openapi,
                nest_routers,
            )?;
        }
    }

    // Raw merged routers are opaque — we can't inspect their route
    // tables through the axum API. Warn instead of failing so users
    // know the check doesn't cover this code path.
    if !merge_routers.is_empty() {
        tracing::warn!(
            openapi_json_path = %openapi.openapi_json_path,
            swagger_ui_path = ?openapi.swagger_ui_path,
            merged_routers = merge_routers.len(),
            "OpenAPI mount collision check skipped for AppBuilder::merge routers: \
             axum does not expose their route table, so overlapping GET handlers \
             will still panic at startup. Choose OpenAPI paths that don't overlap \
             with any merged router's handlers."
        );
    }

    Ok(())
}

/// Evaluate a single `OpenAPI` path against the claimed-path set plus
/// any nest prefixes. Returns an `OpenApiPathCollision` error on
/// collision.
#[cfg(feature = "openapi")]
fn check_openapi_path_against(
    field: &'static str,
    path: &str,
    claimed: &std::collections::HashSet<String>,
    nest_routers: &[(String, axum::Router<AppState>)],
) -> Result<(), RouterBuildError> {
    if claimed.contains(path) {
        return Err(RouterBuildError::OpenApiPathCollision {
            field,
            path: path.to_owned(),
        });
    }
    // A nest prefix P owns every route under P (`/P/...`), so any
    // OpenAPI path that equals P or starts with `P/` will either
    // panic on merge (exact match) or nest inside the user's router
    // (where axum routing semantics decide which handler wins).
    // Reject both cases so the spec endpoint can't silently vanish.
    for (prefix, _) in nest_routers {
        let prefix_slash = format!("{prefix}/");
        if path == prefix || path.starts_with(&prefix_slash) {
            return Err(RouterBuildError::OpenApiPathCollision {
                field,
                path: path.to_owned(),
            });
        }
    }
    Ok(())
}

fn group_and_mount_routes(
    route_list: Vec<Route>,
    idempotency_layers: Option<&BuiltIdempotencyLayers>,
    opaque_app_layers_present: bool,
    state: &AppState,
) -> axum::Router<AppState> {
    // Group routes by path so multiple methods on the same path
    // (e.g. GET /admin + POST /admin) are merged into a single
    // MethodRouter. Axum 0.7+ panics if .route() is called twice
    // with the same path — merging avoids this.
    let mut grouped: indexmap::IndexMap<&str, axum::routing::MethodRouter<AppState>> =
        indexmap::IndexMap::new();
    for route in &route_list {
        tracing::debug!(
            method = %route.method,
            path = route.path,
            name = route.name,
            "Mounted route"
        );
    }
    for route in route_list {
        let selected_layer = idempotency_layers
            .map(|layers| idempotency_layer_for_route(&route, layers, opaque_app_layers_present));
        let mut handler = route.handler;
        if let Some(layer) = selected_layer {
            handler = handler.layer(layer.clone());
        }
        if let Some(version) = route.api_version {
            handler = handler.layer(axum::middleware::from_fn_with_state(
                state.clone(),
                api_versioning_middleware,
            ));
            handler = handler.layer(axum::Extension(RouteVersionMetadata {
                version: version.to_string(),
                sunset_opt_out: route.sunset_opt_out,
                secured: route.api_doc.secured,
                required_roles: route.api_doc.required_roles,
                has_policy: route.api_doc.has_policy,
            }));
        }
        grouped
            .entry(route.path)
            .and_modify(|existing| {
                *existing = std::mem::take(existing).merge(handler.clone());
            })
            .or_insert(handler);
    }

    let mut router = axum::Router::new();
    for (path, method_router) in grouped {
        router = router.route(path, method_router);
    }
    router
}

const fn idempotency_layer_for_route<'a>(
    route: &Route,
    layers: &'a BuiltIdempotencyLayers,
    opaque_app_layers_present: bool,
) -> &'a IdempotencyLayer {
    if opaque_app_layers_present {
        &layers.manual
    } else if route_uses_generated_replay_stop(route) {
        &layers.route
    } else {
        &layers.manual
    }
}

const fn route_uses_generated_replay_stop(route: &Route) -> bool {
    matches!(
        route.idempotency,
        crate::route::RouteIdempotency::ReplayThroughInner
    )
}

fn custom_layers_require_fail_closed_idempotency(
    custom_layers: &[crate::app::CustomLayerRegistration],
) -> bool {
    custom_layers
        .iter()
        .any(|registered| !is_idempotency_transparent_app_layer(registered))
}

fn is_idempotency_transparent_app_layer(registered: &crate::app::CustomLayerRegistration) -> bool {
    registered
        .type_name
        .starts_with("autumn_web::session::SessionLayer<")
        || registered
            .type_name
            .starts_with("autumn::session::SessionLayer<")
        || registered.type_id
            == std::any::TypeId::of::<crate::session::SessionLayer<crate::session::MemoryStore>>()
        || is_i18n_bundle_extension_layer(registered.type_id)
}

#[cfg(feature = "i18n")]
fn is_i18n_bundle_extension_layer(type_id: std::any::TypeId) -> bool {
    type_id == std::any::TypeId::of::<axum::Extension<Arc<crate::i18n::Bundle>>>()
}

#[cfg(not(feature = "i18n"))]
const fn is_i18n_bundle_extension_layer(_type_id: std::any::TypeId) -> bool {
    false
}

#[cfg_attr(not(feature = "mail"), allow(unused_variables))]
#[allow(clippy::cognitive_complexity)]
fn mount_framework_routes(
    mut router: axum::Router<AppState>,
    config: &AutumnConfig,
    dev_reload_enabled: bool,
) -> axum::Router<AppState> {
    #[cfg(not(feature = "mail"))]
    let _ = config;

    // Framework-provided routes
    #[cfg(feature = "htmx")]
    {
        router = router.route(crate::htmx::HTMX_JS_PATH, axum::routing::get(htmx_handler));
        router = router.route(
            crate::htmx::HTMX_CSRF_JS_PATH,
            axum::routing::get(htmx_csrf_handler),
        );
        router = router.route(
            crate::htmx::AUTUMN_WIDGETS_JS_PATH,
            axum::routing::get(autumn_widgets_handler),
        );
        tracing::debug!(
            method = "GET",
            path = crate::htmx::HTMX_JS_PATH,
            name = format!("htmx {}", crate::htmx::HTMX_VERSION),
            "Mounted route"
        );
        tracing::debug!(
            method = "GET",
            path = crate::htmx::HTMX_CSRF_JS_PATH,
            name = "htmx csrf helper",
            "Mounted route"
        );
        tracing::debug!(
            method = "GET",
            path = crate::htmx::AUTUMN_WIDGETS_JS_PATH,
            name = "autumn widget runtime",
            "Mounted route"
        );
    }

    if dev_reload_enabled {
        router = router.route(
            dev::LIVE_RELOAD_PATH,
            axum::routing::get(dev::live_reload_state_handler),
        );
        router = router.route(
            dev::LIVE_RELOAD_SCRIPT_PATH,
            axum::routing::get(dev::live_reload_script_handler),
        );
        tracing::debug!(
            state_path = dev::LIVE_RELOAD_PATH,
            script_path = dev::LIVE_RELOAD_SCRIPT_PATH,
            "Mounted dev live reload endpoints"
        );
    }

    #[cfg(feature = "mail")]
    if config
        .mail
        .preview_routes_enabled(config.profile.as_deref())
    {
        router = router.merge(crate::mail::mail_preview_router(
            config.mail.file_dir.clone(),
        ));
        tracing::debug!(
            path = crate::mail::MAIL_PREVIEW_PATH,
            "Mounted dev mail preview endpoints"
        );
    }

    router
}

fn mount_probe_endpoints<S>(
    mut router: axum::Router<S>,
    config: &AutumnConfig,
) -> (std::collections::HashSet<String>, axum::Router<S>)
where
    S: Clone + Send + Sync + 'static,
    AppState: axum::extract::FromRef<S>,
{
    // Probe endpoints (auto-mounted)
    let mut mounted_probe_paths = std::collections::HashSet::new();

    if mounted_probe_paths.insert(config.health.live_path.clone()) {
        router = router.route(
            &config.health.live_path,
            axum::routing::get(crate::probe::live_handler::<AppState>),
        );
    }
    if mounted_probe_paths.insert(config.health.ready_path.clone()) {
        router = router.route(
            &config.health.ready_path,
            axum::routing::get(crate::probe::ready_handler::<AppState>),
        );
    }
    if mounted_probe_paths.insert(config.health.startup_path.clone()) {
        router = router.route(
            &config.health.startup_path,
            axum::routing::get(crate::probe::startup_handler::<AppState>),
        );
    }
    if mounted_probe_paths.insert(config.health.path.clone()) {
        router = router.route(
            &config.health.path,
            axum::routing::get(crate::health::handler::<AppState>),
        );
    }
    tracing::debug!(
        health = %config.health.path,
        live = %config.health.live_path,
        ready = %config.health.ready_path,
        startup = %config.health.startup_path,
        "Mounted probe endpoints"
    );

    (mounted_probe_paths, router)
}

fn mount_actuator_endpoints(
    mut router: axum::Router<AppState>,
    config: &AutumnConfig,
    mounted_probe_paths: &std::collections::HashSet<String>,
) -> Result<axum::Router<AppState>, RouterBuildError> {
    // Actuator endpoints
    let actuator_sensitive = config.actuator.sensitive;
    let actuator_prometheus = config.actuator.prometheus;
    let actuator_paths = crate::actuator::actuator_endpoint_paths(
        &config.actuator.prefix,
        actuator_sensitive,
        actuator_prometheus,
    );
    if let Some(path) = actuator_paths
        .iter()
        .find(|path| mounted_probe_paths.contains(path.as_str()))
    {
        return Err(RouterBuildError::FrameworkRouteOverlap {
            path: path.clone(),
            existing: "probe endpoint",
            incoming: "actuator endpoint",
        });
    }
    router = router.merge(crate::actuator::actuator_router_with_prefix(
        &config.actuator.prefix,
        actuator_sensitive,
        actuator_prometheus,
    ));
    tracing::debug!(
        sensitive = actuator_sensitive,
        prometheus = actuator_prometheus,
        prefix = %config.actuator.prefix,
        "Mounted actuator endpoints"
    );
    Ok(router)
}

fn mount_scoped_groups(
    mut router: axum::Router<AppState>,
    scoped_groups: Vec<ScopedGroup>,
    idempotency_layers: Option<&BuiltIdempotencyLayers>,
    state: &AppState,
) -> axum::Router<AppState> {
    // Mount scoped route groups (each with its own middleware layer).
    for group in scoped_groups {
        let mut sub_router = axum::Router::new();
        for route in group.routes {
            tracing::debug!(
                method = %route.method,
                path = route.path,
                name = route.name,
                scope = %group.prefix,
                "Mounted scoped route"
            );
            // Scoped groups are wrapped by an opaque user-provided layer after
            // the route handlers are built. The idempotency storage key cannot
            // know whether that layer authorizes, audits, or resolves tenant
            // state from non-whitelisted headers/extensions, so cached hits
            // fail closed instead of replaying through a generated stop inside
            // the scoped route.
            let selected_layer = idempotency_layers.map(|layers| &layers.manual);
            let mut handler = route.handler;
            if let Some(layer) = selected_layer {
                handler = handler.layer(layer.clone());
            }
            if let Some(version) = route.api_version {
                handler = handler.layer(axum::middleware::from_fn_with_state(
                    state.clone(),
                    api_versioning_middleware,
                ));
                handler = handler.layer(axum::Extension(RouteVersionMetadata {
                    version: version.to_string(),
                    sunset_opt_out: route.sunset_opt_out,
                    secured: route.api_doc.secured,
                    required_roles: route.api_doc.required_roles,
                    has_policy: route.api_doc.has_policy,
                }));
            }
            sub_router = sub_router.route(route.path, handler);
        }
        sub_router = (group.apply_layer)(sub_router);
        router = router.nest(&group.prefix, sub_router);
    }
    router
}

fn mount_raw_routers(
    mut router: axum::Router<AppState>,
    merge_routers: Vec<axum::Router<AppState>>,
    nest_routers: Vec<(String, axum::Router<AppState>)>,
    idempotency_layers: Option<&BuiltIdempotencyLayers>,
) -> axum::Router<AppState> {
    // Merge user-supplied raw Axum routers (escape hatch).
    // Merged after annotated routes so annotated routes take precedence.
    for raw_router in merge_routers {
        tracing::debug!("Merged raw Axum router");
        let raw_router = if let Some(layers) = idempotency_layers {
            raw_router.layer(layers.manual.clone())
        } else {
            raw_router
        };
        router = router.merge(raw_router);
    }

    // Nest user-supplied raw Axum routers under path prefixes.
    for (prefix, raw_router) in nest_routers {
        tracing::debug!(prefix = %prefix, "Nested raw Axum router");
        // We explicitly apply the fallback to the nested router before nesting,
        // so that unmatched routes within this prefix are protected by global middleware.
        let nested_router =
            raw_router.fallback(crate::middleware::error_page_filter::fallback_404_handler);
        let nested_router = if let Some(layers) = idempotency_layers {
            nested_router.layer(layers.manual.clone())
        } else {
            nested_router
        };
        router = router.nest(&prefix, nested_router);
    }
    router
}

fn apply_compression_middleware<S>(
    mut router: axum::Router<S>,
    config: &AutumnConfig,
) -> axum::Router<S>
where
    S: Clone + Send + Sync + 'static,
{
    if config.compression.enabled {
        use tower_http::compression::predicate::{DefaultPredicate, NotForContentType, Predicate};
        // Extend the default predicate (skips images, gRPC, SSE, small bodies) to also
        // skip binary media and already-compressed formats — compressing these wastes
        // CPU, increases transfer size for archives, and can confuse media players.
        let predicate = DefaultPredicate::new()
            // Binary media — already-encoded by codec, not compressible by gzip/br.
            .and(NotForContentType::const_new("audio/"))
            .and(NotForContentType::const_new("video/"))
            .and(NotForContentType::const_new("application/octet-stream"))
            // Compressed archive formats — re-compressing wastes CPU.
            .and(NotForContentType::const_new("application/zip"))
            .and(NotForContentType::const_new("application/gzip"))
            .and(NotForContentType::const_new("application/x-gzip"))
            .and(NotForContentType::const_new("application/zstd"))
            .and(NotForContentType::const_new("application/x-bzip2"))
            .and(NotForContentType::const_new("application/x-bzip"))
            .and(NotForContentType::const_new("application/x-rar-compressed"))
            .and(NotForContentType::const_new("application/vnd.rar"))
            .and(NotForContentType::const_new("application/x-7z-compressed"));
        router =
            router.layer(tower_http::compression::CompressionLayer::new().compress_when(predicate));
        tracing::info!("Response compression enabled (gzip/brotli)");
    }
    router
}

fn apply_cors_middleware<S>(mut router: axum::Router<S>, config: &AutumnConfig) -> axum::Router<S>
where
    S: Clone + Send + Sync + 'static,
{
    // CORS middleware (only applied when allowed_origins is non-empty)
    if !config.cors.allowed_origins.is_empty() {
        let cors = build_cors_layer(&config.cors);
        tracing::info!(
            origins = ?config.cors.allowed_origins,
            credentials = config.cors.allow_credentials,
            "CORS enabled"
        );
        router = router.layer(cors);
    }
    router
}

fn apply_csrf_middleware<S>(
    mut router: axum::Router<S>,
    config: &AutumnConfig,
    signing_keys: Option<std::sync::Arc<crate::security::config::ResolvedSigningKeys>>,
) -> axum::Router<S>
where
    S: Clone + Send + Sync + 'static,
{
    // CSRF middleware (only applied when enabled)
    if config.security.csrf.enabled {
        let mut csrf_layer = crate::security::CsrfLayer::from_config(&config.security.csrf)
            .with_max_scan_bytes(config.security.upload.max_request_size_bytes);
        if let Some(keys) = signing_keys {
            csrf_layer = csrf_layer.with_signing_keys(keys);
        }
        for endpoint in &config.security.webhooks.endpoints {
            csrf_layer = csrf_layer.with_exempt_path(&endpoint.path);
        }
        tracing::info!("CSRF protection enabled");
        router = router.layer(csrf_layer);
    }
    router
}

fn apply_bot_protection_middleware<S>(
    mut router: axum::Router<S>,
    config: &AutumnConfig,
) -> axum::Router<S>
where
    S: Clone + Send + Sync + 'static,
{
    if config.bot_protection.enabled {
        // Use the dedicated captcha_exempt_paths list — NOT csrf.exempt_paths —
        // so that a route exempt from CSRF for non-cookie auth reasons does not
        // automatically bypass bot-protection as well.
        let mut exempt = config.security.captcha_exempt_paths.clone();
        for endpoint in &config.security.webhooks.endpoints {
            exempt.push(endpoint.path.clone());
        }
        let layer =
            crate::security::captcha::BotProtectionLayer::from_config(&config.bot_protection)
                .with_max_scan_bytes(config.security.upload.max_request_size_bytes)
                .with_exempt_paths(exempt);
        tracing::info!(
            provider = ?config.bot_protection.provider,
            dev_bypass = config.bot_protection.dev_bypass,
            "Bot protection (CAPTCHA) enabled"
        );
        router = router.layer(layer);
    }
    router
}

async fn populate_rate_limit_principal(
    axum::extract::State(state): axum::extract::State<AppState>,
    mut req: axum::extract::Request,
    next: axum::middleware::Next,
) -> axum::response::Response {
    if let Some(session) = req.extensions().get::<crate::session::Session>() {
        let auth_session_key = state.auth_session_key();
        if let Some(user_id) = session.get(auth_session_key).await {
            req.extensions_mut()
                .insert(crate::security::RateLimitPrincipal(user_id));
        }
    }
    next.run(req).await
}

fn apply_trusted_proxies_middleware<S>(
    router: axum::Router<S>,
    config: &AutumnConfig,
) -> axum::Router<S>
where
    S: Clone + Send + Sync + 'static,
{
    let tp = &config.security.trusted_proxies;
    let layer = crate::security::TrustedProxiesLayer::from_config(tp);
    if tp.trust_forwarded_headers || !tp.ranges.is_empty() || tp.trusted_hops.is_some() {
        tracing::info!(
            ranges = ?tp.ranges,
            trusted_hops = ?tp.trusted_hops,
            "Centralized trusted-proxy resolution enabled"
        );
    }
    router.layer(layer)
}

fn apply_rate_limit_middleware(
    mut router: axum::Router<AppState>,
    config: &AutumnConfig,
    state: &AppState,
) -> axum::Router<AppState> {
    if config.security.rate_limit.enabled {
        let tp = &config.security.trusted_proxies;
        let rl = &config.security.rate_limit;
        let has_top_level_proxy_config =
            tp.trust_forwarded_headers || !tp.ranges.is_empty() || tp.trusted_hops.is_some();
        // Preserve explicit rate-limit proxy config (legacy fields). The shared
        // top-level resolver is only injected when the rate-limit section carries
        // no proxy config of its own, preventing dev defaults from silently
        // overriding an operator's explicit security.rate_limit.trusted_proxies.
        let has_rate_limit_proxy_config =
            rl.trust_forwarded_headers || !rl.trusted_proxies.is_empty();
        // The framework default limiter shares its bucket with the MCP `/mcp`
        // envelope limiter (both built here), so it honors `RateLimitExempt` to
        // avoid double-counting an already-charged `tools/call`. User-installed
        // limiters don't, so MCP replays still consume their per-route buckets.
        let mut layer = crate::security::RateLimitLayer::from_config(rl).honoring_mcp_exempt();
        if has_top_level_proxy_config && !has_rate_limit_proxy_config {
            let resolver = crate::security::ProxyResolver::from_config(tp);
            layer = layer.with_proxy_resolver(resolver);
        }
        tracing::info!(
            rps = config.security.rate_limit.requests_per_second,
            burst = config.security.rate_limit.burst,
            "Rate limiting enabled"
        );
        router = router.layer(layer);

        if config.security.rate_limit.key_strategy
            == crate::security::KeyStrategy::AuthenticatedPrincipal
        {
            router = router.layer(axum::middleware::from_fn_with_state(
                state.clone(),
                populate_rate_limit_principal,
            ));
        }
    }
    router
}

fn apply_upload_middleware<S>(router: axum::Router<S>, config: &AutumnConfig) -> axum::Router<S>
where
    S: Clone + Send + Sync + 'static,
{
    let upload_config = config.security.upload.clone();
    let max_request_size = upload_config.max_request_size_bytes;
    tracing::info!(
        max_request_size_bytes = max_request_size,
        max_file_size_bytes = upload_config.max_file_size_bytes,
        allowed_mime_types = ?upload_config.allowed_mime_types,
        "Request body size limits enabled (applies to all content types)"
    );

    // Apply a global body-size cap covering JSON, form, raw bytes, and multipart.
    // The Multipart extractor further refines this per the UploadConfig extension.
    let router = router.layer(axum::extract::DefaultBodyLimit::max(max_request_size));

    // Insert UploadConfig into extensions so the Multipart extractor can read
    // per-file limits and the allowed MIME-type list.
    router.layer(axum::middleware::from_fn(
        move |mut req: axum::extract::Request, next: axum::middleware::Next| {
            let upload_config = upload_config.clone();
            async move {
                req.extensions_mut().insert(upload_config);
                next.run(req).await
            }
        },
    ))
}

/// Build the [`MaintenanceLayer`](crate::middleware::maintenance::MaintenanceLayer)
/// from config + state, with the health/probe paths that always bypass the gate.
///
/// Shared by [`apply_middleware`] (direct routes) and the late-mounted `/mcp`
/// envelope so both return the documented `503` identically when maintenance
/// mode is active — the `/mcp` router is merged after `apply_middleware`, so
/// without an explicit layer its `initialize`/`tools/list` would keep serving
/// the catalog during maintenance.
fn build_maintenance_layer(
    config: &AutumnConfig,
    state: &AppState,
) -> crate::middleware::maintenance::MaintenanceLayer {
    let maintenance_state = state
        .extension::<crate::maintenance::MaintenanceState>()
        .map(|s| (*s).clone())
        .unwrap_or_default();
    let bypass_paths = vec![
        config.health.path.clone(),
        config.health.live_path.clone(),
        config.health.ready_path.clone(),
        config.health.startup_path.clone(),
        crate::actuator::actuator_route_path(&config.actuator.prefix, "/health"),
    ];
    crate::middleware::maintenance::MaintenanceLayer::new(maintenance_state)
        .with_health_prefix(config.actuator.prefix.clone())
        .with_probe_paths(bypass_paths)
}

/// Apply a per-request-cycle timeout when `config.server.timeouts.request_timeout_ms`
/// is set and non-zero.
///
/// The middleware is inserted inner to [`RequestIdLayer`] so the request ID is
/// available in the warning log and 408 response body. The layer is a no-op when
/// the timeout is disabled, preserving zero overhead for unconfigured deployments.
fn apply_request_timeout_middleware(
    router: axum::Router<AppState>,
    config: &AutumnConfig,
    metrics: crate::middleware::MetricsCollector,
) -> axum::Router<AppState> {
    let timeout_ms = match config.server.timeouts.request_timeout_ms {
        Some(ms) if ms > 0 => ms,
        _ => return router,
    };
    let duration = std::time::Duration::from_millis(timeout_ms);
    let is_dev = matches!(
        config.profile.as_deref(),
        Some("dev" | "development") | None
    );
    tracing::info!(timeout_ms, "Per-request timeout enabled");
    router.layer(axum::middleware::from_fn(move |req, next| {
        request_timeout_handler(req, next, duration, metrics.clone(), is_dev)
    }))
}

async fn request_timeout_handler(
    req: axum::extract::Request,
    next: axum::middleware::Next,
    duration: std::time::Duration,
    metrics: crate::middleware::MetricsCollector,
    is_dev: bool,
) -> axum::response::Response {
    let request_id = req
        .extensions()
        .get::<crate::middleware::RequestId>()
        .cloned();
    match tokio::time::timeout(duration, next.run(req)).await {
        Ok(response) => response,
        Err(_elapsed) => {
            if let Some(ref rid) = request_id {
                tracing::warn!(request_id = %rid, "Request timed out");
            } else {
                tracing::warn!("Request timed out");
            }
            metrics.record_request_timeout();
            let body = crate::error::problem_details_json_string(
                http::StatusCode::REQUEST_TIMEOUT,
                "The server did not receive a complete request within the allowed time",
                None,
                None,
                request_id.as_ref().map(ToString::to_string),
                None,
                is_dev,
            );
            (
                http::StatusCode::REQUEST_TIMEOUT,
                [(http::header::CONTENT_TYPE, "application/problem+json")],
                body,
            )
                .into_response()
        }
    }
}

struct BuiltIdempotencyLayers {
    route: crate::idempotency::IdempotencyLayer,
    manual: crate::idempotency::IdempotencyLayer,
}

fn build_idempotency_layers(
    config: &AutumnConfig,
    state: &AppState,
) -> Result<Option<BuiltIdempotencyLayers>, RouterBuildError> {
    if !config.idempotency.enabled.unwrap_or(false) {
        return Ok(None);
    }

    let ttl = Duration::from_secs(config.idempotency.ttl_secs);
    let in_flight_ttl = Duration::from_secs(config.idempotency.in_flight_ttl_secs);
    let store: std::sync::Arc<dyn IdempotencyStore> = match config.idempotency.backend {
        crate::config::IdempotencyBackend::Memory => {
            std::sync::Arc::new(MemoryIdempotencyStore::new(ttl))
        }
        #[cfg(feature = "redis")]
        crate::config::IdempotencyBackend::Redis => {
            match crate::idempotency::RedisIdempotencyStore::from_config(&config.idempotency) {
                Ok(s) => std::sync::Arc::new(s),
                Err(e) => return Err(RouterBuildError::InvalidIdempotencyBackend(e)),
            }
        }
        #[cfg(not(feature = "redis"))]
        crate::config::IdempotencyBackend::Redis => {
            return Err(RouterBuildError::InvalidIdempotencyBackend(
                "idempotency backend 'redis' requires the autumn-web 'redis' feature \
                 flag; rebuild with --features redis or switch to backend = \"memory\""
                    .to_owned(),
            ));
        }
    };

    tracing::debug!(
        backend = ?config.idempotency.backend,
        ttl_secs = config.idempotency.ttl_secs,
        in_flight_ttl_secs = config.idempotency.in_flight_ttl_secs,
        "Idempotency-key middleware enabled"
    );

    let base = IdempotencyLayer::new(store)
        .with_ttl(ttl)
        .with_in_flight_ttl(in_flight_ttl)
        .with_metrics(state.metrics.clone());

    Ok(Some(BuiltIdempotencyLayers {
        route: base.clone().replay_through_inner(),
        manual: base.fail_closed_on_replay(),
    }))
}

#[allow(clippy::cognitive_complexity, clippy::too_many_lines)]
fn apply_middleware(
    mut router: axum::Router<AppState>,
    config: &AutumnConfig,
    state: &AppState,
    exception_filters: Vec<Arc<dyn ExceptionFilter>>,
    custom_layers: Vec<crate::app::CustomLayerRegistration>,
    error_page_renderer: Option<SharedRenderer>,
    session_store: Option<Arc<dyn crate::session::BoxedSessionStore>>,
) -> Result<axum::Router<AppState>, RouterBuildError> {
    // 404 fallback handler for unmatched routes must be registered BEFORE global middleware
    // so that unmatched routes are still protected by rate limiting, CSRF, CORS, etc.
    router = router.fallback(crate::middleware::error_page_filter::fallback_404_handler);

    // Resolve signing keys once; shared across session and CSRF layers.
    let is_production = matches!(config.profile.as_deref(), Some("prod" | "production"));
    let signing_keys = std::sync::Arc::new(crate::security::config::resolve_signing_keys(
        &config.security.signing_secret,
    ));
    // Only thread signing keys when a secret is configured (or in production where
    // fail_fast already ensures one is present). In dev without a configured secret
    // the ephemeral key is generated per-process — useful but not required.
    let signing_keys_opt: Option<std::sync::Arc<crate::security::config::ResolvedSigningKeys>> =
        if config.security.signing_secret.secret.is_some() || is_production {
            Some(signing_keys)
        } else {
            None
        };

    router = apply_cors_middleware(router, config);
    let trusted_host_policy = TrustedHostPolicy::from_config(config);
    router = router.layer(axum::middleware::from_fn(move |req, next| {
        trusted_host_middleware(req, next, trusted_host_policy.clone())
    }));
    router = apply_csrf_middleware(router, config, signing_keys_opt.clone());
    router = apply_bot_protection_middleware(router, config);
    // Method-override rejection filter. The outer `MethodOverrideLayer`
    // (applied at the `axum::serve` boundary so it can rewrite the
    // request method before route matching) stamps a
    // [`MethodOverrideRejection`] extension when the override field
    // value is invalid or the body was too large to scan; this inner
    // middleware converts that extension into the corresponding
    // `400`/`413` response. Running it here means the rejection flows
    // through the rest of the response stack (security headers,
    // request IDs, metrics, error-page filter) rather than bypassing
    // them. Placed outside CSRF so a `BodyTooLarge` (empty body)
    // doesn't get masked by a `403` from CSRF's missing-token branch,
    // and a clear `400 invalid _method` outranks "missing CSRF".
    router = router.layer(axum::middleware::from_fn(
        crate::middleware::method_override_rejection_filter,
    ));
    router = apply_rate_limit_middleware(router, config, state);

    // Register MaintenanceLayer automatically (shared construction with the
    // late-mounted `/mcp` envelope — see `build_maintenance_layer`).
    router = router.layer(build_maintenance_layer(config, state));

    router = router.layer(axum::middleware::from_fn(
        crate::webhook::webhook_replay_cleanup_middleware,
    ));
    router = apply_upload_middleware(router, config);

    // Security headers layer (always applied)
    let security_headers =
        crate::security::SecurityHeadersLayer::from_config(&config.security.headers);
    tracing::debug!("Security headers enabled");

    // User-registered Tower layers (AppBuilder::layer). Outermost — applied
    // last so they wrap all framework middleware.  Iterate in reverse so the
    // first registered layer ends up outermost among user layers — matching
    // tower::ServiceBuilder ordering.
    //
    // When a static dist dir is active (SSG/ISG build), these layers are
    // NOT passed here — they are extracted by try_build_router_with_static_inner
    // and applied outside the static-first middleware instead, so they can
    // process pre-rendered responses without creating a session dependency.
    let custom_layer_count = custom_layers.len();
    for registered in custom_layers.into_iter().rev() {
        router = (registered.apply)(router);
    }
    if custom_layer_count > 0 {
        tracing::debug!(count = custom_layer_count, "Custom Tower layers applied");
    }

    // TrustedProxiesLayer is applied after user layers so it is outermost in the
    // ingress request path, stamping ResolvedClientIdentity before any user or
    // framework middleware reads ClientAddr / ClientHost / ClientScheme.
    router = apply_trusted_proxies_middleware(router, config);

    let mut router = router;

    if config.tenancy.enabled {
        router = router.layer(axum::middleware::from_fn_with_state(
            state.clone(),
            crate::tenancy::tenancy_middleware,
        ));
        tracing::debug!("Multi-tenancy middleware enabled");
    }

    // Per-request timeout (inner to RequestId so the request ID set by that
    // layer is available when the timeout fires — see request_timeout_handler).
    //
    // Full ingress layer order (outermost → innermost):
    //   TraceContext → AccessLog-fallback (applied in apply_startup_barrier) →
    //   StartupBarrier → Compression → Metrics → ExceptionFilter → ErrorPageContext →
    //   Session → SecurityHeaders → RequestId → LogContext → AccessLog-primary →
    //   Timeout → [user layers] → Tenancy → BodyLimit/UploadConfig →
    //   MethodOverride → RateLimit → CSRF → CORS → handler
    router = apply_request_timeout_middleware(router, config, state.metrics.clone());

    // Error-reporting + panic-catch layer. Placed inner to `RequestIdLayer`
    // (so the request id is available when a handler panics) and outer to the
    // timeout, user layers, and handler (so their panics are caught and turned
    // into a clean 500 instead of aborting the worker task). The resulting 500
    // still flows out through the exception-filter chain for HTML negotiation.
    #[cfg(feature = "reporting")]
    {
        router = router.layer(crate::reporting::ReportingLayer::new(
            state.error_reporters(),
            config.reporting.enabled,
            config.reporting.sample_rate,
        ));
    }

    // Structured per-request access log (#999), primary emitter: one INFO
    // event (target `autumn::access`) per served request at the response
    // boundary. Inner to RequestId (so the request id is available) and to
    // LogContext (so the event is emitted inside the request span); outer to
    // the reporting and timeout layers so panics-turned-500s and timeout
    // responses are logged with the status the client receives. Emitted
    // responses are marked so the outermost fallback (apply_startup_barrier)
    // does not double-log; that fallback covers requests that short-circuit
    // before this layer runs.
    if config.log.access_log {
        router = router.layer(crate::middleware::AccessLogLayer::new(
            config.log.access_log_exclude.clone(),
        ));
    }

    // Request-scoped log context (#1169). Established for every request, inner
    // to `RequestIdLayer` (so the request id is available to seed it) and outer
    // to tenancy, user layers, and the handler (so all of them, and every
    // `tracing` event they emit, inherit the same correlating context). The
    // filter mirrors the error-page scrubber so sensitive custom fields never
    // enter the context output.
    let mut log_context_filter_parameters = config.log.filter_parameters.clone();
    log_context_filter_parameters.extend(crate::encryption::registered_encrypted_column_names());
    let log_context_filter = Arc::new(crate::log::filter::ParameterFilter::new(
        &log_context_filter_parameters,
        &config.log.unfilter_parameters,
    ));
    let router = router.layer(crate::middleware::LogContextLayer::new(log_context_filter));

    let router = router.layer(RequestIdLayer).layer(security_headers);

    let router = crate::session::apply_session_layer(
        router,
        &config.session,
        config.profile.as_deref(),
        session_store,
        signing_keys_opt,
    )?;
    tracing::debug!(backend = ?config.session.backend, "Session management enabled");

    // Error page filter: renders HTML error pages for browser requests.
    // Always registered (uses default renderer if no custom one is provided).
    let is_dev = config
        .profile
        .as_deref()
        .map_or(cfg!(debug_assertions), |p| p == "dev");
    let renderer = error_page_renderer.unwrap_or_else(error_pages::default_renderer);
    // Encrypted columns (#805) compose into log scrubbing (#697): their names are
    // always scrubbed from trace/error parameter output so ciphertext-backed
    // values never leak through logs even if an app forgets to list them.
    let mut filter_parameters = config.log.filter_parameters.clone();
    filter_parameters.extend(crate::encryption::registered_encrypted_column_names());
    let error_page_filter = crate::middleware::error_page_filter::ErrorPageFilter {
        renderer,
        is_dev,
        parameter_filter: crate::log::filter::ParameterFilter::new(
            &filter_parameters,
            &config.log.unfilter_parameters,
        ),
    };

    // Combine the Problem Details normalizer and error page filter with user
    // exception filters. Problem Details runs first so HTML negotiation can
    // still replace the JSON response for browser requests.
    let mut all_filters: Vec<Arc<dyn ExceptionFilter>> = vec![
        Arc::new(ProblemDetailsFilter { is_dev }),
        Arc::new(error_page_filter),
    ];
    all_filters.extend(exception_filters);

    let count = all_filters.len();
    tracing::debug!(
        count,
        "Registered exception filters (including error page filter)"
    );

    // Error page context layer must be inner to the exception filter so
    // WantsHtml is set on the response before the filter inspects it.
    // Full ingress layer order (outermost -> innermost):
    //   TraceContext (applied outside the startup barrier so short-circuit
    //   responses still carry traceparent) ->
    //   Compression (outer to ExceptionFilter — see note below) ->
    //   [user layers, when SSG/ISG dist dir active] ->
    //   StaticFileMiddleware (when SSG/ISG enabled) ->
    //   Metrics -> ExceptionFilter -> ErrorPageContext -> Session ->
    //   SecurityHeaders -> RequestId -> LogContext -> AccessLog-primary ->
    //   [user layers, non-static build] ->
    //   Tenancy -> RateLimit -> CSRF -> CORS -> handler
    //   (An AccessLog fallback sits outermost, applied in apply_startup_barrier.)
    let router = router
        .layer(crate::middleware::error_page_filter::ErrorPageContextLayer { is_dev })
        .layer(ExceptionFilterLayer::new(all_filters))
        .layer(crate::middleware::MetricsLayer::new(state.metrics.clone()));

    // Response compression is applied outermost (outside ExceptionFilter) so that
    // exception filters which rebuild the response body (e.g. ProblemDetailsFilter
    // normalising AutumnErrors to JSON Problem Details) do so before the body is
    // encoded. If compression were inner to ExceptionFilter, the filter would
    // inherit a Content-Encoding: gzip header on the rebuilt uncompressed body,
    // causing clients to receive uncompressed bytes labeled as gzip.
    // User-registered layers (EtagLayer etc.) remain inner to Compression, so
    // ETags are still computed on the uncompressed body before encoding occurs.
    let router = apply_compression_middleware(router, config);

    Ok(router)
}

async fn trusted_host_middleware(
    req: Request<axum::body::Body>,
    next: Next,
    policy: TrustedHostPolicy,
) -> axum::response::Response {
    let path = req.uri().path();
    if (req.method() == http::Method::GET || req.method() == http::Method::HEAD)
        && policy.probe_bypass_paths.contains(path)
    {
        return next.run(req).await;
    }
    let authority = req.uri().authority().map(http::uri::Authority::as_str);
    let host_header = req
        .headers()
        .get(http::header::HOST)
        .and_then(|v| v.to_str().ok());
    let raw_host = authority.or(host_header);
    let parsed_host = raw_host.and_then(extract_host_without_port);
    let host = parsed_host
        .map(str::to_ascii_lowercase)
        .map(|h| h.trim_end_matches('.').to_owned())
        .filter(|h| !h.is_empty());
    let host_source_present = raw_host.is_some();
    if host.is_none() && !host_source_present && policy.allow_missing_host {
        return next.run(req).await;
    }
    if host.as_deref().is_some_and(|host| policy.allows_host(host)) {
        next.run(req).await
    } else {
        tracing::warn!(host = ?host, "trusted host rejected request");
        let body = crate::error::problem_details_json_string(
            StatusCode::BAD_REQUEST,
            "Invalid Host header",
            None,
            None,
            None,
            None,
            true,
        );
        (
            StatusCode::BAD_REQUEST,
            [(http::header::CONTENT_TYPE, "application/problem+json")],
            body,
        )
            .into_response()
    }
}

pub fn extract_host_without_port(header: &str) -> Option<&str> {
    let host = header.trim();
    if host.is_empty() {
        return None;
    }
    if host.starts_with('[') {
        let end = host.find(']')?;
        let literal = host.get(1..end)?;
        if literal.is_empty() || literal.parse::<std::net::IpAddr>().is_err() {
            return None;
        }

        let remainder = host.get(end + 1..)?;
        if remainder.is_empty() {
            return Some(literal);
        }

        let maybe_port = remainder.strip_prefix(':')?;
        if !maybe_port.is_empty() && maybe_port.chars().all(|c| c.is_ascii_digit()) {
            return Some(literal);
        }

        return None;
    }
    let Some((candidate, maybe_port)) = host.rsplit_once(':') else {
        return Some(host);
    };
    if candidate.contains(':') {
        // unbracketed IPv6 literal; keep host verbatim
        return Some(host);
    }
    if !maybe_port.is_empty()
        && maybe_port.chars().all(|c| c.is_ascii_digit())
        && !candidate.is_empty()
    {
        Some(candidate)
    } else {
        None
    }
}

/// Build the router with optional static-file-first serving.
///
/// If `dist_dir` is `Some` and contains a valid `manifest.json`, the
/// returned router intercepts GET/HEAD requests whose path appears in
/// the manifest and serves pre-built HTML directly — before the dynamic
/// router runs.  This matches Next.js SSG/ISR semantics where static
/// pages always win over dynamic handlers.
///
/// Requests not in the manifest (including non-GET/HEAD methods) fall
/// through to the dynamic router unchanged.
///
/// When `dist_dir` is `None` or the manifest is missing, the returned
/// router is identical to [`build_router`].
///
/// This function is public primarily for integration testing.
///
/// # Panics
///
/// Panics when framework router assembly encounters invalid configuration.
/// Use [`try_build_router_with_static`] to handle configuration errors
/// explicitly.
#[allow(dead_code)]
pub fn build_router_with_static(
    route_list: Vec<Route>,
    config: &AutumnConfig,
    state: AppState,
    dist_dir: Option<&std::path::Path>,
) -> axum::Router {
    try_build_router_with_static(route_list, config, state, dist_dir)
        .unwrap_or_else(|error| panic!("invalid router configuration: {error}"))
}

/// Checked variant of [`build_router_with_static`] that returns configuration
/// errors instead of panicking.
///
/// # Errors
///
/// Returns [`RouterBuildError`] when router assembly encounters invalid
/// framework configuration, such as an unusable session backend.
#[allow(dead_code)]
pub fn try_build_router_with_static(
    route_list: Vec<Route>,
    config: &AutumnConfig,
    state: AppState,
    dist_dir: Option<&std::path::Path>,
) -> Result<axum::Router, RouterBuildError> {
    try_build_router_with_static_inner(
        route_list,
        config,
        state,
        dist_dir,
        RouterContext {
            exception_filters: Vec::new(),
            scoped_groups: Vec::new(),
            merge_routers: Vec::new(),
            nest_routers: Vec::new(),
            custom_layers: Vec::new(),
            error_page_renderer: None,
            session_store: None,
            #[cfg(feature = "openapi")]
            openapi: None,
            #[cfg(feature = "mcp")]
            mcp: None,
        },
    )
}

pub fn try_build_router_with_static_inner(
    route_list: Vec<Route>,
    config: &AutumnConfig,
    state: AppState,
    dist_dir: Option<&std::path::Path>,
    mut ctx: RouterContext,
) -> Result<axum::Router, RouterBuildError> {
    let startup_barrier_state = state.clone();

    let Some(dist) = dist_dir else {
        let app_router = try_build_router_inner(route_list, config, state, ctx)?;
        return Ok(apply_startup_barrier(
            app_router,
            config,
            &startup_barrier_state,
        ));
    };

    let Some(layer) = crate::static_gen::StaticFileLayer::new(dist) else {
        tracing::debug!(
            dist = %dist.display(),
            "No valid manifest.json in dist dir; skipping static file layer"
        );
        let app_router = try_build_router_inner(route_list, config, state, ctx)?;
        return Ok(apply_startup_barrier(
            app_router,
            config,
            &startup_barrier_state,
        ));
    };

    for (route, entry) in &layer.manifest().routes {
        tracing::debug!(
            route = %route,
            file = %entry.file,
            revalidate = ?entry.revalidate,
            "Static route"
        );
    }

    // Extract user layers before building the inner router. They are applied
    // OUTSIDE the static-first middleware (and outside session) so that:
    //   • User layers (e.g. compression) can process pre-rendered responses.
    //   • Static serving remains available even if the session backend is down.
    //   • ISR regeneration uses the inner router (no user layers), ensuring
    //     re-rendered pages are saved as raw HTML rather than pre-transformed.
    //
    // Compute the idempotency flag NOW while custom_layers is still populated,
    // then drain it. build_router_pre_state would otherwise see an empty list
    // and incorrectly treat opaque layers as absent when selecting idempotency
    // behaviour for each route.
    let opaque_present = Some(custom_layers_require_fail_closed_idempotency(
        &ctx.custom_layers,
    ));
    let custom_layers = std::mem::take(&mut ctx.custom_layers);

    let inner_router = build_router_pre_state(route_list, config, &state, ctx, opaque_present)?;

    // Attach the inner router for ISR background regeneration. Because user
    // layers are excluded, re-renders produce raw HTML (no compression, etc.)
    // that is then saved to disk and served with user-layer processing applied
    // at request time.
    let has_isr = layer
        .manifest()
        .routes
        .values()
        .any(|e| e.revalidate.is_some());
    let layer = if has_isr {
        layer.with_router(inner_router.clone().with_state(state.clone()))
    } else {
        layer
    };
    let layer = Arc::new(layer);

    // Static-first serving: intercept GET/HEAD requests whose path appears
    // in the manifest and serve pre-built HTML directly — BEFORE the dynamic
    // router (and session layer) runs. This preserves availability of static
    // pages even when the session backend is unavailable.
    //
    // Requests not in the manifest (including non-GET/HEAD methods) fall
    // through to the dynamic router unchanged.
    //
    // ISR staleness checking happens inside `resolve()`: stale pages are
    // still served immediately while background regeneration runs
    // (stale-while-revalidate).
    let static_layer = layer;
    let mut router: axum::Router<AppState> = inner_router.layer(axum::middleware::from_fn(
        move |req: axum::extract::Request, next: axum::middleware::Next| {
            let static_layer = static_layer.clone();
            async move {
                let is_get = req.method() == http::Method::GET;
                let is_head = req.method() == http::Method::HEAD;
                if is_get || is_head {
                    let path = req.uri().path();
                    // Normalize trailing slash: /about/ → /about (but keep / as /)
                    let normalized = if path.len() > 1 && path.ends_with('/') {
                        &path[..path.len() - 1]
                    } else {
                        path
                    };
                    if let Some(file_path) = static_layer.resolve(normalized)
                        && let Ok(contents) = tokio::fs::read(&file_path).await
                    {
                        let body = if is_head {
                            axum::body::Body::empty()
                        } else {
                            axum::body::Body::from(contents)
                        };
                        return http::Response::builder()
                            .status(http::StatusCode::OK)
                            .header(http::header::CONTENT_TYPE, "text/html; charset=utf-8")
                            .body(body)
                            .expect("infallible response builder");
                    }
                }
                next.run(req).await
            }
        },
    ));

    // Apply user layers OUTSIDE the static middleware so they wrap it and can
    // process both static and dynamic responses (e.g. compress the HTML on
    // the way out). Iterate in reverse so the first registered layer ends up
    // outermost — matching tower::ServiceBuilder ordering.
    let custom_layer_count = custom_layers.len();
    for registered in custom_layers.into_iter().rev() {
        router = (registered.apply)(router);
    }
    if custom_layer_count > 0 {
        tracing::debug!(
            count = custom_layer_count,
            "Custom Tower layers applied outside static middleware"
        );
    }

    // Compression must also be applied OUTSIDE the static-first middleware so
    // that pre-rendered HTML pages (served directly by StaticFileLayer without
    // reaching inner_router) are also compressed. This mirrors the placement in
    // apply_middleware for the dynamic-only path.
    router = apply_compression_middleware(router, config);

    let router = router.layer(crate::security::SecurityHeadersLayer::from_config(
        &config.security.headers,
    ));

    Ok(apply_startup_barrier(
        router.with_state(state),
        config,
        &startup_barrier_state,
    ))
}

#[derive(Clone)]
struct StartupBarrierState {
    app_state: AppState,
    live_path: String,
    ready_path: String,
    startup_path: String,
    health_path: String,
    actuator_paths: Vec<String>,
    actuator_subtree_paths: Vec<String>,
}

impl StartupBarrierState {
    fn from_config(config: &AutumnConfig, app_state: &AppState) -> Self {
        let actuator_subtree_paths = if config.actuator.sensitive {
            vec![crate::actuator::actuator_route_path(
                &config.actuator.prefix,
                "/loggers",
            )]
        } else {
            Vec::new()
        };

        Self {
            app_state: app_state.clone(),
            live_path: config.health.live_path.clone(),
            ready_path: config.health.ready_path.clone(),
            startup_path: config.health.startup_path.clone(),
            health_path: config.health.path.clone(),
            actuator_paths: crate::actuator::actuator_endpoint_paths(
                &config.actuator.prefix,
                config.actuator.sensitive,
                config.actuator.prometheus,
            ),
            actuator_subtree_paths,
        }
    }

    fn allows_path(&self, path: &str) -> bool {
        path == self.live_path
            || path == self.ready_path
            || path == self.startup_path
            || path == self.health_path
            || self.actuator_paths.iter().any(|allowed| path == allowed)
            || self
                .actuator_subtree_paths
                .iter()
                .any(|allowed| path_matches_route_prefix(path, allowed))
    }
}

fn apply_startup_barrier(
    router: axum::Router,
    config: &AutumnConfig,
    state: &AppState,
) -> axum::Router {
    let barrier_state = StartupBarrierState::from_config(config, state);
    let router = router.layer(axum::middleware::from_fn_with_state(
        barrier_state,
        startup_barrier,
    ));
    // Access-log fallback (#999), applied OUTSIDE the startup barrier, the
    // static-first (SSG/ISR) middleware, the session layer, and the
    // exception-filter chain — every production build path funnels through
    // this function, including after the late MCP endpoint merge. It emits
    // only for responses the primary in-stack layer never saw (it checks the
    // AccessLogEmitted response marker), giving startup 503s, pre-built
    // static page hits, session-store outage 503s, and MCP endpoint requests
    // an access line too. Those short-circuits never ran RequestIdLayer, so
    // the fallback reads `x-request-id` from the response when present and
    // logs without a request id otherwise.
    let router = if config.log.access_log {
        router.layer(crate::middleware::AccessLogLayer::fallback(
            config.log.access_log_exclude.clone(),
        ))
    } else {
        router
    };
    // W3C Trace Context propagation wraps the startup barrier (and the
    // static-first middleware above it) so short-circuit responses —
    // startup 503s and pre-built static file hits — still extract the
    // incoming `traceparent` and inject the current context into the
    // outgoing response. Applied here rather than inside `apply_middleware`
    // because those outer wrappers can return without ever invoking the
    // inner router. Outer to AccessLog so the access event is emitted while
    // the trace context is current.
    #[cfg(feature = "telemetry-otlp")]
    let router = router.layer(crate::middleware::TraceContextLayer);
    router
}

async fn startup_barrier(
    State(state): State<StartupBarrierState>,
    request: axum::extract::Request,
    next: Next,
) -> axum::response::Response {
    if crate::app::is_static_build_mode()
        || state.app_state.probes().is_startup_complete()
        || state.allows_path(request.uri().path())
    {
        next.run(request).await
    } else {
        (
            StatusCode::SERVICE_UNAVAILABLE,
            "Service is still starting up",
        )
            .into_response()
    }
}

fn path_matches_route_prefix(path: &str, prefix: &str) -> bool {
    path == prefix
        || path
            .strip_prefix(prefix)
            .is_some_and(|rest| rest.is_empty() || rest.starts_with('/'))
}

/// Build a `tower_http::cors::CorsLayer` from the framework's [`crate::config::CorsConfig`].
///
/// Called only when `config.cors.allowed_origins` is non-empty.
pub fn build_cors_layer(cors: &crate::config::CorsConfig) -> tower_http::cors::CorsLayer {
    use http::header::HeaderName;
    use tower_http::cors::{AllowOrigin, CorsLayer};

    let layer = if cors.allowed_origins.iter().any(|o| o == "*") {
        CorsLayer::new().allow_origin(AllowOrigin::any())
    } else {
        let origins: Vec<http::HeaderValue> = cors
            .allowed_origins
            .iter()
            .filter_map(|o| match o.parse() {
                Ok(v) => Some(v),
                Err(e) => {
                    tracing::warn!(origin = %o, error = %e, "CORS: ignoring malformed allowed_origin");
                    None
                }
            })
            .collect();
        CorsLayer::new().allow_origin(origins)
    };

    let methods: Vec<http::Method> = cors
        .allowed_methods
        .iter()
        .filter_map(|m| match m.parse() {
            Ok(v) => Some(v),
            Err(e) => {
                tracing::warn!(method = %m, error = %e, "CORS: ignoring malformed allowed_method");
                None
            }
        })
        .collect();

    let headers: Vec<HeaderName> = cors
        .allowed_headers
        .iter()
        .filter_map(|h| match h.parse() {
            Ok(v) => Some(v),
            Err(e) => {
                tracing::warn!(header = %h, error = %e, "CORS: ignoring malformed allowed_header");
                None
            }
        })
        .collect();

    layer
        .allow_methods(methods)
        .allow_headers(headers)
        .allow_credentials(cors.allow_credentials)
        .max_age(std::time::Duration::from_secs(cors.max_age_secs))
}

/// Set `Cache-Control` headers for static assets based on whether the path is
/// fingerprinted.
///
/// | Path | Header |
/// |------|--------|
/// | `/static/**.<8hex>.*` | `public, max-age=31536000, immutable` |
/// | `/static/**` (other) | `public, max-age=0, must-revalidate` |
/// | Everything else | unchanged |
///
/// The short `must-revalidate` policy for plain static paths ensures that
/// returning visitors always fetch the latest file after a deploy, while the
/// long `immutable` policy for fingerprinted files lets browsers skip the
/// network entirely for assets whose content will never change.
pub async fn asset_cache_control(
    req: axum::extract::Request,
    next: axum::middleware::Next,
) -> axum::response::Response {
    let path = req.uri().path().to_owned();
    let mut resp = next.run(req).await;
    if path.starts_with("/static/") && resp.status().is_success() {
        // Use manifest membership rather than filename pattern so that
        // user-authored assets like `vendor.deadbeef.js` are never given an
        // immutable cache lifetime.
        let is_immutable = path
            .strip_prefix("/static/")
            .is_some_and(crate::assets::is_manifest_asset);
        let header = if is_immutable {
            "public, max-age=31536000, immutable"
        } else {
            "public, max-age=0, must-revalidate"
        };
        resp.headers_mut().insert(
            http::header::CACHE_CONTROL,
            http::HeaderValue::from_static(header),
        );
    }
    resp
}

#[cfg(feature = "htmx")]
pub async fn htmx_handler() -> axum::response::Response {
    use axum::response::IntoResponse;
    (
        [
            (http::header::CONTENT_TYPE, "application/javascript"),
            (
                http::header::CACHE_CONTROL,
                "public, max-age=31536000, immutable",
            ),
        ],
        crate::htmx::HTMX_JS,
    )
        .into_response()
}

#[cfg(feature = "htmx")]
pub async fn htmx_csrf_handler() -> axum::response::Response {
    use axum::response::IntoResponse;
    (
        [
            (http::header::CONTENT_TYPE, "application/javascript"),
            (
                http::header::CACHE_CONTROL,
                "public, max-age=31536000, immutable",
            ),
        ],
        crate::htmx::HTMX_CSRF_JS,
    )
        .into_response()
}

#[cfg(feature = "htmx")]
pub async fn autumn_widgets_handler() -> axum::response::Response {
    use axum::response::IntoResponse;
    (
        [
            (http::header::CONTENT_TYPE, "application/javascript"),
            (
                http::header::CACHE_CONTROL,
                "public, max-age=31536000, immutable",
            ),
        ],
        crate::htmx::AUTUMN_WIDGETS_JS,
    )
        .into_response()
}

#[cfg(feature = "openapi")]
fn collect_openapi_docs(
    route_list: &[Route],
    scoped_groups: &[ScopedGroup],
) -> Vec<crate::openapi::ApiDoc> {
    // Walk both top-level routes and scoped groups. For scoped groups the
    // effective path is `prefix + route.path`; we materialize these into
    // fresh `ApiDoc`s so the rendered spec reflects the actual URL the
    // user will call.
    let mut docs: Vec<crate::openapi::ApiDoc> = Vec::new();
    for route in route_list {
        let mut doc = route.api_doc.clone();
        doc.api_version = route.api_version;
        doc.sunset_opt_out = route.sunset_opt_out;
        docs.push(doc);
    }
    for group in scoped_groups {
        // Extract `{name}` captures from the scope prefix so parameters
        // declared in the prefix (e.g. `/orgs/{org_id}`) show up on the
        // generated operation alongside the child route's own params.
        let prefix_params = extract_path_params(&group.prefix);
        for route in &group.routes {
            let mut doc = route.api_doc.clone();
            doc.api_version = route.api_version;
            doc.sunset_opt_out = route.sunset_opt_out;
            // Leak the combined path so it fits the `&'static str` shape of
            // ApiDoc. The spec is built once per process; the leak is
            // bounded by the route table size. Using the same
            // normalization as `join_nested_path` keeps the spec's
            // paths aligned with the URLs axum actually routes.
            let full = join_nested_path(&group.prefix, route.api_doc.path);
            doc.path = Box::leak(full.into_boxed_str());

            if !prefix_params.is_empty() {
                let mut merged: Vec<&'static str> = prefix_params
                    .iter()
                    .map(|p| &*Box::leak(p.clone().into_boxed_str()))
                    .collect();
                for existing in route.api_doc.path_params {
                    if !merged.iter().any(|n| n == existing) {
                        merged.push(existing);
                    }
                }
                doc.path_params = Box::leak(merged.into_boxed_slice());
            }

            docs.push(doc);
        }
    }
    docs
}

#[cfg(feature = "openapi")]
fn mount_swagger_ui_routes(
    mut router: axum::Router<AppState>,
    path: &str,
    title: &str,
    json_path: &str,
) -> axum::Router<AppState> {
    let [css_path, bundle_path, initializer_path] = crate::openapi::swagger_ui_asset_paths(path);
    let html_body = Arc::new(crate::openapi::swagger_ui_html(
        title,
        &css_path,
        &bundle_path,
        &initializer_path,
    ));
    let initializer_body = Arc::new(crate::openapi::swagger_ui_initializer_js(json_path));
    router = router.route(
        path,
        axum::routing::get(move || {
            let html = html_body.clone();
            async move {
                use axum::response::IntoResponse;
                (
                    [(http::header::CONTENT_TYPE, "text/html; charset=utf-8")],
                    (*html).clone(),
                )
                    .into_response()
            }
        }),
    );
    router = router.route(
        &css_path,
        axum::routing::get(|| async move {
            use axum::response::IntoResponse;
            (
                [(http::header::CONTENT_TYPE, "text/css; charset=utf-8")],
                crate::openapi::SWAGGER_UI_CSS,
            )
                .into_response()
        }),
    );
    router = router.route(
        &bundle_path,
        axum::routing::get(|| async move {
            use axum::body::Bytes;
            use axum::response::IntoResponse;
            (
                [(
                    http::header::CONTENT_TYPE,
                    "application/javascript; charset=utf-8",
                )],
                Bytes::from_static(crate::openapi::SWAGGER_UI_BUNDLE),
            )
                .into_response()
        }),
    );
    router = router.route(
        &initializer_path,
        axum::routing::get(move || {
            let js = initializer_body.clone();
            async move {
                use axum::response::IntoResponse;
                (
                    [(
                        http::header::CONTENT_TYPE,
                        "application/javascript; charset=utf-8",
                    )],
                    (*js).clone(),
                )
                    .into_response()
            }
        }),
    );
    router
}

#[cfg(feature = "oauth2")]
async fn http_interceptor_middleware(
    state: axum::extract::State<AppState>,
    req: axum::extract::Request,
    next: axum::middleware::Next,
) -> axum::response::Response {
    use crate::interceptor::{ACTIVE_HTTP_INTERCEPTORS, HttpInterceptor};
    if let Some(interceptor_arc) = state.extension::<Arc<dyn HttpInterceptor>>() {
        let interceptor = (*interceptor_arc).clone();
        let interceptors = vec![interceptor];
        ACTIVE_HTTP_INTERCEPTORS
            .scope(interceptors, async move { next.run(req).await })
            .await
    } else {
        next.run(req).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::body::Body;
    use axum::http::{Request, StatusCode};
    use tower::ServiceExt;

    fn test_state() -> AppState {
        AppState {
            extensions: std::sync::Arc::new(std::sync::RwLock::new(
                std::collections::HashMap::new(),
            )),
            #[cfg(feature = "db")]
            pool: None,
            #[cfg(feature = "db")]
            replica_pool: None,
            profile: Some("test".to_owned()),
            started_at: std::time::Instant::now(),
            health_detailed: false,
            probes: crate::probe::ProbeState::ready_for_test(),
            metrics: crate::middleware::MetricsCollector::new(),
            log_levels: crate::actuator::LogLevels::new("info"),
            task_registry: crate::actuator::TaskRegistry::new(),
            job_registry: crate::actuator::JobRegistry::new(),
            config_props: crate::actuator::ConfigProperties::default(),
            metrics_source_registry: crate::actuator::MetricsSourceRegistry::new(),
            health_indicator_registry: crate::actuator::HealthIndicatorRegistry::new(),
            #[cfg(feature = "ws")]
            channels: crate::channels::Channels::new(32),
            #[cfg(feature = "presence")]
            presence: crate::presence::Presence::new(crate::channels::Channels::new(32)),
            #[cfg(feature = "ws")]
            shutdown: tokio_util::sync::CancellationToken::new(),
            policy_registry: crate::authorization::PolicyRegistry::default(),
            forbidden_response: crate::authorization::ForbiddenResponse::default(),
            auth_session_key: "user_id".to_owned(),
            shared_cache: None,
            clock: std::sync::Arc::new(crate::time::SystemClock),
        }
    }

    #[tokio::test]
    async fn build_router_mounts_actuator_at_configured_prefix() {
        let mut config = AutumnConfig::default();
        config.actuator.prefix = "/ops".to_owned();
        config.actuator.sensitive = true;

        let app = build_router(Vec::new(), &config, test_state());

        let prefixed = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/ops/health")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(prefixed.status(), StatusCode::OK);

        let legacy = app
            .oneshot(
                Request::builder()
                    .uri("/actuator/health")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(legacy.status(), StatusCode::NOT_FOUND);
    }

    /// Pins the production access-log wiring (#999): the layer is applied in
    /// `apply_startup_barrier`, outside the barrier itself, so even requests
    /// rejected with 503 before the app router runs emit one access event
    /// carrying the status the client receives.
    #[test]
    fn startup_barrier_503s_are_access_logged() {
        use tracing_subscriber::layer::SubscriberExt as _;

        #[derive(Clone, Default)]
        struct Capture {
            events: Arc<std::sync::Mutex<Vec<std::collections::BTreeMap<String, String>>>>,
        }
        struct Visitor<'a>(&'a mut std::collections::BTreeMap<String, String>);
        impl tracing::field::Visit for Visitor<'_> {
            fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
                self.0.insert(field.name().to_owned(), format!("{value:?}"));
            }
            fn record_u64(&mut self, field: &tracing::field::Field, value: u64) {
                self.0.insert(field.name().to_owned(), value.to_string());
            }
        }
        impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for Capture {
            fn on_event(
                &self,
                event: &tracing::Event<'_>,
                _ctx: tracing_subscriber::layer::Context<'_, S>,
            ) {
                if event.metadata().target() != crate::middleware::ACCESS_LOG_TARGET {
                    return;
                }
                let mut fields = std::collections::BTreeMap::new();
                event.record(&mut Visitor(&mut fields));
                self.events.lock().unwrap().push(fields);
            }
        }

        let capture = Capture::default();
        let events = Arc::clone(&capture.events);
        let subscriber = tracing_subscriber::registry().with(capture);

        tracing::subscriber::with_default(subscriber, || {
            // With startup incomplete, the barrier rejects non-probe requests
            // with 503 before the app router runs.
            let state = AppState::for_test()
                .with_profile("test")
                .with_startup_complete(false);
            let app = build_router(Vec::new(), &AutumnConfig::default(), state);
            let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .unwrap();
            let response = rt.block_on(async {
                app.oneshot(
                    Request::builder()
                        .uri("/not-a-probe")
                        .body(Body::empty())
                        .unwrap(),
                )
                .await
                .unwrap()
            });
            assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
        });

        let events = events.lock().unwrap().clone();
        assert_eq!(
            events.len(),
            1,
            "a barrier-rejected request should emit one access event: {events:?}"
        );
        assert_eq!(events[0].get("status").map(String::as_str), Some("503"));
        assert!(
            !events[0].contains_key("request_id"),
            "barrier short-circuits before RequestIdLayer, so no request id"
        );
    }

    #[test]
    fn try_build_router_rejects_invalid_session_backend_config() {
        let mut config = AutumnConfig::default();
        config.session.backend = crate::session::SessionBackend::Redis;

        let error = try_build_router(Vec::new(), &config, test_state())
            .expect_err("missing redis config should fail checked router build");

        assert!(matches!(
            error,
            RouterBuildError::InvalidSessionBackend(
                crate::session::SessionBackendConfigError::MissingRedisUrl
            )
        ));
    }

    #[test]
    fn try_build_router_with_static_rejects_invalid_session_backend_config() {
        let mut config = AutumnConfig::default();
        config.session.backend = crate::session::SessionBackend::Redis;

        let error = try_build_router_with_static(Vec::new(), &config, test_state(), None)
            .expect_err("missing redis config should fail checked static router build");

        assert!(matches!(
            error,
            RouterBuildError::InvalidSessionBackend(
                crate::session::SessionBackendConfigError::MissingRedisUrl
            )
        ));
    }

    #[test]
    fn try_build_router_returns_error_for_probe_actuator_path_overlap() {
        let mut config = AutumnConfig::default();
        config.actuator.prefix = "/".to_owned();

        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            try_build_router(Vec::new(), &config, test_state())
        }));

        assert!(result.is_ok(), "try_build_router panicked on route overlap");
        assert!(
            result.unwrap().is_err(),
            "route overlap should be reported as a checked router build error"
        );
    }

    #[tokio::test]
    async fn apply_cors_middleware_skipped_when_no_origins() {
        let config = AutumnConfig::default();
        assert!(config.cors.allowed_origins.is_empty());

        let base: axum::Router<AppState> =
            axum::Router::new().route("/test", axum::routing::get(|| async { "ok" }));
        let router = apply_cors_middleware(base, &config).with_state(test_state());

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/test")
                    .header("Origin", "https://example.com")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        assert!(
            response
                .headers()
                .get("access-control-allow-origin")
                .is_none(),
            "CORS header must be absent when no origins are configured"
        );
    }

    #[tokio::test]
    async fn apply_cors_middleware_present_when_origins_configured() {
        let mut config = AutumnConfig::default();
        config.cors.allowed_origins = vec!["https://example.com".to_owned()];

        let base: axum::Router<AppState> =
            axum::Router::new().route("/test", axum::routing::get(|| async { "ok" }));
        let router = apply_cors_middleware(base, &config).with_state(test_state());

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/test")
                    .header("Origin", "https://example.com")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        assert!(
            response
                .headers()
                .get("access-control-allow-origin")
                .is_some(),
            "CORS header must be present when origins are configured"
        );
    }

    #[tokio::test]
    async fn apply_cors_middleware_handles_preflight_request() {
        let mut config = AutumnConfig::default();
        config.cors.allowed_origins = vec!["https://example.com".to_owned()];

        let base: axum::Router<AppState> =
            axum::Router::new().route("/api/widgets", axum::routing::post(|| async { "ok" }));
        let router = apply_cors_middleware(base, &config).with_state(test_state());

        let response = router
            .oneshot(
                Request::builder()
                    .method("OPTIONS")
                    .uri("/api/widgets")
                    .header("Origin", "https://example.com")
                    .header("Access-Control-Request-Method", "POST")
                    .header("Access-Control-Request-Headers", "Content-Type")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        let headers = response.headers();
        assert_eq!(
            headers
                .get("access-control-allow-origin")
                .and_then(|v| v.to_str().ok()),
            Some("https://example.com"),
            "preflight must echo the allowed origin"
        );
        assert!(
            headers.get("access-control-allow-methods").is_some(),
            "preflight must advertise allowed methods"
        );
        assert!(
            headers.get("access-control-allow-headers").is_some(),
            "preflight must advertise allowed headers"
        );
        assert!(
            headers.get("access-control-max-age").is_some(),
            "preflight must advertise max-age so browsers can cache it"
        );
    }

    #[tokio::test]
    async fn apply_csrf_middleware_skipped_when_disabled() {
        let config = AutumnConfig::default();
        assert!(!config.security.csrf.enabled);

        let base: axum::Router<AppState> =
            axum::Router::new().route("/form", axum::routing::post(|| async { "posted" }));
        let router = apply_csrf_middleware(base, &config, None).with_state(test_state());

        // Without CSRF the POST should pass through with no CSRF-specific response
        let response = router
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/form")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn apply_rate_limit_middleware_skipped_when_disabled() {
        let config = AutumnConfig::default();
        assert!(!config.security.rate_limit.enabled);

        let base: axum::Router<AppState> =
            axum::Router::new().route("/ping", axum::routing::get(|| async { "pong" }));
        let state = test_state();
        let router = apply_rate_limit_middleware(base, &config, &state).with_state(state.clone());

        // Fire several rapid requests; none should be throttled.
        for _ in 0..5 {
            let response = router
                .clone()
                .oneshot(Request::builder().uri("/ping").body(Body::empty()).unwrap())
                .await
                .unwrap();
            assert_eq!(response.status(), StatusCode::OK);
        }
    }

    #[tokio::test]
    async fn apply_rate_limit_middleware_returns_429_when_exhausted() {
        let mut config = AutumnConfig::default();
        config.security.rate_limit.enabled = true;
        config.security.rate_limit.requests_per_second = 0.1;
        config.security.rate_limit.burst = 1;
        config.security.rate_limit.trust_forwarded_headers = true;

        let base: axum::Router<AppState> =
            axum::Router::new().route("/ping", axum::routing::get(|| async { "pong" }));
        let state = test_state();
        let router = apply_rate_limit_middleware(base, &config, &state).with_state(state.clone());

        let ok = router
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/ping")
                    .header("X-Forwarded-For", "203.0.113.9")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(ok.status(), StatusCode::OK);

        let blocked = router
            .oneshot(
                Request::builder()
                    .uri("/ping")
                    .header("X-Forwarded-For", "203.0.113.9")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(blocked.status(), StatusCode::TOO_MANY_REQUESTS);
        assert!(blocked.headers().get("retry-after").is_some());
    }

    #[cfg(feature = "mcp")]
    #[tokio::test]
    async fn mcp_envelope_is_gated_during_maintenance() {
        use crate::maintenance::{MaintenanceConfig, MaintenanceState};

        // Trust the host the control request sends so that, with maintenance
        // off, the envelope's host guard lets `initialize` through.
        let mut config = AutumnConfig::default();
        config.security.trusted_hosts.hosts = vec!["app.example".to_owned()];

        let wiring = crate::mcp::McpWiring {
            cors: crate::config::CorsConfig::default(),
            trusted_hosts: TrustedHostPolicy::from_config(&config),
            tenant_header: None,
            csrf_header: "x-csrf-token".to_owned(),
            envelope_rate_limited: false,
        };
        let mcp_router =
            crate::mcp::build_mcp_router("/mcp", Vec::new(), axum::Router::new(), wiring, None);

        let initialize = || {
            Request::builder()
                .method("POST")
                .uri("/mcp")
                .header("host", "app.example")
                .header("content-type", "application/json")
                .body(Body::from(
                    serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize"}).to_string(),
                ))
                .unwrap()
        };

        // Maintenance ON: the late-mounted envelope returns the documented 503
        // instead of serving the catalog — the gap this layer closes.
        let state = test_state();
        let maintenance = MaintenanceState::new();
        maintenance.enable(MaintenanceConfig::default());
        state.insert_extension(maintenance);
        let gated = mcp_router
            .clone()
            .layer(build_maintenance_layer(&config, &state))
            .with_state(state);
        let resp = gated.oneshot(initialize()).await.unwrap();
        assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);

        // Maintenance OFF (no enabled state): the same envelope serves
        // `initialize` normally, confirming the gate is the only difference.
        let state = test_state();
        let open = mcp_router
            .layer(build_maintenance_layer(&config, &state))
            .with_state(state);
        let resp = open.oneshot(initialize()).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[cfg(feature = "mail")]
    fn dev_mail_preview_config(dir: &std::path::Path) -> AutumnConfig {
        let mut config = AutumnConfig {
            profile: Some("dev".to_owned()),
            mail: crate::mail::MailConfig {
                transport: crate::mail::Transport::File,
                file_dir: dir.to_path_buf(),
                ..Default::default()
            },
            ..Default::default()
        };
        config.security.trusted_hosts.hosts = vec!["example.com".to_owned()];
        config
    }

    #[cfg(feature = "mail")]
    async fn response_text(response: axum::response::Response) -> String {
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("body should collect");
        String::from_utf8(body.to_vec()).expect("body should be utf8")
    }

    #[cfg(feature = "mail")]
    #[tokio::test]
    async fn build_router_mounts_dev_mail_preview_empty_state_for_file_transport() {
        let dir = tempfile::tempdir().expect("tempdir");
        let config = dev_mail_preview_config(dir.path());
        let router = build_router(Vec::new(), &config, test_state());

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/_autumn/mail")
                    .header("host", "example.com")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let body = response_text(response).await;
        assert!(
            body.contains("No captured emails"),
            "missing empty state: {body}"
        );
        assert!(
            body.contains("mail.transport = &quot;file&quot;"),
            "empty state should explain capture setup: {body}"
        );
    }

    #[cfg(feature = "mail")]
    #[tokio::test]
    async fn build_router_lists_captured_mail_newest_first() {
        let dir = tempfile::tempdir().expect("tempdir");
        let older = dir.path().join("older.eml");
        let newer = dir.path().join("newer.eml");
        std::fs::write(
            &older,
            "To: first@example.com\nSubject: First\nDate: Tue, 05 May 2026 10:00:00 +0000\nMessage-Id: <first@example.com>\n\nfirst body\n",
        )
        .expect("write older eml");
        std::fs::write(
            &newer,
            "To: second@example.com\nSubject: Second\nDate: Tue, 05 May 2026 10:01:00 +0000\nMessage-Id: <second@example.com>\n\nsecond body\n",
        )
        .expect("write newer eml");
        filetime::set_file_mtime(&older, filetime::FileTime::from_unix_time(100, 0))
            .expect("set older mtime");
        filetime::set_file_mtime(&newer, filetime::FileTime::from_unix_time(200, 0))
            .expect("set newer mtime");

        let config = dev_mail_preview_config(dir.path());
        let router = build_router(Vec::new(), &config, test_state());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/_autumn/mail")
                    .header("host", "example.com")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let body = response_text(response).await;
        let second = body.find("Second").expect("newer subject should render");
        let first = body.find("First").expect("older subject should render");
        assert!(second < first, "newest message should render first: {body}");
        assert!(
            body.contains("second@example.com"),
            "missing To column: {body}"
        );
        assert!(
            body.contains("Timestamp"),
            "missing timestamp column: {body}"
        );
    }

    #[cfg(feature = "mail")]
    #[tokio::test]
    async fn build_router_mail_preview_detail_renders_html_in_sandboxed_iframe() {
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(
            dir.path().join("detail.eml"),
            "From: Autumn <noreply@example.com>\nTo: ada@example.com\nReply-To: support@example.com\nSubject: Reset\nDate: Tue, 05 May 2026 10:00:00 +0000\nMessage-Id: <reset@example.com>\nMIME-Version: 1.0\nContent-Type: multipart/alternative; boundary=\"autumn-mail\"\n\n--autumn-mail\nContent-Type: text/plain; charset=utf-8\n\nPlain reset\n--autumn-mail\nContent-Type: text/html; charset=utf-8\n\n<h1>Hello iframe</h1>\n--autumn-mail--\n",
        )
        .expect("write detail eml");

        let config = dev_mail_preview_config(dir.path());
        let router = build_router(Vec::new(), &config, test_state());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/_autumn/mail/messages/detail.eml")
                    .header("host", "example.com")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let body = response_text(response).await;
        assert!(body.contains("<iframe"), "missing iframe: {body}");
        assert!(body.contains("sandbox"), "iframe must be sandboxed: {body}");
        assert!(body.contains("Hello iframe"), "missing html body: {body}");
        assert!(body.contains("Plain text"), "missing text toggle: {body}");
        assert!(body.contains("Headers"), "missing headers toggle: {body}");
        assert!(
            body.contains("Raw .eml"),
            "missing raw source toggle: {body}"
        );
        assert!(
            body.contains("Message-Id"),
            "missing message id header: {body}"
        );
    }

    #[cfg(feature = "mail")]
    #[tokio::test]
    async fn build_router_does_not_mount_mail_preview_outside_dev() {
        let dir = tempfile::tempdir().expect("tempdir");
        let mut config = dev_mail_preview_config(dir.path());
        config.profile = Some("prod".to_owned());
        let router = build_router(Vec::new(), &config, test_state());

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/_autumn/mail")
                    .header("host", "example.com")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn apply_csrf_middleware_blocks_without_token_when_enabled() {
        let mut config = AutumnConfig::default();
        config.security.csrf.enabled = true;

        let base: axum::Router<AppState> =
            axum::Router::new().route("/form", axum::routing::post(|| async { "posted" }));
        let router = apply_csrf_middleware(base, &config, None).with_state(test_state());

        // POST without CSRF token should be rejected
        let response = router
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/form")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_ne!(
            response.status(),
            StatusCode::OK,
            "POST without CSRF token should be rejected when CSRF is enabled"
        );
    }

    #[test]
    fn join_nested_path_normalizes_like_axum() {
        // Reviewer's reported case: scope "/api" + child "/" must
        // produce "/api", not "/api/" — otherwise a user-configured
        // openapi_json_path("/api") won't match the effective mount
        // point and the collision check is unreliable.
        assert_eq!(super::join_nested_path("/api", "/"), "/api");
        // Trailing slash on prefix is stripped.
        assert_eq!(super::join_nested_path("/api/", "/"), "/api");
        // Normal case: prefix + child.
        assert_eq!(super::join_nested_path("/api", "/users"), "/api/users");
        // Trailing slash on prefix + child starting with slash doesn't
        // produce doubled slashes.
        assert_eq!(super::join_nested_path("/api/", "/users"), "/api/users");
        // Root prefix handles sensibly.
        assert_eq!(super::join_nested_path("", "/"), "/");
        assert_eq!(super::join_nested_path("", "/users"), "/users");
    }

    #[cfg(feature = "openapi")]
    #[tokio::test]
    async fn try_build_router_detects_scoped_root_collision() {
        // Scope "/api" + child "/" mounts axum's handler at "/api"
        // (not "/api/"). The collision check must use the same
        // normalization or we'd miss this overlap.
        use crate::openapi::{ApiDoc, OpenApiConfig};
        async fn child() -> &'static str {
            "inner"
        }
        let group = crate::app::ScopedGroup {
            prefix: "/api".to_owned(),
            routes: vec![Route {
                method: http::Method::GET,
                path: "/",
                handler: axum::routing::get(child),
                name: "root",
                api_doc: ApiDoc {
                    method: "GET",
                    path: "/",
                    operation_id: "root",
                    success_status: 200,
                    ..Default::default()
                },
                repository: None,
                idempotency: crate::route::RouteIdempotency::Direct,
                api_version: None,
                sunset_opt_out: false,
            }],
            source: crate::route_listing::RouteSource::User,
            apply_layer: Box::new(|r| r),
        };

        let openapi = OpenApiConfig::new("Demo", "1.0.0").openapi_json_path("/api");
        let config = AutumnConfig::default();
        let ctx = RouterContext {
            exception_filters: Vec::new(),
            scoped_groups: vec![group],
            merge_routers: Vec::new(),
            nest_routers: Vec::new(),
            custom_layers: Vec::new(),
            error_page_renderer: None,
            session_store: None,
            openapi: Some(openapi),
            #[cfg(feature = "mcp")]
            mcp: None,
        };
        let err = super::try_build_router_inner(Vec::new(), &config, test_state(), ctx)
            .expect_err("scope '/api' + child '/' should collide with openapi path '/api'");
        assert!(matches!(
            err,
            RouterBuildError::OpenApiPathCollision {
                field: "openapi_json_path",
                ..
            }
        ));
    }

    #[cfg(feature = "openapi")]
    #[test]
    fn extract_path_params_matches_macro_behavior() {
        assert_eq!(
            super::extract_path_params("/orgs/{org_id}/users/{id}"),
            vec!["org_id".to_owned(), "id".to_owned()]
        );
        assert!(super::extract_path_params("/static").is_empty());
        assert_eq!(
            super::extract_path_params("/users/{id:[0-9]+}"),
            vec!["id".to_owned()]
        );
    }

    #[cfg(feature = "openapi")]
    #[tokio::test]
    async fn openapi_merges_scoped_prefix_path_params() {
        use crate::openapi::{ApiDoc, OpenApiConfig};

        // Scope prefix has `{org_id}`; the child route has `{id}`. The
        // generated ApiDoc must declare BOTH parameters, or Swagger
        // validators reject the document for referencing undeclared
        // path params.
        async fn handler() -> &'static str {
            "ok"
        }
        let child = Route {
            method: http::Method::GET,
            path: "/users/{id}",
            handler: axum::routing::get(handler),
            name: "child",
            api_doc: ApiDoc {
                method: "GET",
                path: "/users/{id}",
                operation_id: "child",
                path_params: &["id"],
                success_status: 200,
                ..Default::default()
            },
            repository: None,
            idempotency: crate::route::RouteIdempotency::Direct,
            api_version: None,
            sunset_opt_out: false,
        };
        let group = crate::app::ScopedGroup {
            prefix: "/orgs/{org_id}".to_owned(),
            routes: vec![child],
            source: crate::route_listing::RouteSource::User,
            apply_layer: Box::new(|r| r),
        };

        let config = OpenApiConfig::new("Demo", "1.0.0");
        let router = super::build_openapi_router(&[], &[group], Some(&config), "autumn.sid", &[])
            .expect("openapi sub-router builds")
            .expect("openapi sub-router present when config is Some");
        let state = test_state();
        let router = router.with_state(state);

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/openapi.json")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let spec: serde_json::Value = serde_json::from_slice(&body).unwrap();
        let params = &spec["paths"]["/orgs/{org_id}/users/{id}"]["get"]["parameters"];
        let names: Vec<&str> = params
            .as_array()
            .unwrap()
            .iter()
            .map(|p| p["name"].as_str().unwrap())
            .collect();
        assert!(names.contains(&"org_id"), "missing org_id: {names:?}");
        assert!(names.contains(&"id"), "missing id: {names:?}");
    }

    #[cfg(feature = "openapi")]
    #[tokio::test]
    async fn openapi_documents_configured_session_cookie_name() {
        use crate::openapi::{ApiDoc, OpenApiConfig};

        async fn handler() -> &'static str {
            "ok"
        }

        let route = Route {
            method: http::Method::GET,
            path: "/protected",
            handler: axum::routing::get(handler),
            name: "protected",
            api_doc: ApiDoc {
                method: "GET",
                path: "/protected",
                operation_id: "protected",
                success_status: 200,
                secured: true,
                ..Default::default()
            },
            repository: None,
            idempotency: crate::route::RouteIdempotency::Direct,
            api_version: None,
            sunset_opt_out: false,
        };

        let protected_routes = vec![route];
        let config = OpenApiConfig::new("Demo", "1.0.0");
        let docs_router =
            super::build_openapi_router(&protected_routes, &[], Some(&config), "demo.sid", &[])
                .expect("openapi sub-router builds")
                .expect("openapi sub-router present when config is Some");
        let docs_router = docs_router.with_state(test_state());

        let response = docs_router
            .oneshot(
                Request::builder()
                    .uri("/openapi.json")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let spec: serde_json::Value = serde_json::from_slice(&body).unwrap();
        let schemes = &spec["components"]["securitySchemes"];

        assert_eq!(schemes["SessionAuth"]["type"], "apiKey");
        assert_eq!(schemes["SessionAuth"]["in"], "cookie");
        assert_eq!(schemes["SessionAuth"]["name"], "demo.sid");
        assert!(
            schemes.get("BearerAuth").is_none(),
            "secured routes must not be documented as bearer JWT routes"
        );
    }

    #[cfg(feature = "openapi")]
    #[test]
    fn openapi_rejects_json_path_without_leading_slash() {
        let config =
            crate::openapi::OpenApiConfig::new("Demo", "1.0.0").openapi_json_path("openapi.json");
        let err = super::build_openapi_router(&[], &[], Some(&config), "autumn.sid", &[])
            .expect_err("non-slash path should be rejected");
        assert!(matches!(
            err,
            RouterBuildError::InvalidOpenApiPath {
                field: "openapi_json_path",
                ..
            }
        ));
    }

    #[cfg(feature = "openapi")]
    #[test]
    fn openapi_rejects_path_with_captures() {
        // `{id}` captures would be a typo for a mount path — the
        // endpoints are static. Catch it before axum panics.
        let config =
            crate::openapi::OpenApiConfig::new("Demo", "1.0.0").openapi_json_path("/docs/{id}");
        let err = super::build_openapi_router(&[], &[], Some(&config), "autumn.sid", &[])
            .expect_err("captures should be rejected");
        assert!(matches!(err, RouterBuildError::InvalidOpenApiPath { .. }));
    }

    #[cfg(feature = "openapi")]
    #[test]
    fn openapi_rejects_path_with_unbalanced_brace() {
        let config =
            crate::openapi::OpenApiConfig::new("Demo", "1.0.0").openapi_json_path("/docs/{id");
        let err = super::build_openapi_router(&[], &[], Some(&config), "autumn.sid", &[])
            .expect_err("unbalanced brace should be rejected");
        assert!(matches!(err, RouterBuildError::InvalidOpenApiPath { .. }));
    }

    #[cfg(feature = "openapi")]
    #[test]
    fn openapi_rejects_path_with_wildcard() {
        let config =
            crate::openapi::OpenApiConfig::new("Demo", "1.0.0").openapi_json_path("/docs/*rest");
        let err = super::build_openapi_router(&[], &[], Some(&config), "autumn.sid", &[])
            .expect_err("wildcard should be rejected");
        assert!(matches!(err, RouterBuildError::InvalidOpenApiPath { .. }));
    }

    #[cfg(feature = "openapi")]
    #[test]
    fn openapi_rejects_path_with_double_slash() {
        let config =
            crate::openapi::OpenApiConfig::new("Demo", "1.0.0").openapi_json_path("//docs");
        let err = super::build_openapi_router(&[], &[], Some(&config), "autumn.sid", &[])
            .expect_err("double-slash should be rejected");
        assert!(matches!(err, RouterBuildError::InvalidOpenApiPath { .. }));
    }

    #[cfg(feature = "openapi")]
    #[test]
    fn openapi_rejects_swagger_ui_path_without_leading_slash() {
        let config = crate::openapi::OpenApiConfig::new("Demo", "1.0.0")
            .swagger_ui_path(Some("docs".to_owned()));
        let err = super::build_openapi_router(&[], &[], Some(&config), "autumn.sid", &[])
            .expect_err("non-slash path should be rejected");
        assert!(matches!(
            err,
            RouterBuildError::InvalidOpenApiPath {
                field: "swagger_ui_path",
                ..
            }
        ));
    }

    #[cfg(feature = "openapi")]
    #[test]
    fn openapi_rejects_empty_json_path() {
        let config = crate::openapi::OpenApiConfig::new("Demo", "1.0.0").openapi_json_path("");
        let err = super::build_openapi_router(&[], &[], Some(&config), "autumn.sid", &[])
            .expect_err("empty path should be rejected");
        assert!(matches!(err, RouterBuildError::InvalidOpenApiPath { .. }));
    }

    #[cfg(feature = "openapi")]
    #[test]
    fn openapi_accepts_valid_paths() {
        let config = crate::openapi::OpenApiConfig::new("Demo", "1.0.0")
            .openapi_json_path("/api-docs")
            .swagger_ui_path(Some("/ui".to_owned()));
        let out = super::build_openapi_router(&[], &[], Some(&config), "autumn.sid", &[])
            .expect("valid paths must not error");
        assert!(out.is_some());
    }

    #[cfg(feature = "openapi")]
    #[test]
    fn openapi_rejects_duplicate_json_and_swagger_paths() {
        let config = crate::openapi::OpenApiConfig::new("Demo", "1.0.0")
            .openapi_json_path("/docs")
            .swagger_ui_path(Some("/docs".to_owned()));
        let err = super::build_openapi_router(&[], &[], Some(&config), "autumn.sid", &[])
            .expect_err("colliding paths should be rejected before axum panics");
        assert!(matches!(
            err,
            RouterBuildError::DuplicateOpenApiPath { ref path } if path == "/docs"
        ));
    }

    #[cfg(feature = "openapi")]
    async fn collision_test_handler() -> &'static str {
        "user"
    }

    #[cfg(feature = "openapi")]
    #[tokio::test]
    async fn try_build_router_rejects_openapi_path_colliding_with_user_route() {
        let mut config = AutumnConfig::default();
        config.actuator.prefix = "/ops".to_owned();
        let openapi =
            crate::openapi::OpenApiConfig::new("Demo", "1.0.0").openapi_json_path("/my-api-docs");

        let user_route = Route {
            method: http::Method::GET,
            path: "/my-api-docs",
            handler: axum::routing::get(collision_test_handler),
            name: "collides",
            api_doc: crate::openapi::ApiDoc {
                method: "GET",
                path: "/my-api-docs",
                operation_id: "collides",
                success_status: 200,
                ..Default::default()
            },
            repository: None,
            idempotency: crate::route::RouteIdempotency::Direct,
            api_version: None,
            sunset_opt_out: false,
        };

        let ctx = RouterContext {
            exception_filters: Vec::new(),
            scoped_groups: Vec::new(),
            merge_routers: Vec::new(),
            nest_routers: Vec::new(),
            custom_layers: Vec::new(),
            error_page_renderer: None,
            session_store: None,
            openapi: Some(openapi),
            #[cfg(feature = "mcp")]
            mcp: None,
        };
        let err = super::try_build_router_inner(vec![user_route], &config, test_state(), ctx)
            .expect_err("user-owned path should prevent OpenAPI mount");
        assert!(matches!(
            err,
            RouterBuildError::OpenApiPathCollision { field: "openapi_json_path", ref path } if path == "/my-api-docs"
        ));
    }

    #[cfg(feature = "openapi")]
    #[tokio::test]
    async fn try_build_router_rejects_openapi_path_colliding_with_framework_route() {
        let config = AutumnConfig::default(); // /actuator/health is a GET by default
        let openapi = crate::openapi::OpenApiConfig::new("Demo", "1.0.0")
            .openapi_json_path("/actuator/health");
        let ctx = RouterContext {
            exception_filters: Vec::new(),
            scoped_groups: Vec::new(),
            merge_routers: Vec::new(),
            nest_routers: Vec::new(),
            custom_layers: Vec::new(),
            error_page_renderer: None,
            session_store: None,
            openapi: Some(openapi),
            #[cfg(feature = "mcp")]
            mcp: None,
        };
        let err = super::try_build_router_inner(Vec::new(), &config, test_state(), ctx)
            .expect_err("framework-owned path should prevent OpenAPI mount");
        assert!(matches!(
            err,
            RouterBuildError::OpenApiPathCollision {
                field: "openapi_json_path",
                ..
            }
        ));
    }

    #[cfg(feature = "openapi")]
    #[tokio::test]
    async fn try_build_router_rejects_swagger_ui_asset_path_colliding_with_user_route() {
        let config = AutumnConfig::default();
        let openapi = crate::openapi::OpenApiConfig::new("Demo", "1.0.0");

        let user_route = Route {
            method: http::Method::GET,
            path: "/swagger-ui/swagger-ui.css",
            handler: axum::routing::get(collision_test_handler),
            name: "swagger-ui-asset-collides",
            api_doc: crate::openapi::ApiDoc {
                method: "GET",
                path: "/swagger-ui/swagger-ui.css",
                operation_id: "swagger_ui_asset_collides",
                success_status: 200,
                ..Default::default()
            },
            repository: None,
            idempotency: crate::route::RouteIdempotency::Direct,
            api_version: None,
            sunset_opt_out: false,
        };

        let ctx = RouterContext {
            exception_filters: Vec::new(),
            scoped_groups: Vec::new(),
            merge_routers: Vec::new(),
            nest_routers: Vec::new(),
            custom_layers: Vec::new(),
            error_page_renderer: None,
            session_store: None,
            openapi: Some(openapi),
            #[cfg(feature = "mcp")]
            mcp: None,
        };
        let err = super::try_build_router_inner(vec![user_route], &config, test_state(), ctx)
            .expect_err("swagger ui asset path should be reserved");
        assert!(matches!(
            err,
            RouterBuildError::OpenApiPathCollision {
                field: "swagger_ui_path",
                ref path,
            } if path == "/swagger-ui/swagger-ui.css"
        ));
    }

    #[cfg(all(feature = "openapi", feature = "htmx"))]
    #[tokio::test]
    async fn try_build_router_rejects_openapi_path_colliding_with_htmx_csrf_route() {
        let config = AutumnConfig::default();
        let openapi = crate::openapi::OpenApiConfig::new("Demo", "1.0.0")
            .openapi_json_path(crate::htmx::HTMX_CSRF_JS_PATH);
        let ctx = RouterContext {
            exception_filters: Vec::new(),
            scoped_groups: Vec::new(),
            merge_routers: Vec::new(),
            nest_routers: Vec::new(),
            custom_layers: Vec::new(),
            error_page_renderer: None,
            session_store: None,
            openapi: Some(openapi),
            #[cfg(feature = "mcp")]
            mcp: None,
        };
        let err = super::try_build_router_inner(Vec::new(), &config, test_state(), ctx)
            .expect_err("htmx csrf helper path should be reserved");
        assert!(matches!(
            err,
            RouterBuildError::OpenApiPathCollision {
                field: "openapi_json_path",
                ref path,
            } if path == crate::htmx::HTMX_CSRF_JS_PATH
        ));
    }

    #[cfg(feature = "openapi")]
    #[tokio::test]
    async fn try_build_router_rejects_openapi_path_under_nest_prefix() {
        // Nesting `/api` means that router owns everything under
        // `/api/...`. Mounting OpenAPI at `/api/docs` would either
        // panic on merge or silently lose one of the routes, so the
        // collision check rejects it.
        let config = AutumnConfig::default();
        let openapi =
            crate::openapi::OpenApiConfig::new("Demo", "1.0.0").openapi_json_path("/api/docs");
        let nested = axum::Router::<AppState>::new()
            .route("/inner", axum::routing::get(|| async { "inner" }));
        let ctx = RouterContext {
            exception_filters: Vec::new(),
            scoped_groups: Vec::new(),
            merge_routers: Vec::new(),
            nest_routers: vec![("/api".to_owned(), nested)],
            custom_layers: Vec::new(),
            error_page_renderer: None,
            session_store: None,
            openapi: Some(openapi),
            #[cfg(feature = "mcp")]
            mcp: None,
        };
        let err = super::try_build_router_inner(Vec::new(), &config, test_state(), ctx)
            .expect_err("OpenAPI path under a nest prefix should collide");
        assert!(matches!(
            err,
            RouterBuildError::OpenApiPathCollision {
                field: "openapi_json_path",
                ref path,
            } if path == "/api/docs"
        ));
    }

    #[cfg(feature = "openapi")]
    #[test]
    fn try_build_router_rejects_openapi_path_on_dev_live_reload() {
        temp_env::with_vars(
            [
                ("AUTUMN_DEV_RELOAD", Some("1")),
                ("AUTUMN_DEV_RELOAD_STATE", Some("/tmp/autumn-reload-test")),
            ],
            || {
                let config = AutumnConfig::default();
                let openapi = crate::openapi::OpenApiConfig::new("Demo", "1.0.0")
                    .openapi_json_path("/__autumn/live-reload");
                let ctx = RouterContext {
                    exception_filters: Vec::new(),
                    scoped_groups: Vec::new(),
                    merge_routers: Vec::new(),
                    nest_routers: Vec::new(),
                    custom_layers: Vec::new(),
                    error_page_renderer: None,
                    session_store: None,
                    openapi: Some(openapi),
                    #[cfg(feature = "mcp")]
                    mcp: None,
                };
                let err = super::try_build_router_inner(Vec::new(), &config, test_state(), ctx)
                    .expect_err("dev reload path should be reserved");
                assert!(matches!(
                    err,
                    RouterBuildError::OpenApiPathCollision {
                        field: "openapi_json_path",
                        ..
                    }
                ));
            },
        );
    }

    // --- Static file serving (SSG/ISG) tests ---

    fn create_static_dist(revalidate: Option<u64>) -> tempfile::TempDir {
        let dir = tempfile::tempdir().expect("tempdir");
        let dist = dir.path().join("dist");
        std::fs::create_dir_all(dist.join("about")).expect("mkdir about");
        std::fs::write(dist.join("index.html"), b"<h1>Home</h1>").expect("write index");
        std::fs::write(dist.join("about/index.html"), b"<h1>About</h1>").expect("write about");

        let mut routes = std::collections::HashMap::new();
        routes.insert(
            "/".to_owned(),
            crate::static_gen::ManifestEntry {
                file: "index.html".to_owned(),
                revalidate: None,
            },
        );
        routes.insert(
            "/about".to_owned(),
            crate::static_gen::ManifestEntry {
                file: "about/index.html".to_owned(),
                revalidate,
            },
        );

        let manifest = crate::static_gen::StaticManifest {
            generated_at: "2026-05-18T00:00:00Z".to_owned(),
            autumn_version: "0.5.0".to_owned(),
            routes,
        };
        let json = serde_json::to_string(&manifest).expect("serialize manifest");
        std::fs::write(dist.join("manifest.json"), json).expect("write manifest");
        dir
    }

    #[tokio::test]
    async fn static_serving_serves_get_request_inside_user_layers() {
        let tmp = create_static_dist(None);
        let dist = tmp.path().join("dist");
        let config = AutumnConfig::default();

        let router = try_build_router_with_static(Vec::new(), &config, test_state(), Some(&dist))
            .expect("router builds");

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/about")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_eq!(body.as_ref(), b"<h1>About</h1>");
    }

    #[tokio::test]
    async fn static_serving_serves_head_request() {
        let tmp = create_static_dist(None);
        let dist = tmp.path().join("dist");
        let config = AutumnConfig::default();

        let router = try_build_router_with_static(Vec::new(), &config, test_state(), Some(&dist))
            .expect("router builds");

        let response = router
            .oneshot(
                Request::builder()
                    .method("HEAD")
                    .uri("/about")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        assert!(body.is_empty(), "HEAD response body should be empty");
    }

    #[tokio::test]
    async fn static_serving_normalizes_trailing_slash() {
        let tmp = create_static_dist(None);
        let dist = tmp.path().join("dist");
        let config = AutumnConfig::default();

        let router = try_build_router_with_static(Vec::new(), &config, test_state(), Some(&dist))
            .expect("router builds");

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/about/")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn static_serving_falls_through_for_unknown_route() {
        let tmp = create_static_dist(None);
        let dist = tmp.path().join("dist");
        let config = AutumnConfig::default();

        let router = try_build_router_with_static(Vec::new(), &config, test_state(), Some(&dist))
            .expect("router builds");

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/not-in-manifest")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn static_serving_skipped_when_no_manifest() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let dist = tmp.path().join("dist");
        std::fs::create_dir_all(&dist).expect("mkdir dist");
        let config = AutumnConfig::default();

        let router = try_build_router_with_static(Vec::new(), &config, test_state(), Some(&dist))
            .expect("router builds even without manifest");

        let response = router
            .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn static_serving_with_isr_manifest_builds_successfully() {
        let tmp = create_static_dist(Some(3600));
        let dist = tmp.path().join("dist");
        let config = AutumnConfig::default();

        let router = try_build_router_with_static(Vec::new(), &config, test_state(), Some(&dist))
            .expect("router with ISR manifest should build");

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/about")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }
}

#[cfg(test)]
mod trusted_host_tests {
    use super::*;
    use axum::body::Body;
    use http::Request;
    use tower::util::ServiceExt;

    #[tokio::test]
    async fn trusted_host_allows_matching_and_blocks_nonmatching() {
        let mut cfg = AutumnConfig::default();
        cfg.security.trusted_hosts.hosts = vec!["example.com".into(), ".example.com".into()];
        let state = crate::state::AppState::for_test();
        let router = build_router(vec![], &cfg, state);

        let ok = router
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/nope")
                    .header("host", "api.example.com")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(ok.status(), StatusCode::NOT_FOUND);

        let blocked = router
            .oneshot(
                Request::builder()
                    .uri("/nope")
                    .header("host", "evil.com")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(blocked.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn trusted_host_wildcard_allows_any_host() {
        let mut cfg = AutumnConfig::default();
        cfg.security.trusted_hosts.hosts = vec!["*".into()];
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/nope")
                    .header("host", "anything.example")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn trusted_host_bypasses_probe_paths() {
        let mut cfg = AutumnConfig::default();
        cfg.security.trusted_hosts.hosts = vec!["example.com".into()];
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/actuator/health")
                    .header("host", "evil.com")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn trusted_host_bypasses_actuator_health_path() {
        let mut cfg = AutumnConfig::default();
        cfg.security.trusted_hosts.hosts = vec!["example.com".into()];
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/actuator/health")
                    .header("host", "evil.com")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn trusted_host_release_rejects_loopback_unless_listed() {
        let mut cfg = AutumnConfig {
            profile: Some("prod".into()),
            ..AutumnConfig::default()
        };
        cfg.security.trusted_hosts.hosts = vec!["example.com".into()];
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/nope")
                    .header("host", "localhost")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn trusted_host_uses_uri_authority_when_host_header_missing() {
        let mut cfg = AutumnConfig::default();
        cfg.security.trusted_hosts.hosts = vec!["example.com".into()];
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("http://EXAMPLE.COM/nope")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn trusted_host_accepts_bracketed_ipv6_loopback_in_dev() {
        let cfg = AutumnConfig::default();
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/nope")
                    .header("host", "[::1]:3000")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn trusted_host_matching_is_case_insensitive() {
        let mut cfg = AutumnConfig::default();
        cfg.security.trusted_hosts.hosts = vec!["example.com".into()];
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/nope")
                    .header("host", "EXAMPLE.COM")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn trusted_host_rejects_malformed_port() {
        let mut cfg = AutumnConfig::default();
        cfg.security.trusted_hosts.hosts = vec!["example.com".into()];
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/nope")
                    .header("host", "example.com:abc")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn trusted_host_rejects_empty_port_suffix() {
        let mut cfg = AutumnConfig::default();
        cfg.security.trusted_hosts.hosts = vec!["example.com".into()];
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/nope")
                    .header("host", "example.com:")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn trusted_host_rejects_bracketed_reg_name() {
        let mut cfg = AutumnConfig::default();
        cfg.security.trusted_hosts.hosts = vec!["example.com".into()];
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/nope")
                    .header("host", "[example.com]")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }
    #[tokio::test]
    async fn trusted_host_configured_trailing_dot_matches_normalized_host() {
        let mut cfg = AutumnConfig::default();
        cfg.security.trusted_hosts.hosts = vec!["example.com.".into()];
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/nope")
                    .header("host", "example.com")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn trusted_host_accepts_trailing_dot_fqdn() {
        let mut cfg = AutumnConfig::default();
        cfg.security.trusted_hosts.hosts = vec!["example.com".into()];
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/nope")
                    .header("host", "example.com.")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn trusted_host_bypasses_custom_probe_path_only() {
        let mut cfg = AutumnConfig::default();
        cfg.security.trusted_hosts.hosts = vec!["example.com".into()];
        cfg.health.path = "/healthz".into();
        cfg.health.startup_path = "/startupz".into();
        cfg.health.ready_path = "/readyz".into();
        cfg.health.live_path = "/livez".into();
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());

        let bypassed = router
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/healthz")
                    .header("host", "evil.com")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(bypassed.status(), StatusCode::OK);

        let not_bypassed = router
            .oneshot(
                Request::builder()
                    .uri("/health")
                    .header("host", "evil.com")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(not_bypassed.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn trusted_host_does_not_bypass_non_get_probe_path_requests() {
        let mut cfg = AutumnConfig::default();
        cfg.security.trusted_hosts.hosts = vec!["example.com".into()];
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());
        let response = router
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/health")
                    .header("host", "evil.com")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }

    // ── Global body-size limit (AC: DefaultBodyLimit covers all content types) ──

    #[tokio::test]
    async fn apply_upload_middleware_rejects_oversized_json_body() {
        let mut config = AutumnConfig::default();
        config.security.upload.max_request_size_bytes = 100; // 100-byte limit

        let base: axum::Router<AppState> = axum::Router::new().route(
            "/data",
            axum::routing::post(|_: axum::body::Bytes| async { "ok" }),
        );
        let router =
            apply_upload_middleware(base, &config).with_state(crate::state::AppState::for_test());

        // 200 bytes of JSON-shaped content exceeds the 100-byte cap.
        let big_body = "x".repeat(200);
        let response = router
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/data")
                    .header("content-type", "application/json")
                    .body(Body::from(big_body))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(
            response.status(),
            StatusCode::PAYLOAD_TOO_LARGE,
            "oversized body must be rejected with 413 regardless of content type"
        );
    }

    #[tokio::test]
    async fn apply_upload_middleware_accepts_body_within_limit() {
        let mut config = AutumnConfig::default();
        config.security.upload.max_request_size_bytes = 1024;

        let base: axum::Router<AppState> = axum::Router::new().route(
            "/data",
            axum::routing::post(|_: axum::body::Bytes| async { "ok" }),
        );
        let router =
            apply_upload_middleware(base, &config).with_state(crate::state::AppState::for_test());

        let response = router
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/data")
                    .header("content-type", "application/json")
                    .body(Body::from("hello"))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    // ── Per-request timeout (AC: 408 on timeout, metrics, WARN log) ──────────

    #[tokio::test(start_paused = true)]
    async fn request_timeout_returns_408_when_exceeded() {
        let mut config = AutumnConfig::default();
        config.server.timeouts.request_timeout_ms = Some(100);

        let state = crate::state::AppState::for_test();
        let router: axum::Router<AppState> = axum::Router::new().route(
            "/slow",
            axum::routing::get(|| async {
                // This sleep is much longer than the 100ms timeout.
                tokio::time::sleep(std::time::Duration::from_secs(60)).await;
                "ok"
            }),
        );

        // Place timeout inner to RequestIdLayer (matches apply_middleware ordering).
        let router = apply_request_timeout_middleware(router, &config, state.metrics.clone())
            .layer(RequestIdLayer)
            .with_state(state);

        let response = router
            .oneshot(Request::builder().uri("/slow").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(
            response.status(),
            StatusCode::REQUEST_TIMEOUT,
            "a slow handler must trigger 408"
        );
        assert_eq!(
            response
                .headers()
                .get("content-type")
                .and_then(|v| v.to_str().ok()),
            Some("application/problem+json"),
            "timeout response must use Problem Details content type"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn request_timeout_increments_metric() {
        let mut config = AutumnConfig::default();
        config.server.timeouts.request_timeout_ms = Some(100);

        let state = crate::state::AppState::for_test();
        let router: axum::Router<AppState> = axum::Router::new().route(
            "/slow",
            axum::routing::get(|| async {
                tokio::time::sleep(std::time::Duration::from_secs(60)).await;
                "ok"
            }),
        );

        let router = apply_request_timeout_middleware(router, &config, state.metrics.clone())
            .layer(RequestIdLayer)
            .with_state(state.clone());

        router
            .oneshot(Request::builder().uri("/slow").body(Body::empty()).unwrap())
            .await
            .unwrap();

        let snap = state.metrics.snapshot();
        assert_eq!(
            snap.http.request_timeouts_total, 1,
            "autumn_request_timeouts_total must be incremented on timeout"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn request_timeout_response_includes_request_id() {
        let mut config = AutumnConfig::default();
        config.server.timeouts.request_timeout_ms = Some(100);

        let state = crate::state::AppState::for_test();
        let router: axum::Router<AppState> = axum::Router::new().route(
            "/slow",
            axum::routing::get(|| async {
                tokio::time::sleep(std::time::Duration::from_secs(60)).await;
                "ok"
            }),
        );

        let router = apply_request_timeout_middleware(router, &config, state.metrics.clone())
            .layer(RequestIdLayer)
            .with_state(state);

        let response = router
            .oneshot(Request::builder().uri("/slow").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::REQUEST_TIMEOUT);
        // X-Request-Id is added by RequestIdLayer on the egress path.
        assert!(
            response.headers().contains_key("x-request-id"),
            "408 response must carry the X-Request-Id header"
        );

        // The body must be valid JSON with a request_id field.
        let body_bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let body: serde_json::Value = serde_json::from_slice(&body_bytes).unwrap();
        assert_eq!(body["status"], 408);
    }

    #[tokio::test]
    async fn request_timeout_disabled_when_none() {
        let config = AutumnConfig::default(); // request_timeout_ms = None

        let state = crate::state::AppState::for_test();
        let router: axum::Router<AppState> =
            axum::Router::new().route("/fast", axum::routing::get(|| async { "pong" }));

        let router = apply_request_timeout_middleware(router, &config, state.metrics.clone())
            .with_state(state);

        let response = router
            .oneshot(Request::builder().uri("/fast").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn request_timeout_zero_treated_as_disabled() {
        let mut config = AutumnConfig::default();
        config.server.timeouts.request_timeout_ms = Some(0); // 0 = disabled

        let state = crate::state::AppState::for_test();
        let router: axum::Router<AppState> =
            axum::Router::new().route("/fast", axum::routing::get(|| async { "pong" }));

        let router = apply_request_timeout_middleware(router, &config, state.metrics.clone())
            .with_state(state);

        let response = router
            .oneshot(Request::builder().uri("/fast").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    // Exercises the warn!("Request timed out") branch when no RequestIdLayer
    // is present (no request_id extension), keeping coverage of the else arm.
    #[tokio::test(start_paused = true)]
    async fn request_timeout_408_without_request_id_layer() {
        let mut config = AutumnConfig::default();
        config.server.timeouts.request_timeout_ms = Some(100);

        let state = crate::state::AppState::for_test();
        let router: axum::Router<AppState> = axum::Router::new().route(
            "/slow",
            axum::routing::get(|| async {
                tokio::time::sleep(std::time::Duration::from_secs(60)).await;
                "ok"
            }),
        );

        // No RequestIdLayer — exercises the else branch in request_timeout_handler.
        let router = apply_request_timeout_middleware(router, &config, state.metrics.clone())
            .with_state(state);

        let response = router
            .oneshot(Request::builder().uri("/slow").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::REQUEST_TIMEOUT);
    }
}
#[derive(Clone, Debug)]
pub struct TrustedHostPolicy {
    rules: Arc<Vec<String>>,
    allow_any: bool,
    allow_missing_host: bool,
    probe_bypass_paths: Arc<std::collections::HashSet<String>>,
}

impl TrustedHostPolicy {
    pub fn from_config(config: &AutumnConfig) -> Self {
        let mut rules: Vec<String> = config
            .security
            .trusted_hosts
            .hosts
            .iter()
            .map(|h| h.trim().to_ascii_lowercase())
            .map(|h| h.trim_end_matches('.').to_owned())
            .filter(|h| !h.is_empty())
            .collect();
        let is_production = matches!(config.profile.as_deref(), Some("prod" | "production"));
        if !is_production {
            rules.extend(
                ["localhost", "127.0.0.1", "::1"]
                    .into_iter()
                    .map(std::borrow::ToOwned::to_owned),
            );
        }
        let allow_any = rules.iter().any(|h| h == "*");
        let probe_bypass_paths = std::collections::HashSet::from([
            config.health.path.clone(),
            config.health.live_path.clone(),
            config.health.ready_path.clone(),
            config.health.startup_path.clone(),
            crate::actuator::actuator_route_path(&config.actuator.prefix, "/health"),
        ]);
        Self {
            rules: Arc::new(rules),
            allow_any,
            allow_missing_host: !is_production,
            probe_bypass_paths: Arc::new(probe_bypass_paths),
        }
    }

    /// Whether a request carrying no usable `Host` is allowed through. Mirrors
    /// `trusted_host_middleware`'s missing-host branch for callers (e.g. the MCP
    /// envelope) that enforce the policy outside that middleware.
    ///
    /// Only the `mcp` feature consumes this today; gated so default-feature
    /// builds don't flag it as dead code.
    #[cfg(feature = "mcp")]
    pub const fn allows_missing_host(&self) -> bool {
        self.allow_missing_host
    }

    pub fn allows_host(&self, host: &str) -> bool {
        if self.allow_any {
            return true;
        }
        self.rules.iter().any(|rule| {
            rule.strip_prefix('.').map_or_else(
                || host == rule,
                |suffix| {
                    host == suffix
                        || host
                            .strip_suffix(suffix)
                            .is_some_and(|prefix| prefix.ends_with('.'))
                },
            )
        })
    }
}

/// Metadata carrying API version, sunset opt-out, and security configuration for a route.
#[derive(Clone, Debug)]
pub struct RouteVersionMetadata {
    pub version: String,
    pub sunset_opt_out: bool,
    pub secured: bool,
    pub required_roles: &'static [&'static str],
    pub has_policy: bool,
}

/// Middleware that handles API deprecation, sunsets, and Gone responses.
async fn api_versioning_middleware(
    state: axum::extract::State<AppState>,
    route_version: Option<axum::extract::Extension<RouteVersionMetadata>>,
    request: axum::http::Request<axum::body::Body>,
    next: axum::middleware::Next,
) -> axum::response::Response {
    let Some(axum::extract::Extension(meta)) = route_version else {
        return next.run(request).await;
    };

    let clock = state.clock();
    let now = clock.now();

    let versions = state.extension::<crate::app::RegisteredApiVersions>();
    let matching_version = versions
        .as_ref()
        .and_then(|v| v.0.iter().find(|av| av.version == meta.version));

    let Some(version) = matching_version else {
        return next.run(request).await;
    };

    let is_deprecated = version.deprecated_at.is_some_and(|d| now >= d);
    let is_sunset = version.sunset_at.is_some_and(|s| now >= s);

    if is_sunset && !meta.sunset_opt_out {
        if meta.has_policy {
            return next.run(request).await;
        }
        if meta.secured {
            let session = request.extensions().get::<crate::session::Session>();
            let mut auth_failed = false;
            let mut auth_error = None;
            if let Some(session) = session {
                if let Err(err) = crate::auth::__check_secured_with_key(
                    session,
                    state.auth_session_key(),
                    meta.required_roles,
                )
                .await
                {
                    auth_failed = true;
                    auth_error = Some(err);
                }
            } else {
                auth_failed = true;
                auth_error = Some(crate::error::AutumnError::unauthorized_msg(
                    "authentication required",
                ));
            }
            if auth_failed {
                return auth_error.unwrap().into_response();
            }
        }

        let err = crate::error::AutumnError::gone_msg(format!(
            "API version '{}' has been sunsetted.",
            meta.version
        ));
        let mut response = err.into_response();
        if let Some(sunset) = version.sunset_at {
            let http_date = sunset.format("%a, %d %b %Y %H:%M:%S GMT").to_string();
            if let Ok(val) = axum::http::HeaderValue::from_str(&http_date) {
                response.headers_mut().insert("Sunset", val);
            }
        }
        let deprecation_date = match (version.deprecated_at, version.sunset_at) {
            (Some(d), Some(s)) => Some(d.min(s)),
            (d, s) => d.or(s),
        };
        if let Some(date) = deprecation_date {
            let timestamp = date.timestamp();
            if let Ok(val) = axum::http::HeaderValue::from_str(&format!("@{timestamp}")) {
                response.headers_mut().insert("Deprecation", val);
            }
        }
        return response;
    }

    let mut response = next.run(request).await;

    if is_deprecated || is_sunset {
        let deprecation_date = match (version.deprecated_at, version.sunset_at) {
            (Some(d), Some(s)) => Some(d.min(s)),
            (d, s) => d.or(s),
        };
        if let Some(date) = deprecation_date {
            let timestamp = date.timestamp();
            if let Ok(val) = axum::http::HeaderValue::from_str(&format!("@{timestamp}")) {
                response.headers_mut().insert("Deprecation", val);
            }
        }
    }
    if let Some(sunset) = version.sunset_at.filter(|_| is_deprecated || is_sunset) {
        let http_date = sunset.format("%a, %d %b %Y %H:%M:%S GMT").to_string();
        if let Ok(val) = axum::http::HeaderValue::from_str(&http_date) {
            response.headers_mut().insert("Sunset", val);
        }
    }

    response
}

/// Helper function to perform a sunset check during dynamic handler execution.
/// Returns a `410 Gone` response if the route version has sunsetted.
#[must_use]
pub fn check_sunset(
    state: &crate::state::AppState,
    meta: &RouteVersionMetadata,
) -> Option<axum::response::Response> {
    let clock = state.clock();
    let now = clock.now();

    let versions = state.extension::<crate::app::RegisteredApiVersions>();
    let matching_version = versions
        .as_ref()
        .and_then(|v| v.0.iter().find(|av| av.version == meta.version));

    let version = matching_version?;
    let is_sunset = version.sunset_at.is_some_and(|s| now >= s);

    if is_sunset && !meta.sunset_opt_out {
        let err = crate::error::AutumnError::gone_msg(format!(
            "API version '{}' has been sunsetted.",
            meta.version
        ));
        let mut response = axum::response::IntoResponse::into_response(err);
        if let Some(sunset) = version.sunset_at {
            let http_date = sunset.format("%a, %d %b %Y %H:%M:%S GMT").to_string();
            if let Ok(val) = axum::http::HeaderValue::from_str(&http_date) {
                response.headers_mut().insert("Sunset", val);
            }
        }
        let deprecation_date = match (version.deprecated_at, version.sunset_at) {
            (Some(d), Some(s)) => Some(d.min(s)),
            (d, s) => d.or(s),
        };
        if let Some(date) = deprecation_date {
            let timestamp = date.timestamp();
            if let Ok(val) = axum::http::HeaderValue::from_str(&format!("@{timestamp}")) {
                response.headers_mut().insert("Deprecation", val);
            }
        }
        return Some(response);
    }

    None
}