keysink 0.1.4

Local gateway that keeps real AI API keys out of agents (Claude Code, OpenAI, MCP): agents hold revocable virtual keys, real keys stay in an encrypted vault.
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
use crate::audit::{Audit, AuditEntry};
use crate::error::{Error, Result};
use crate::model::{Auth, Route, Store, Terminator};
use crate::retry::{RetryPolicy, parse_retry_after};
use crate::store::Paths;
use crate::vkey::{self, RouteTable};
use arc_swap::ArcSwap;
use axum::body::Body;
use axum::extract::{Request, State};
use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use axum::{Json, Router};
use base64::Engine;
use bytes::Bytes;
use futures_util::{StreamExt, stream};
use serde_json::json;
use std::collections::{HashMap, HashSet};
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
use tokio::io::{AsyncReadExt, ReadBuf};
use tracing::Instrument;
use zeroize::Zeroizing;

static REQ_SEQ: AtomicU64 = AtomicU64::new(1);

/// Read-idle timeout for streaming (SSE) clients: if the upstream sends no
/// bytes for this long, it is deemed hung. Applies only to the streaming
/// client — at the client level, non-streaming requests must not set a read
/// idle, because reqwest applies it to the response-header wait too: slow
/// models that only send response headers after generation completes
/// (non-streaming long reasoning) would be killed at 60s and then retried as
/// a network error POST (double billing). The header wait is backstopped by
/// the outer header_timeout (tokio timeout) instead.
const STREAM_READ_TIMEOUT: Duration = Duration::from_secs(60);

/// Read-idle bound for a non-streaming response body, applied per chunk at
/// the passthrough layer (see `idle_bounded`). The plain client has no
/// client-level read_timeout (see STREAM_READ_TIMEOUT), so without this an
/// upstream that sends response headers and then goes silent mid-body would
/// hang the handler forever — and with it, graceful shutdown. Aligned with
/// the header-phase bound on purpose: one story, "no upstream progress ⇒
/// give up". SSE bodies are bounded by STREAM_READ_TIMEOUT instead.
pub const BODY_READ_IDLE: Duration = crate::retry::DEFAULT_HEADER_TIMEOUT;

/// Whole-head bound on the inbound request from an agent client: a
/// connection that never finishes sending its head (slowloris) is closed
/// within this window. Bounds the head as a whole, matching hyper-util's
/// semantics (not per read).
pub const CLIENT_HEADER_TIMEOUT: Duration = Duration::from_secs(30);

/// Whole-body bound on the handler reading the inbound request body: a
/// client that trickles a body forever gets a 408 instead of holding the
/// handler (and its buffered bytes) indefinitely. Generous next to the 32MB
/// byte limit — legit payloads are small (LLM prompts) and, once flowing,
/// arrive continuously. Streaming responses are NOT affected: this bounds
/// reads from the client only.
pub const CLIENT_BODY_TIMEOUT: Duration = Duration::from_secs(120);

/// Inbound h2 keep-alive cadence: after this long without inbound frames the
/// server PINGs the peer; see serve_inbound for why h2 needs its own bound.
const HTTP2_KEEPALIVE_INTERVAL: Duration = Duration::from_secs(30);
/// How long the server waits for the keep-alive PING ACK before closing an
/// unresponsive h2 connection. A peer that answers is actively maintaining
/// the connection (equivalent to sending traffic), so only silent stalers
/// are reaped.
const HTTP2_KEEPALIVE_TIMEOUT: Duration = Duration::from_secs(15);

/// Bound on how long a request may queue for an inbound permit. A wedged
/// upstream (accepts TCP, never sends response headers) holds every permit
/// for up to attempts × header_timeout + backoff, so an open-ended queue
/// would hang agents with no server-side error at all; past this bound the
/// request is shed with an explicit 503 + Retry-After instead of waiting
/// for the client's own timeout.
pub const PERMIT_QUEUE_TIMEOUT: Duration = Duration::from_secs(30);

/// TCP keepalive on inbound connections: dead-peer insurance for sockets
/// that never deliver a full request head — an HTTP/2 client stalling
/// after the connection preface is invisible to header_read_timeout
/// (http1-only), and without keepalive it would hold its connection slot
/// until process exit.
const TCP_KEEPALIVE: Duration = Duration::from_secs(60);

const RID_DIGITS: &[u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

fn next_rid() -> String {
    let n = REQ_SEQ.fetch_add(1, Ordering::Relaxed);
    rid_from(n)
}

/// At least 4 base36 digits; it naturally lengthens past 36^4, avoiding duplicate rids after wraparound.
pub(crate) fn rid_from(n: u64) -> String {
    let mut digits = Vec::with_capacity(4);
    let mut m = n;
    loop {
        digits.push(RID_DIGITS[(m % 36) as usize]);
        m /= 36;
        if m == 0 {
            break;
        }
    }
    while digits.len() < 4 {
        digits.push(b'0');
    }
    digits.reverse();
    String::from_utf8(digits).unwrap_or_else(|_| "0000".into())
}

pub struct Snapshot {
    pub store: Arc<Store>,
    pub table: RouteTable,
    /// Whether this snapshot came from the `.bak` backup (main store failed to decrypt).
    /// Surfaced as `degraded` on the health endpoint; revoked/deleted vkeys may become effective again.
    pub from_backup: bool,
}

pub struct AppState {
    pub snapshot: ArcSwap<Snapshot>,
    pub clients: ProxyClients,
    pub retry: RetryPolicy,
    pub body_limit: usize,
    /// Per-chunk read-idle bound for non-streaming upstream bodies (BODY_READ_IDLE in production; tests inject a small value).
    pub body_read_idle: Duration,
    /// Whole-body bound on reading the inbound request body (CLIENT_BODY_TIMEOUT in production; tests inject a small value).
    pub inbound_body_timeout: Duration,
    /// Bound on queueing for an inbound permit (PERMIT_QUEUE_TIMEOUT in production; tests inject a small value).
    pub permit_queue_timeout: Duration,
    /// Bounds concurrent handler executions — the memory-heavy phase (whole
    /// inbound body buffered + waiting for upstream response headers). The
    /// permit is held until the handler returns; the response body, including
    /// long-lived SSE, streams afterwards without one, so streams can never
    /// starve new requests. The health endpoint is not routed through the
    /// handler and stays available under load.
    pub inbound_permits: Arc<tokio::sync::Semaphore>,
    pub audit: Audit,
    pub started: Instant,
}

/// Builds an upstream HTTP client; `proxy` decides proxy semantics and
/// `read_timeout` decides read idle:
/// - `None` → follow system proxy environment variables (reqwest default behavior)
/// - `Some("direct")` → clear proxy and skip system proxy pickup, forcing a direct connection
/// - `Some(url)` → use the specified proxy (reqwest semantics: an explicit proxy disables system proxy pickup)
///
/// read_timeout is for the streaming client only; non-streaming clients must
/// pass None: reqwest's read_timeout also applies to the "waiting for response
/// headers" phase, so if non-streaming also set 60s, a slow non-streaming
/// request (response headers sent only after generation completes) would be
/// cut off and retried as a network error POST.
pub fn build_upstream_client(
    proxy: Option<&str>,
    read_timeout: Option<Duration>,
) -> Result<reqwest::Client> {
    // reqwest 0.13 uses rustls-no-provider: pick ring as the process-wide
    // crypto provider before the first client is built (idempotent; covers
    // every entry path including tests that bypass bootstrap()).
    let _ = rustls::crypto::ring::default_provider().install_default();
    let mut builder = reqwest::Client::builder()
        .pool_max_idle_per_host(64)
        .pool_idle_timeout(Duration::from_secs(90))
        .tcp_keepalive(Duration::from_secs(60))
        .tcp_nodelay(true)
        .connect_timeout(Duration::from_secs(10))
        .redirect(reqwest::redirect::Policy::none());
    if let Some(rt) = read_timeout {
        builder = builder.read_timeout(rt);
    }
    builder = match proxy {
        None => builder,
        Some(crate::model::PROXY_DIRECT) => builder.no_proxy(),
        Some(url) => builder.proxy(
            reqwest::Proxy::all(url)
                .map_err(|e| Error::msg(format!("invalid proxy URL `{url}`: {e}")))?,
        ),
    };
    builder
        .build()
        .map_err(|e| Error::msg(format!("failed to build HTTP client: {e}")))
}

/// Two clients under the same proxy config: streaming / non-streaming timeout semantics differ, so they must be built separately.
#[derive(Clone)]
struct ClientPair {
    /// Non-streaming: no client-level read idle (see STREAM_READ_TIMEOUT); the header wait is backstopped by the outer header_timeout (tokio timeout), the body phase by the per-chunk BODY_READ_IDLE at the passthrough layer.
    plain: reqwest::Client,
    /// Streaming: 60s read idle, used to detect hung SSE.
    streaming: reqwest::Client,
}

impl ClientPair {
    fn build(proxy: Option<&str>) -> Result<Self> {
        Ok(Self {
            plain: build_upstream_client(proxy, None)?,
            streaming: build_upstream_client(proxy, Some(STREAM_READ_TIMEOUT))?,
        })
    }

    fn pick(&self, is_stream: bool) -> reqwest::Client {
        if is_stream {
            self.streaming.clone()
        } else {
            self.plain.clone()
        }
    }
}

/// Client pool cached per route proxy config. reqwest has no per-request
/// proxy override and proxy URLs are hot-reload mutable, so cache by
/// "proxy config → client": base/direct prebuilt, URLs built lazily. Reads
/// are lock-free (ArcSwap copy-on-write): the per-request path never takes a
/// lock; first use and hot-reload cleanup publish whole new maps.
/// After a successful hot reload, retain_urls converges to the URLs still in
/// use, releasing clients (and their connection pools) left behind by
/// obsolete configs.
pub struct ProxyClients {
    base: ClientPair,
    direct: ClientPair,
    by_url: ArcSwap<HashMap<String, ClientPair>>,
}

impl ProxyClients {
    pub fn new() -> Result<Self> {
        Ok(Self {
            base: ClientPair::build(None)?,
            direct: ClientPair::build(Some(crate::model::PROXY_DIRECT))?,
            by_url: ArcSwap::from_pointee(HashMap::new()),
        })
    }

    /// Route proxy decision: the route.proxy config wins; the default follows the system proxy.
    pub fn for_route(&self, route: &Route, is_stream: bool) -> Result<reqwest::Client> {
        match route.proxy.as_deref() {
            None => Ok(self.base.pick(is_stream)),
            Some(crate::model::PROXY_DIRECT) => Ok(self.direct.pick(is_stream)),
            Some(url) => {
                if let Some(pair) = self.by_url.load().get(url) {
                    return Ok(pair.pick(is_stream));
                }
                let pair = ClientPair::build(Some(url))?;
                let client = pair.pick(is_stream);
                // Publish copy-on-write; under a race with another builder the
                // first insertion wins and the duplicate client is dropped.
                // rcu hands the closure &Arc<HashMap>, hence HashMap::clone.
                self.by_url.rcu(|cache| {
                    let mut next = HashMap::clone(cache);
                    next.entry(url.to_string()).or_insert_with(|| pair.clone());
                    next
                });
                Ok(client)
            }
        }
    }

    /// Called after a successful hot reload: drops cached proxy URLs no longer referenced by any route.
    /// In-flight requests hold Client clones (Arc) and are unaffected.
    pub fn retain_urls(&self, live: &HashSet<String>) {
        self.by_url.rcu(|cache| {
            cache
                .iter()
                .filter(|(url, _)| live.contains(url.as_str()))
                .map(|(url, pair)| (url.clone(), pair.clone()))
                .collect::<HashMap<_, _>>()
        });
    }
}

pub fn build_app(state: Arc<AppState>) -> Router {
    Router::new()
        .route("/__keysink/health", get(health))
        .fallback(handler)
        .with_state(state)
}

/// Inbound read bounds applied by serve_inbound.
#[derive(Clone)]
pub struct InboundLimits {
    /// Whole-head bound: a client that does not finish sending its request
    /// head within this time is disconnected (slowloris defense).
    pub header_timeout: Duration,
    /// Cap on concurrently open client connections: excess connections are
    /// closed on accept instead of accumulating tasks and file descriptors
    /// (matters once the gateway is exposed with --allow-remote). Higher
    /// than the request bound on purpose: idle keep-alive and long-lived SSE
    /// connections hold a connection slot but no request permit.
    pub max_connections: usize,
    /// Test instrumentation: counts accept-loop iterations. An idle loop must
    /// pend on accept (single digits over seconds); an always-ready select
    /// arm spins it into the millions. Production passes None.
    pub loop_iterations: Option<Arc<AtomicU64>>,
}

/// The h2 prior-knowledge preface. hyper-util's auto builder reads it — or a
/// first diverging byte — to pick http1 vs h2, and that sniff phase obeys
/// neither inbound bound: http1's header_read_timeout only arms once http1 is
/// selected, and the h2 keep-alive PING only starts after the h2 handshake
/// completes. A peer that connects and then sends nothing (or stalls
/// mid-preface) therefore holds its connection slot until process exit, and
/// silently parking max_connections of them is the same one-shot remote DoS
/// the h2 keep-alive closed — at lower cost, since not a single byte needs
/// to be sent. So the first bytes are read here, under the same whole-head
/// deadline as http1, and replayed into hyper.
const H2_PREFACE: &[u8] = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";

/// Reads from `io` until the protocol is decidable — `H2_PREFACE` complete
/// (h2), a divergence from it (http1), or EOF — under one whole-phase
/// deadline (a slowloris trickling one byte per window gets nowhere, same
/// semantics as CLIENT_HEADER_TIMEOUT). TimedOut on deadline; read errors
/// propagate.
async fn sniff_protocol(
    io: &mut (impl tokio::io::AsyncRead + Unpin),
    head_timeout: Duration,
) -> std::io::Result<Vec<u8>> {
    let deadline = tokio::time::Instant::now() + head_timeout;
    let mut seen = Vec::with_capacity(H2_PREFACE.len());
    let mut chunk = [0u8; H2_PREFACE.len() + 8];
    while seen.len() < H2_PREFACE.len() {
        let read = tokio::time::timeout_at(deadline, io.read(&mut chunk))
            .await
            .map_err(|_| {
                std::io::Error::new(std::io::ErrorKind::TimedOut, "protocol sniff timed out")
            })??;
        if read == 0 {
            // EOF: replay what arrived so hyper reports the closed peer itself.
            break;
        }
        seen.extend_from_slice(&chunk[..read]);
        // Compare only the prefix-length part: a burst can carry the preface
        // plus the first h2 frames in one read, and that overshoot is legal.
        let decided = &seen[..seen.len().min(H2_PREFACE.len())];
        if !H2_PREFACE.starts_with(decided) {
            break; // cannot be h2 → http1; header_read_timeout takes over
        }
    }
    Ok(seen)
}

/// Replays the sniffed bytes ahead of the live socket so hyper sees the exact
/// byte stream it would have read itself. Writes pass straight through
/// (WebSocket upgrades included).
struct PrefaceIo<T> {
    io: T,
    preface: Vec<u8>,
    pos: usize,
}

impl<T: tokio::io::AsyncRead + Unpin> tokio::io::AsyncRead for PrefaceIo<T> {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<std::io::Result<()>> {
        if self.pos < self.preface.len() {
            let n = (self.preface.len() - self.pos).min(buf.remaining());
            buf.put_slice(&self.preface[self.pos..self.pos + n]);
            self.pos += n;
            return Poll::Ready(Ok(()));
        }
        Pin::new(&mut self.io).poll_read(cx, buf)
    }
}

impl<T: tokio::io::AsyncWrite + Unpin> tokio::io::AsyncWrite for PrefaceIo<T> {
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<std::io::Result<usize>> {
        Pin::new(&mut self.io).poll_write(cx, buf)
    }
    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
        Pin::new(&mut self.io).poll_flush(cx)
    }
    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
        Pin::new(&mut self.io).poll_shutdown(cx)
    }
    fn poll_write_vectored(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        bufs: &[std::io::IoSlice<'_>],
    ) -> Poll<std::io::Result<usize>> {
        Pin::new(&mut self.io).poll_write_vectored(cx, bufs)
    }
    fn is_write_vectored(&self) -> bool {
        self.io.is_write_vectored()
    }
}

/// Serves the gateway on `listener` until `shutdown` resolves — the same
/// shape as axum::serve(listener, app).with_graceful_shutdown(shutdown),
/// except the inbound head read is time-bounded: axum::serve exposes no
/// header_read_timeout, so a client that opens a connection and stalls
/// mid-head would hold a task + socket forever. That matters once the
/// gateway is exposed with --allow-remote, but reaping dead connections is
/// cheap insurance everywhere. The body phase is bounded app-side (see
/// CLIENT_BODY_TIMEOUT), where it can never touch streaming responses.
pub async fn serve_inbound(
    listener: tokio::net::TcpListener,
    app: Router,
    limits: InboundLimits,
    shutdown: impl std::future::Future<Output = ()>,
) -> std::io::Result<()> {
    let mut shutdown = std::pin::pin!(shutdown);
    let mut conns = tokio::task::JoinSet::new();
    let conn_slots = Arc::new(tokio::sync::Semaphore::new(limits.max_connections));
    let mut shed = 0u64;
    loop {
        if let Some(counter) = &limits.loop_iterations {
            counter.fetch_add(1, Ordering::Relaxed);
        }
        let accepted = tokio::select! {
            _ = &mut shutdown => None,
            // Reap connection tasks as they finish: JoinSet retains each
            // entry (the JoinHandle plus the task's harness allocation,
            // sized to hold hyper's connection future) until join_next
            // consumes it, so without this branch memory would grow with
            // the cumulative number of accepted connections over the
            // process lifetime. The arm must be disabled while the set is
            // empty: join_next returns Ready(None) immediately for an empty
            // set (it only pends while tasks are still running), and an
            // always-ready arm would spin the loop and starve
            // listener.accept() — the gateway would stop serving entirely.
            res = conns.join_next(), if !conns.is_empty() => {
                let _ = res;
                continue;
            }
            accepted = listener.accept() => Some(accepted),
        };
        let Some(accepted) = accepted else {
            break;
        };
        let (stream, _peer) = match accepted {
            Ok(ok) => ok,
            Err(e) => {
                // Descriptor pressure is transient (a burst above the OS fd
                // limit); back off and keep serving instead of turning it
                // into a full outage. Everything else stays fatal, as before.
                if is_transient_accept_error(&e) {
                    tracing::warn!(error = %e, "transient accept error (descriptor pressure); backing off 1s");
                    // Shutdown stays live during the backoff: an uninterruptible
                    // sleep would delay a stop by up to 1s per burst.
                    tokio::select! {
                        _ = &mut shutdown => break,
                        _ = tokio::time::sleep(Duration::from_secs(1)) => {}
                    }
                    continue;
                }
                return Err(e);
            }
        };
        // Shed beyond the connection cap: close immediately instead of
        // accumulating tasks and fds. The permit lives exactly as long as
        // the connection task. Warn cadence matches the audit-drop counter:
        // a flood sheds fast, so one line per 100 keeps the default info
        // log sane while still leaving evidence a cap was ever hit.
        let Ok(_conn_slot) = conn_slots.clone().try_acquire_owned() else {
            shed += 1;
            if shed % 100 == 1 {
                tracing::warn!(
                    shed,
                    "connection cap reached; dropping incoming connections"
                );
            }
            drop(stream);
            continue;
        };
        let _ = stream.set_nodelay(true);
        // Best-effort like nodelay: keepalive is dead-peer hardening, not a
        // prerequisite for serving. SockRef borrows the stream, so the socket
        // config lands before the stream moves into the connection task.
        // Interval must be explicit: Windows maps it straight onto
        // SIO_KEEPALIVE_VALS, and socket2 turns an unset interval into a 0ms
        // probe gap — undefined winsock input, where one dropped packet on a
        // busy link could reap a healthy connection.
        let socket = socket2::SockRef::from(&stream);
        let _ = socket.set_tcp_keepalive(
            &socket2::TcpKeepalive::new()
                .with_time(TCP_KEEPALIVE)
                .with_interval(Duration::from_secs(15)),
        );
        // The connection future owns its builder (cheap config clone) so it
        // stays 'static and can outlive this loop while draining.
        let app = app.clone();
        conns.spawn(async move {
            // Hold the connection slot for the task's whole life: dropped
            // when the connection ends, freeing the slot for the next accept.
            let _conn_slot = _conn_slot;
            let mut stream = stream;
            let preface = match sniff_protocol(&mut stream, limits.header_timeout).await {
                Ok(preface) => preface,
                Err(e) => {
                    // Silent peers are the DoS shape this bounds; aborts and
                    // resets are routine client noise in both cases.
                    tracing::debug!(error = %e, "inbound connection dropped before speaking");
                    return;
                }
            };
            let mut builder =
                hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new());
            builder.http1().timer(hyper_util::rt::TokioTimer::new());
            builder
                .http1()
                .header_read_timeout(Some(limits.header_timeout));
            // The http1 bounds above do not reach h2c connections (the auto
            // builder accepts prior-knowledge h2): without a keep-alive an
            // established h2 connection that goes silent holds its connection
            // slot forever, and silently parking max_connections of them is a
            // one-shot remote DoS on an --allow-remote deployment. The server
            // PINGs after the interval and closes the connection when the
            // PING is not ACKed within the timeout (timer required — the
            // default () timer makes both options inert).
            builder.http2().timer(hyper_util::rt::TokioTimer::new());
            builder
                .http2()
                .keep_alive_interval(Some(HTTP2_KEEPALIVE_INTERVAL));
            builder.http2().keep_alive_timeout(HTTP2_KEEPALIVE_TIMEOUT);
            if let Err(e) = builder
                .serve_connection_with_upgrades(
                    hyper_util::rt::TokioIo::new(PrefaceIo {
                        io: stream,
                        preface,
                        pos: 0,
                    }),
                    hyper_util::service::TowerToHyperService::new(app.clone()),
                )
                .await
            {
                // Client aborts mid-stream are routine for a proxy; keep the
                // noise down but leave a trace for debugging.
                tracing::debug!(error = %e, "inbound connection ended");
            }
        });
    }
    // Graceful: stop accepting, then let in-flight requests (including long
    // SSE streams) run to completion on their own — same semantics as
    // axum::serve's graceful shutdown; the service manager's stop timeout is
    // the hard cap. The count tells the operator what is still holding the
    // drain; a second signal exits immediately (see shutdown_signal — tokio
    // swallows further signals once the shutdown future resolved).
    tracing::info!(
        connections = conns.len(),
        "shutdown: draining in-flight connections (a second signal exits immediately)"
    );
    while conns.join_next().await.is_some() {}
    Ok(())
}

/// Whether an accept error is transient resource pressure to back off from,
/// rather than a fatal condition for the serve loop. Unix: EMFILE/ENFILE (a
/// burst above the fd limit). Windows: the winsock equivalents WSAEMFILE
/// (10024) / WSAENOBUFS (10055) as raw codes, because libc there carries
/// neither the errno nor the winsock constants portably.
fn is_transient_accept_error(e: &std::io::Error) -> bool {
    #[cfg(unix)]
    {
        matches!(e.raw_os_error(), Some(libc::EMFILE) | Some(libc::ENFILE))
    }
    #[cfg(not(unix))]
    {
        matches!(e.raw_os_error(), Some(10024) | Some(10055))
    }
}

async fn health(State(state): State<Arc<AppState>>) -> impl IntoResponse {
    let snap = state.snapshot.load();
    Json(json!({
        "ok": true,
        "degraded": snap.from_backup,
        "version": env!("CARGO_PKG_VERSION"),
        "uptime_secs": state.started.elapsed().as_secs(),
        "routes": snap.table.len(),
    }))
}

pub async fn handler(State(state): State<Arc<AppState>>, req: Request<Body>) -> Response {
    let rid = next_rid();
    let span = tracing::info_span!("req", rid = %rid);
    async move { handle_inner(state, req, rid).await }
        .instrument(span)
        .await
}

async fn handle_inner(state: Arc<AppState>, req: Request<Body>, rid: String) -> Response {
    let started = Instant::now();
    let (parts, body) = req.into_parts();
    let method = parts.method.clone();
    let path = parts.uri.path().to_string();
    let query = parts.uri.query().map(str::to_string);
    let in_headers = parts.headers;

    // Rejected requests are audited too (route `-` means no route matched).
    let deny = |route: &str,
                hash: Option<&[u8; 32]>,
                status: StatusCode,
                kind: &'static str,
                msg: &str|
     -> Response {
        record_reject(
            state.as_ref(),
            &rid,
            route,
            hash,
            &method,
            &path,
            status,
            started,
        );
        error_response(status, kind, msg, &rid)
    };

    // Cheap head screening comes BEFORE the request permit: everything
    // rejected below needs no body read and no upstream work, so a
    // credential-less flood (or a peer dribbling an oversized declared
    // body) must not occupy permits — with the permit first, such a flood
    // could pin every permit for CLIENT_BODY_TIMEOUT each and starve
    // legitimate traffic while it queues. Declared is the operative word:
    // the screen reads Content-Length, so a chunked request still takes a
    // permit before its size is knowable — bounded then by body_limit +
    // CLIENT_BODY_TIMEOUT once the read starts, which is the pre-existing
    // exposure, strictly narrowed by this screen.
    if in_headers.contains_key(header::UPGRADE) {
        return deny(
            "-",
            None,
            StatusCode::NOT_IMPLEMENTED,
            "unsupported",
            "keysink does not support WebSocket / Upgrade",
        );
    }

    let Some(token) = extract_vkey(&in_headers) else {
        return deny(
            "-",
            None,
            StatusCode::UNAUTHORIZED,
            "authentication_error",
            "missing valid virtual key (Authorization: Bearer ks_... or x-api-key)",
        );
    };

    let snapshot = state.snapshot.load_full();
    let hash = vkey::hash(&token);
    let Some(resolved) = snapshot.table.lookup_hash(&hash) else {
        // an unknown vkey is indistinguishable from one whose hot reload (fs-watch
        // debounce, ~1s) has not reached this gateway yet — say so instead of
        // blaming a rotation the caller may not have done
        return deny(
            "-",
            Some(&hash),
            StatusCode::UNAUTHORIZED,
            "authentication_error",
            "virtual key is invalid or has been rotated (if it was just added or rotated, hot reload may not have reached the gateway yet — retry in a second)",
        );
    };
    let route = &resolved.route;
    let route_name = resolved.name.as_str();
    if !route.enabled {
        return deny(
            route_name,
            Some(&hash),
            StatusCode::FORBIDDEN,
            "permission_error",
            "route is disabled",
        );
    }

    let Some(value) = &route.inline_key else {
        // validate guarantees non-empty; reaching here means the snapshot came from old data that never passed validate.
        tracing::error!(route = route_name, "route is missing route-only key");
        return deny(
            route_name,
            Some(&hash),
            StatusCode::INTERNAL_SERVER_ERROR,
            "configuration_error",
            "incomplete route configuration",
        );
    };
    let key = Zeroizing::new(value.clone());

    if let Some(len) = in_headers
        .get(header::CONTENT_LENGTH)
        .and_then(|v| v.to_str().ok())
        .and_then(|s| s.parse::<usize>().ok())
        && len > state.body_limit
    {
        return deny(
            route_name,
            Some(&hash),
            StatusCode::PAYLOAD_TOO_LARGE,
            "request_too_large",
            &format!("request body exceeds limit of {} bytes", state.body_limit),
        );
    }

    // Queue until a permit frees up: saturating the gateway makes extra
    // requests wait rather than pile up unbounded memory. The wait is
    // bounded (permit_queue_timeout): a wedged upstream (accepts TCP, never
    // sends response headers) holds every permit for up to attempts ×
    // header_timeout + backoff, so an open-ended queue would hang agents
    // with no server-side error at all — past the bound the request is shed
    // with 503 + Retry-After.
    let permit = tokio::time::timeout(
        state.permit_queue_timeout,
        state.inbound_permits.clone().acquire_owned(),
    )
    .await;
    let _permit = match permit {
        Ok(Ok(permit)) => permit,
        Err(_elapsed) => {
            record_reject(
                state.as_ref(),
                &rid,
                route_name,
                Some(&hash),
                &method,
                &path,
                StatusCode::SERVICE_UNAVAILABLE,
                started,
            );
            let mut response = error_response(
                StatusCode::SERVICE_UNAVAILABLE,
                "overloaded",
                "gateway is at capacity; retry shortly",
                &rid,
            );
            response
                .headers_mut()
                .insert(header::RETRY_AFTER, HeaderValue::from_static("1"));
            return response;
        }
        // The semaphore is never closed; this arm only fires in a shutdown race.
        Ok(Err(_closed)) => {
            return error_response(
                StatusCode::SERVICE_UNAVAILABLE,
                "overloaded",
                "gateway is not accepting requests",
                &rid,
            );
        }
    };

    let read = tokio::time::timeout(
        state.inbound_body_timeout,
        axum::body::to_bytes(body, state.body_limit),
    )
    .await;
    let body = match read {
        Ok(Ok(bytes)) => bytes,
        Ok(Err(e)) => {
            let too_large = is_length_limit_error(&e);
            let (status, kind, message) = if too_large {
                (
                    StatusCode::PAYLOAD_TOO_LARGE,
                    "request_too_large",
                    "request body exceeds limit",
                )
            } else {
                (
                    StatusCode::BAD_REQUEST,
                    "invalid_request",
                    "failed to read request body",
                )
            };
            return deny(route_name, Some(&hash), status, kind, message);
        }
        // The client never finished sending its body: 408, and drop it.
        Err(_elapsed) => {
            return deny(
                route_name,
                Some(&hash),
                StatusCode::REQUEST_TIMEOUT,
                "request_timeout",
                "timed out reading request body",
            );
        }
    };

    let is_stream = is_stream_request(&body);

    let fwd_headers = match forward_headers(&in_headers, route, key.as_str(), is_stream) {
        Ok(h) => h,
        Err(e) => {
            tracing::error!(error = %e, route = route_name, "failed to build upstream headers");
            return deny(
                route_name,
                Some(&hash),
                StatusCode::INTERNAL_SERVER_ERROR,
                "configuration_error",
                "invalid route header configuration",
            );
        }
    };

    let url = match build_upstream_url(
        &route.base_url,
        &path,
        query.as_deref(),
        &route.auth,
        key.as_str(),
    ) {
        Ok(u) => u,
        Err(e) => {
            tracing::error!(error = %e, route = route_name, "failed to build upstream URL");
            return deny(
                route_name,
                Some(&hash),
                StatusCode::INTERNAL_SERVER_ERROR,
                "configuration_error",
                "invalid route URL configuration",
            );
        }
    };

    // debug, not info: at ~60k RPS the per-request info line wrote ~12MB/s
    // (6.4GB over a 10-minute soak) and its formatting + stdout-lock cost
    // showed up as a measurable throughput hit. The audit log (--audit-log)
    // is the per-request record; RUST_LOG=keysink=debug restores this line.
    tracing::debug!(
        route = route_name,
        %method,
        %path,
        is_stream,
        bytes_in = body.len(),
        "forwarding request"
    );

    let client = match state.clients.for_route(route, is_stream) {
        Ok(c) => c,
        Err(e) => {
            tracing::error!(error = %e, route = route_name, "failed to build route proxy client");
            return deny(
                route_name,
                Some(&hash),
                StatusCode::INTERNAL_SERVER_ERROR,
                "configuration_error",
                "invalid route proxy configuration",
            );
        }
    };

    let forward = forward_with_retry(
        &state,
        &client,
        route,
        route_name,
        method.clone(),
        url,
        fwd_headers,
        body.clone(),
        is_stream,
        &rid,
    )
    .await;

    let mut response = forward.response;
    response.headers_mut().insert(
        "x-keysink-request-id",
        HeaderValue::from_str(&rid).unwrap_or(HeaderValue::from_static("0000")),
    );

    // AuditEntry::new formats an RFC3339 local timestamp and allocates a
    // handful of Strings per request — pure waste on the default audit-off
    // path, so check first. The writer is fixed at startup (--audit-log or
    // not), so the answer cannot flip between here and record().
    if state.audit.is_enabled() {
        let mut entry = AuditEntry::new(
            rid.clone(),
            route_name,
            vkey::fingerprint(&hash),
            method.to_string(),
            path,
            body.len(),
            is_stream,
        );
        entry.status = response.status().as_u16();
        entry.ms = started.elapsed().as_millis() as u64;
        entry.attempts = forward.attempts;
        state.audit.record(entry);
    }

    response
}

/// Audit row for a rejected request: `route` `-` means no route matched;
/// record the fingerprint (not invertible) when the token hash is available, `-` otherwise.
#[allow(clippy::too_many_arguments)]
fn record_reject(
    state: &AppState,
    rid: &str,
    route: &str,
    hash: Option<&[u8; 32]>,
    method: &Method,
    path: &str,
    status: StatusCode,
    started: Instant,
) {
    let mut entry = AuditEntry::new(
        rid.to_string(),
        route.to_string(),
        hash.map(vkey::fingerprint).unwrap_or_else(|| "-".into()),
        method.to_string(),
        path.to_string(),
        0,
        false,
    );
    entry.status = status.as_u16();
    entry.ms = started.elapsed().as_millis() as u64;
    // Rejection rows are attacker-rateable without any credential, so they go
    // through the throttled entry point instead of plain record().
    state.audit.record_reject(entry);
}

struct Forwarded {
    response: Response,
    attempts: u8,
}

/// Whether a network-class error may be replayed: for connect errors the
/// request certainly never arrived (zero side effects upstream); replaying
/// idempotent methods has no side effects. In the remaining cases (timeout /
/// disconnect mid-send) the upstream may have already processed and billed it.
fn network_retry_allowed(is_connect: bool, idempotent_method: bool) -> bool {
    is_connect || idempotent_method
}

/// Whether a to_bytes error is a length-limit breach: downcast along the
/// source chain to http_body_util::LengthLimitError (axum wraps it in
/// axum::Error), keeping the message match as a fallback in case axum's
/// wording changes between versions.
fn is_length_limit_error(e: &axum::Error) -> bool {
    let mut cur: Option<&dyn std::error::Error> = Some(e);
    while let Some(err) = cur {
        if err
            .downcast_ref::<http_body_util::LengthLimitError>()
            .is_some()
            || err.to_string().contains("length limit")
        {
            return true;
        }
        cur = err.source();
    }
    false
}

/// Bounded read that discards a retryable response body to give the
/// connection back: past the limit it simply gives up (drop the connection,
/// no reuse), preventing a misbehaving upstream from blowing up memory with a
/// huge body.
const DISCARD_BODY_LIMIT: usize = 64 * 1024;

async fn discard_body_limited(mut resp: reqwest::Response) {
    let mut remaining = DISCARD_BODY_LIMIT;
    while let Ok(Some(chunk)) = resp.chunk().await {
        if chunk.len() >= remaining {
            return;
        }
        remaining -= chunk.len();
    }
}

#[allow(clippy::too_many_arguments)]
async fn forward_with_retry(
    state: &AppState,
    client: &reqwest::Client,
    route: &Route,
    route_name: &str,
    method: Method,
    url: String,
    headers: HeaderMap,
    body: Bytes,
    is_stream: bool,
    rid: &str,
) -> Forwarded {
    let policy = state.retry.for_route(route);
    let max_retries = policy.max_retries;
    // POST replay safety (§4.2): on a response-header timeout or a network
    // error mid-send, the request may already have reached the upstream and
    // been billed, so a retry is a second POST. Only connect-class errors
    // (request definitely not delivered, including connect timeout) or
    // idempotent methods (GET/HEAD/OPTIONS) are retried; everything else
    // fails immediately for the caller.
    let idempotent = matches!(method, Method::GET | Method::HEAD | Method::OPTIONS);

    for attempt in 0..=max_retries {
        let req = client
            .request(method.clone(), &url)
            .headers(headers.clone());
        let req = if body.is_empty() {
            req
        } else {
            req.body(body.clone())
        };

        let send = tokio::time::timeout(policy.header_timeout, req.send()).await;

        let resp = match send {
            Err(_) => {
                tracing::warn!(
                    attempt,
                    route = route_name,
                    "timed out waiting for upstream response headers"
                );
                if idempotent && attempt < max_retries {
                    tokio::time::sleep(policy.backoff(attempt as u32, None)).await;
                    continue;
                }
                return Forwarded {
                    response: error_response(
                        StatusCode::GATEWAY_TIMEOUT,
                        "upstream_timeout",
                        "upstream response header timeout",
                        rid,
                    ),
                    attempts: attempt + 1,
                };
            }
            Ok(Err(e)) => {
                tracing::warn!(
                    attempt,
                    route = route_name,
                    timeout = e.is_timeout(),
                    connect = e.is_connect(),
                    "upstream request failed"
                );
                if network_retry_allowed(e.is_connect(), idempotent) && attempt < max_retries {
                    tokio::time::sleep(policy.backoff(attempt as u32, None)).await;
                    continue;
                }
                return Forwarded {
                    response: error_response(
                        StatusCode::BAD_GATEWAY,
                        "upstream_error",
                        "upstream unreachable",
                        rid,
                    ),
                    attempts: attempt + 1,
                };
            }
            Ok(Ok(resp)) => resp,
        };

        let status = resp.status().as_u16();
        if policy.is_retryable(status) && attempt < max_retries {
            let retry_after = resp
                .headers()
                .get(header::RETRY_AFTER)
                .and_then(|v| v.to_str().ok())
                .and_then(parse_retry_after);
            tracing::warn!(
                attempt,
                status,
                route = route_name,
                "upstream returned retryable status"
            );
            discard_body_limited(resp).await;
            tokio::time::sleep(policy.backoff(attempt as u32, retry_after)).await;
            continue;
        }

        let response = if is_stream {
            stream_response(
                resp,
                route.sse_terminator,
                rid.to_string(),
                state.body_read_idle,
            )
            .await
        } else {
            pass_through_response(resp, state.body_read_idle).await
        };
        return Forwarded {
            response,
            attempts: attempt + 1,
        };
    }

    Forwarded {
        response: error_response(
            StatusCode::BAD_GATEWAY,
            "internal_error",
            "retry loop exited unexpectedly",
            rid,
        ),
        attempts: max_retries + 1,
    }
}

pub(crate) fn extract_vkey(headers: &HeaderMap) -> Option<String> {
    for name in ["authorization", "x-api-key", "x-goog-api-key", "api-key"] {
        let Some(value) = headers.get(name) else {
            continue;
        };
        let Ok(text) = value.to_str() else {
            continue;
        };
        let text = text.trim();
        let text = if name == "authorization" {
            match text.get(..7) {
                Some(prefix) if prefix.eq_ignore_ascii_case("bearer ") => &text[7..],
                _ => text,
            }
        } else {
            text
        };
        if text.starts_with(vkey::PREFIX) {
            return Some(text.to_string());
        }
    }
    None
}

fn is_hop_by_hop(name: &str) -> bool {
    const HOP: &[&str] = &[
        "host",
        "content-length",
        "connection",
        "keep-alive",
        "proxy-authenticate",
        "proxy-authorization",
        "proxy-connection",
        "te",
        "trailer",
        "transfer-encoding",
        "upgrade",
    ];
    HOP.iter().any(|h| h.eq_ignore_ascii_case(name))
}

fn is_auth_header(name: &str) -> bool {
    const AUTH: &[&str] = &[
        "authorization",
        "x-api-key",
        "x-goog-api-key",
        "api-key",
        "anthropic-api-key",
        "openai-api-key",
    ];
    AUTH.iter().any(|h| h.eq_ignore_ascii_case(name))
}

pub(crate) fn forward_headers(
    src: &HeaderMap,
    route: &Route,
    upstream_key: &str,
    is_stream: bool,
) -> Result<HeaderMap> {
    let mut out = HeaderMap::with_capacity(src.len() + 2);
    for (name, value) in src.iter() {
        let n = name.as_str();
        if is_hop_by_hop(n) || is_auth_header(n) {
            continue;
        }
        // Streaming responses need plain-text scanning for SSE terminators;
        // once the upstream compresses according to the client-negotiated
        // Accept-Encoding (zstd/gzip/br), the scan goes blind, falsely flags
        // truncation, and then appends plain-text events to the tail of the
        // compressed stream, corrupting it. The gateway does not decompress,
        // so streaming requests declare no content encoding to the upstream in
        // exchange for inspectable plain-text SSE.
        if is_stream && n.eq_ignore_ascii_case("accept-encoding") {
            continue;
        }
        out.append(name.clone(), value.clone());
    }

    for (key, value) in &route.headers {
        // Streaming requests must not negotiate a compressed encoding upstream
        // (same rationale as the inbound accept-encoding strip above); static
        // route config gets no exemption.
        if is_stream && key.eq_ignore_ascii_case("accept-encoding") {
            continue;
        }
        let name = HeaderName::from_bytes(key.as_bytes())
            .map_err(|e| Error::msg(format!("invalid header name `{key}`: {e}")))?;
        let value = HeaderValue::from_str(value)
            .map_err(|e| Error::msg(format!("invalid value for header `{key}`: {e}")))?;
        // Static headers are only filled in when the client didn't send them, to avoid overriding version/tracing headers the client negotiated itself.
        out.entry(name).or_insert(value);
    }

    match &route.auth {
        Auth::Bearer => {
            out.insert(
                header::AUTHORIZATION,
                HeaderValue::from_str(&format!("Bearer {upstream_key}"))
                    .map_err(|e| Error::msg(format!("invalid Bearer value: {e}")))?,
            );
        }
        Auth::XApiKey => {
            out.insert(
                HeaderName::from_static("x-api-key"),
                HeaderValue::from_str(upstream_key)
                    .map_err(|e| Error::msg(format!("invalid x-api-key value: {e}")))?,
            );
        }
        Auth::Header { name, prefix } => {
            let header_name = HeaderName::from_bytes(name.as_bytes())
                .map_err(|e| Error::msg(format!("invalid auth header name `{name}`: {e}")))?;
            out.insert(
                header_name,
                HeaderValue::from_str(&format!("{prefix}{upstream_key}"))
                    .map_err(|e| Error::msg(format!("invalid auth header value: {e}")))?,
            );
        }
        Auth::Basic { username } => {
            let raw = format!("{username}:{upstream_key}");
            let encoded = base64::engine::general_purpose::STANDARD.encode(raw.as_bytes());
            out.insert(
                header::AUTHORIZATION,
                HeaderValue::from_str(&format!("Basic {encoded}"))
                    .map_err(|e| Error::msg(format!("invalid Basic value: {e}")))?,
            );
        }
        Auth::Query { .. } | Auth::None => {}
    }

    Ok(out)
}

pub(crate) fn build_upstream_url(
    base_url: &str,
    path: &str,
    query: Option<&str>,
    auth: &Auth,
    upstream_key: &str,
) -> Result<String> {
    let base = base_url.trim_end_matches('/');
    let path = if path.is_empty() {
        "/"
    } else if path.starts_with('/') {
        path
    } else {
        return Err(Error::msg("inbound path does not start with /"));
    };

    let mut url =
        String::with_capacity(base.len() + path.len() + 64 + query.map_or(0, |q| q.len()));
    url.push_str(base);
    url.push_str(path);

    let query_auth = match auth {
        Auth::Query { param } => Some(param.as_str()),
        _ => None,
    };

    let mut parts: Vec<String> = Vec::new();
    if let Some(q) = query {
        for pair in q.split('&') {
            if pair.is_empty() {
                continue;
            }
            if let Some(param) = query_auth {
                let key = pair.split('=').next().unwrap_or("");
                if key == param {
                    continue;
                }
            }
            parts.push(pair.to_string());
        }
    }
    if let Some(param) = query_auth {
        parts.push(format!(
            "{param}={}",
            crate::util::percent_encode(upstream_key)
        ));
    }

    if !parts.is_empty() {
        url.push('?');
        url.push_str(&parts.join("&"));
    }
    Ok(url)
}

pub(crate) fn is_stream_request(body: &[u8]) -> bool {
    // Byte-level pre-filter first: a body not containing the `"stream"`
    // substring cannot be stream:true, which avoids scanning a body of up to
    // 32MB just to probe one field.
    if memchr::memmem::find(body, b"\"stream\"").is_none() {
        return false;
    }
    top_level_stream_true(body)
}

/// Whether the top-level JSON object contains a `stream` member whose value
/// is the literal `true`. Byte-level scan: member names and value extents
/// are tokenized with full JSON semantics (memchr-jumped strings with
/// escapes, numbers, literals, string-aware nesting), so a `"stream"` inside
/// a string value or a nested object can never be mistaken for a member,
/// and the scan answers at the first `stream: true` instead of walking the
/// remaining body — a full `from_slice::<Probe>` used to tokenize up to the
/// 32MB limit on every request, the gateway's largest self-inflicted CPU
/// cost. Nesting depth stays off the call stack (iterative skips).
///
/// Compared to the old full parse this deliberately diverges only on bodies
/// that are not valid LLM requests (which upstream will 4xx anyway; the
/// verdict merely selects the client pair):
/// - the first `stream: true` decides; later `stream` members and a
///   malformed tail do not void it
/// - a wrong-typed `stream` member is skipped instead of failing the probe
/// - array-topped bodies report false (the old probe accepted serde's
///   struct-from-seq quirk where `[true]` meant stream:true)
fn top_level_stream_true(body: &[u8]) -> bool {
    let mut i = skip_ws(body, 0);
    if body.get(i) != Some(&b'{') {
        return false;
    }
    i += 1;
    loop {
        i = skip_ws(body, i);
        match body.get(i) {
            Some(b'}') => return false,
            Some(b'"') => {}
            _ => return false,
        }
        let name_start = i + 1;
        let Some(name_end) = skip_string(body, i) else {
            return false;
        };
        let name = &body[name_start..name_end - 1];
        i = skip_ws(body, name_end);
        if body.get(i) != Some(&b':') {
            return false;
        }
        i = skip_ws(body, i + 1);
        if name == b"stream" || unescapes_to_stream(name) {
            // The literal `true` followed by a structural char decides;
            // anything else (false, null, string, ...) is skipped below.
            if body[i..].starts_with(b"true")
                && matches!(
                    body.get(i + 4),
                    None | Some(b',' | b'}' | b' ' | b'\t' | b'\n' | b'\r')
                )
            {
                return true;
            }
        }
        let Some(next) = skip_value(body, i) else {
            return false;
        };
        i = skip_ws(body, next);
        match body.get(i) {
            Some(b',') => i += 1,
            _ => return false, // '}' ends the object; anything else is malformed
        }
    }
}

/// Only consulted for names that failed the exact `stream` compare: whether
/// the escaped JSON string interior decodes to `stream` (e.g. `stre\u0061m`).
fn unescapes_to_stream(name: &[u8]) -> bool {
    if !name.contains(&b'\\') {
        return false;
    }
    // Re-quote and let serde_json do the (rare) unescaping.
    let mut quoted = Vec::with_capacity(name.len() + 2);
    quoted.push(b'"');
    quoted.extend_from_slice(name);
    quoted.push(b'"');
    serde_json::from_slice::<String>(&quoted).is_ok_and(|s| s == "stream")
}

fn skip_ws(body: &[u8], mut i: usize) -> usize {
    while matches!(body.get(i), Some(b' ' | b'\t' | b'\n' | b'\r')) {
        i += 1;
    }
    i
}

/// `at` is the opening quote; returns the index just past the closing quote,
/// or None when the string never ends. memchr jumps between escapes so a
/// plain megabyte string costs a handful of SIMD scans.
fn skip_string(body: &[u8], at: usize) -> Option<usize> {
    let mut i = at + 1;
    loop {
        i += memchr::memchr2(b'"', b'\\', &body[i..])?;
        match body.get(i)? {
            b'"' => return Some(i + 1),
            _ => i += 2, // backslash: skip it and the escaped byte
        }
    }
}

/// Skips one JSON value starting at `i`; returns the index just past it.
/// Structural tokenization: strings, numbers, the three literals, and
/// nested containers with string-aware tracking of the outer pair — inner
/// same-type brackets nest, other bracket types are inert data positions.
/// Malformed input yields None (the caller reports false, matching the old
/// parse-error path).
fn skip_value(body: &[u8], i: usize) -> Option<usize> {
    match *body.get(i)? {
        b'"' => skip_string(body, i),
        b'[' | b'{' => {
            let (open, close) = if body[i] == b'[' {
                (b'[', b']')
            } else {
                (b'{', b'}')
            };
            let mut depth = 0usize;
            let mut j = i;
            loop {
                match body.get(j)? {
                    b'"' => {
                        j = skip_string(body, j)?;
                        continue;
                    }
                    &c if c == open => depth += 1,
                    &c if c == close => {
                        depth -= 1;
                        if depth == 0 {
                            return Some(j + 1);
                        }
                    }
                    _ => {}
                }
                j += 1;
            }
        }
        b't' if body[i..].starts_with(b"true") => Some(i + 4),
        b'f' if body[i..].starts_with(b"false") => Some(i + 5),
        b'n' if body[i..].starts_with(b"null") => Some(i + 4),
        c if c == b'-' || c.is_ascii_digit() => {
            let mut j = i + 1;
            while matches!(
                body.get(j),
                Some(b'0'..=b'9' | b'-' | b'+' | b'.' | b'e' | b'E')
            ) {
                j += 1;
            }
            Some(j)
        }
        _ => None,
    }
}

/// Drops hop-by-hop entries from an upstream response's header map in place.
/// The map was moved out of the response wholesale, so header values (the
/// byte-expensive part) are never copied; only the few matching names are
/// cloned (refcount bumps) on their way to `remove`.
fn drop_hop_by_hop(headers: &mut HeaderMap) {
    let hop: Vec<HeaderName> = headers
        .iter()
        .filter(|(name, _)| is_hop_by_hop(name.as_str()))
        .map(|(name, _)| name.clone())
        .collect();
    for name in hop {
        headers.remove(&name);
    }
}

/// Whether the response carries a content encoding (`identity` counts as
/// unencoded). When encoded, the body is compressed bytes that cannot be
/// scanned for SSE terminators as plain text, so it can only be passed through as-is.
pub(crate) fn is_encoded(headers: &HeaderMap) -> bool {
    match headers.get(header::CONTENT_ENCODING) {
        None => false,
        Some(value) => match value.to_str() {
            Ok(v) => {
                let v = v.trim();
                !v.is_empty() && !v.eq_ignore_ascii_case("identity")
            }
            Err(_) => true,
        },
    }
}

async fn pass_through_response(mut resp: reqwest::Response, body_idle: Duration) -> Response {
    let status = resp.status();
    // Move the header map out of the upstream response and drop hop-by-hop
    // entries in place; build_response then moves the map straight into the
    // client response. The old path cloned every header twice (once into a
    // fresh map, again through the response builder).
    let mut headers = std::mem::take(resp.headers_mut());
    drop_hop_by_hop(&mut headers);
    let stream = idle_bounded(resp.bytes_stream(), body_idle);
    build_response(status, headers, Body::from_stream(stream))
}

/// Per-chunk read-idle bound for a forwarded response body: chunks pass
/// through unchanged; if the upstream goes silent past `idle`, or errors, the
/// body ends with an error so hyper aborts the response instead of hanging on
/// it forever. Ends after the first error rather than looping errors if the
/// consumer polls again.
fn idle_bounded<S>(
    inner: S,
    idle: Duration,
) -> impl futures_util::Stream<Item = std::result::Result<Bytes, std::io::Error>>
where
    S: futures_util::Stream<Item = reqwest::Result<Bytes>>,
{
    let inner = Box::pin(inner);
    stream::unfold((inner, false), move |(mut inner, done)| async move {
        if done {
            return None;
        }
        match tokio::time::timeout(idle, inner.next()).await {
            Ok(Some(Ok(chunk))) => Some((Ok(chunk), (inner, false))),
            Ok(Some(Err(e))) => {
                if e.is_timeout() {
                    tracing::warn!(
                        "upstream stopped sending the response body (read idle); aborting the response"
                    );
                } else {
                    // Summary fields only, deliberately not the error object:
                    // reqwest Display appends "for url (<url>)" when one is
                    // attached, and with Auth::Query that URL carries the
                    // upstream key. Today body-kind errors carry no URL, but
                    // logging the full object would turn that reqwest
                    // invariant into a silent leak the next time it changes.
                    tracing::warn!(
                        timeout = e.is_timeout(),
                        connect = e.is_connect(),
                        status = e.status().map(|s| s.as_u16()),
                        "failed to read upstream response body"
                    );
                }
                Some((
                    Err(std::io::Error::other("upstream body error")),
                    (inner, true),
                ))
            }
            Ok(None) => None,
            Err(_) => {
                tracing::warn!(
                    "upstream response body stalled past the read idle; aborting the response"
                );
                Some((
                    Err(std::io::Error::new(
                        std::io::ErrorKind::TimedOut,
                        "upstream body read idle timeout",
                    )),
                    (inner, true),
                ))
            }
        }
    })
}

async fn stream_response(
    mut resp: reqwest::Response,
    terminator: Terminator,
    rid: String,
    body_idle: Duration,
) -> Response {
    // The passthrough fallbacks below consume `resp` whole, so the content
    // checks borrow its headers before the map is moved out for the SSE path.
    let is_sse = resp
        .headers()
        .get(header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .map(|v| v.to_ascii_lowercase().starts_with("text/event-stream"))
        .unwrap_or(false);

    if !is_sse || terminator == Terminator::None {
        return pass_through_response(resp, body_idle).await;
    }

    // A content-encoded response is compressed bytes, so terminator scanning
    // is guaranteed to miss; pass it through as-is — better to give up
    // truncation detection than to append plain-text events to a compressed
    // stream (that corrupts the frame tail and makes the client's decoder
    // error out, e.g. Bun's ZstdDecompressionError).
    if is_encoded(resp.headers()) {
        tracing::debug!(rid = %rid, "response is content-encoded, skipping SSE terminator detection");
        return pass_through_response(resp, body_idle).await;
    }

    let status = resp.status();
    // Same in-place hop-by-hop filter as pass_through_response: the map is
    // moved out of the upstream response instead of cloned per header.
    let mut headers = std::mem::take(resp.headers_mut());
    drop_hop_by_hop(&mut headers);

    // Terminator scanning rides an unfold that owns all scan state: each
    // upstream chunk is scanned in place (plus a fixed stack window at the
    // chunk boundary) and passed through unmodified. The previous scan
    // closure had to own its captures per invocation, so every chunk of every
    // stream cloned the rid String and copied carry + chunk into a fresh Vec.
    let inner = Box::pin(resp.bytes_stream());
    let mapped = stream::unfold(
        (inner, SseScan::new(terminator, rid)),
        move |(mut inner, mut scan)| async move {
            if scan.done {
                return None;
            }
            match inner.next().await {
                Some(Ok(chunk)) => {
                    scan.feed(&chunk);
                    Some((Ok::<Bytes, std::io::Error>(chunk), (inner, scan)))
                }
                Some(Err(_)) => {
                    tracing::warn!(rid = %scan.rid, "upstream SSE stream interrupted");
                    let event = sse_error_event("upstream stream error", terminator);
                    scan.finish();
                    Some((Ok(event), (inner, scan)))
                }
                None => {
                    if scan.seen {
                        return None;
                    }
                    tracing::warn!(
                        rid = %scan.rid,
                        "SSE stream ended early without terminator marker, treating as truncated"
                    );
                    let event = sse_error_event("upstream stream ended prematurely", terminator);
                    scan.finish();
                    Some((Ok(event), (inner, scan)))
                }
            }
        },
    );
    build_response(status, headers, Body::from_stream(mapped))
}

/// Longest terminator needle searched by `contains_terminator` (the needle-fit
/// test keeps it honest). The carry window keeps one fewer byte, so a marker
/// split across a chunk boundary always fits in the stack window below.
const TERMINATOR_MAX_NEEDLE: usize = 21;

/// Per-stream state for SSE terminator detection, owned by the response
/// stream's unfold: no Arcs, no Mutex, and nothing allocated per chunk.
struct SseScan {
    terminator: Terminator,
    /// Terminator marker seen (or the stream ended/errored): scanning stops.
    seen: bool,
    /// The stream must end after the synthetic error event has been emitted.
    done: bool,
    /// Tail of the previous chunk, at most `TERMINATOR_MAX_NEEDLE - 1` bytes.
    carry: Vec<u8>,
    /// Request id for the (cold) interruption/truncation log lines.
    rid: String,
}

impl SseScan {
    fn new(terminator: Terminator, rid: String) -> Self {
        Self {
            terminator,
            seen: false,
            done: false,
            carry: Vec::with_capacity(TERMINATOR_MAX_NEEDLE - 1),
            rid,
        }
    }

    /// Marks the stream complete: one more item (the synthetic error event)
    /// is emitted, the next poll ends the stream.
    fn finish(&mut self) {
        self.seen = true;
        self.done = true;
    }

    /// Scans one upstream chunk. The chunk itself is searched in place; a
    /// marker straddling the previous carry and this chunk can only start
    /// within the last L-1 carry bytes and reach at most L-1 bytes into the
    /// chunk, so a fixed stack window of 2·(L-1) bytes covers the boundary
    /// and the chunk body is never copied.
    fn feed(&mut self, chunk: &[u8]) {
        if self.seen || self.terminator == Terminator::None {
            return;
        }
        if contains_terminator(chunk, self.terminator) {
            self.seen = true;
            return;
        }
        let overlap = TERMINATOR_MAX_NEEDLE - 1;
        let head = chunk.len().min(overlap);
        if !self.carry.is_empty() && head > 0 {
            let mut window = [0u8; 2 * (TERMINATOR_MAX_NEEDLE - 1)];
            window[..self.carry.len()].copy_from_slice(&self.carry);
            window[self.carry.len()..self.carry.len() + head].copy_from_slice(&chunk[..head]);
            if contains_terminator(&window[..self.carry.len() + head], self.terminator) {
                self.seen = true;
                return;
            }
        }
        if chunk.len() >= overlap {
            self.carry.clear();
            self.carry
                .extend_from_slice(&chunk[chunk.len() - overlap..]);
        } else {
            let total = self.carry.len() + chunk.len();
            if total > overlap {
                self.carry.drain(..total - overlap);
            }
            self.carry.extend_from_slice(chunk);
        }
    }
}

fn sse_error_event(message: &str, terminator: Terminator) -> Bytes {
    // Inject an Anthropic-shaped error event into Anthropic streams; the others (OpenAI/auto/none) use the OpenAI shape.
    if matches!(terminator, Terminator::Anthropic) {
        let payload = json!({
            "type": "error",
            "error": { "type": "api_error", "message": message }
        });
        Bytes::from(format!("event: error\ndata: {payload}\n\n"))
    } else {
        let payload = json!({ "error": { "type": "upstream_stream_error", "message": message } });
        Bytes::from(format!("data: {payload}\n\ndata: [DONE]\n\n"))
    }
}

/// Every terminator marker the scanner searches for, in one place: the
/// boundary window only covers straddling markers up to
/// TERMINATOR_MAX_NEEDLE, and the fit assertion reads this same array — a
/// needle added here without raising the const fails that test instead of
/// silently blinding the chunk-boundary check. [0] is the OpenAI marker,
/// [1..] the Anthropic ones.
const TERMINATOR_NEEDLES: [&[u8]; 3] = [
    b"data: [DONE]",
    b"event: message_stop",
    b"\"type\":\"message_stop\"",
];

pub(crate) fn contains_terminator(chunk: &[u8], terminator: Terminator) -> bool {
    let needles = match terminator {
        Terminator::Openai => &TERMINATOR_NEEDLES[..1],
        Terminator::Anthropic => &TERMINATOR_NEEDLES[1..],
        Terminator::Auto => &TERMINATOR_NEEDLES[..],
        Terminator::None => return false,
    };
    needles
        .iter()
        .any(|needle| find_memmem(chunk, needle) || find_memmem_ci(chunk, needle))
}

fn find_memmem(haystack: &[u8], needle: &[u8]) -> bool {
    memchr::memmem::find(haystack, needle).is_some()
}

/// ASCII case-insensitive search, memchr-accelerated: a case-insensitive hit
/// at position `i` requires `haystack[i]` to equal the needle's first byte in
/// either case, so SIMD memchr2 locates the only positions worth verifying —
/// an O(n) scan plus a handful of O(m) checks, instead of an O(n*m) windows
/// sweep on every chunk of every SSE stream until the terminator shows up.
fn find_memmem_ci(haystack: &[u8], needle: &[u8]) -> bool {
    if needle.is_empty() || haystack.len() < needle.len() {
        return false;
    }
    let first = needle[0];
    let (cand1, cand2) = if first.is_ascii_alphabetic() {
        (first.to_ascii_lowercase(), first.to_ascii_uppercase())
    } else {
        // Non-letter first byte (e.g. '"' for the anthropic json marker):
        // case folding never touches it, so the exact byte is the candidate.
        (first, first)
    };
    let mut from = 0;
    while let Some(at) = memchr::memchr2(cand1, cand2, &haystack[from..]) {
        let start = from + at;
        if start + needle.len() > haystack.len() {
            return false;
        }
        if haystack[start..start + needle.len()].eq_ignore_ascii_case(needle) {
            return true;
        }
        from = start + 1;
    }
    false
}

fn build_response(status: reqwest::StatusCode, headers: HeaderMap, body: Body) -> Response {
    // Assemble from parts: the status and the already-filtered header map
    // move in wholesale instead of being re-copied header by header through a
    // response builder. Infallible, so the old builder-failure fallback is
    // gone too.
    let mut out = Response::new(body);
    *out.status_mut() = StatusCode::from_u16(status.as_u16()).unwrap_or(StatusCode::BAD_GATEWAY);
    *out.headers_mut() = headers;
    out
}

pub fn error_response(status: StatusCode, kind: &str, message: &str, rid: &str) -> Response {
    let body = json!({
        "error": {
            "type": kind,
            "message": message,
            "request_id": rid,
        }
    })
    .to_string();
    let mut response = (status, [(header::CONTENT_TYPE, "application/json")], body).into_response();
    if let Ok(value) = HeaderValue::from_str(rid) {
        response
            .headers_mut()
            .insert(HeaderName::from_static("x-keysink-request-id"), value);
    }
    response
}

/// Whether to adopt a hot-reloaded new snapshot: never let .bak overwrite a
/// "good" snapshot still being served (.bak lags one generation and would
/// revive revoked/deleted vkeys). Adopt a backup only when there is no
/// current snapshot, or the current snapshot itself came from .bak (old and
/// new are both backups; swapping in the newer one is not a downgrade).
fn adopt_snapshot(incoming_from_backup: bool, current_from_backup: Option<bool>) -> bool {
    !incoming_from_backup || current_from_backup.is_none_or(|current| current)
}

/// Poll cadence for the store watcher while things are healthy.
const RELOAD_POLL: Duration = Duration::from_secs(1);
/// Backoff ceiling for repeated hot-reload failures on the same on-disk
/// state: a corrupt or undecryptable store would otherwise be re-read and
/// re-decrypted every second forever. Any success restores the 1s cadence,
/// so a fix is picked up within one backoff window (≤30s) of landing.
const MAX_RELOAD_BACKOFF: Duration = Duration::from_secs(30);

/// Next wait after a failed reload: doubles per consecutive failure, capped.
fn next_reload_backoff(after: Duration) -> Duration {
    after.saturating_mul(2).min(MAX_RELOAD_BACKOFF)
}

/// Polls the store.age / master.key mtime+size and swaps in a whole new snapshot on change.
pub fn spawn_watcher(state: Arc<AppState>, paths: Paths) {
    tokio::spawn(async move {
        // Zeroed so the first round after startup always reloads once,
        // covering the race where the CLI modified the store between serve
        // finishing the initial store load and the watcher starting.
        let mut last = (0u64, 0u64, 0u64);
        let mut failures = 0u32;
        let mut backup_warned = false;
        let mut delay = RELOAD_POLL;
        loop {
            tokio::time::sleep(delay).await;
            let now = stamp(&paths);
            if now == last {
                continue;
            }
            // File I/O + age decryption + JSON parse + validate are blocking:
            // run them on the blocking pool so a slow disk or a large vault
            // never occupies a tokio worker while requests are being forwarded.
            let unlocked = {
                let paths = paths.clone();
                tokio::task::spawn_blocking(move || crate::store::unlock(&paths))
                    .await
                    .unwrap_or_else(|e| Err(Error::msg(format!("hot reload worker failed: {e}"))))
            };
            match unlocked {
                Ok(unlocked) => match RouteTable::build(&unlocked.store) {
                    Ok(table) => {
                        let from_backup = unlocked.from_backup;
                        if !adopt_snapshot(from_backup, Some(state.snapshot.load().from_backup)) {
                            // .bak wants to overwrite a good in-memory snapshot: refuse the
                            // downgrade. .bak lags one generation and would revive
                            // revoked/deleted vkeys; memory still holds the latest good data.
                            last = now;
                            delay = RELOAD_POLL;
                            if !backup_warned {
                                tracing::error!(
                                    "main store failed to decrypt, refusing to overwrite in-memory snapshot with stale .bak (continuing to serve the latest good data); fix the main store ASAP"
                                );
                                backup_warned = true;
                            }
                            continue;
                        }
                        let routes = table.len();
                        let live_urls: HashSet<String> = unlocked
                            .store
                            .routes
                            .values()
                            .filter_map(|r| r.proxy.clone())
                            .filter(|p| p.as_str() != crate::model::PROXY_DIRECT)
                            .collect();
                        state.snapshot.store(Arc::new(Snapshot {
                            store: Arc::new(unlocked.store),
                            table,
                            from_backup,
                        }));
                        state.clients.retain_urls(&live_urls);
                        last = now;
                        failures = 0;
                        delay = RELOAD_POLL;
                        backup_warned = false;
                        if from_backup {
                            tracing::error!(
                                "hot reload fell back to .bak backup (main store failed to decrypt): revoked/deleted vkeys may become effective again; fix ASAP"
                            );
                        }
                        tracing::info!(routes, from_backup, "store hot-reloaded");
                    }
                    Err(e) => {
                        failures += 1;
                        delay = next_reload_backoff(delay);
                        if failures % 10 == 1 {
                            tracing::warn!(error = %e, "hot reload validation failed, keeping old snapshot");
                        }
                    }
                },
                Err(e) => {
                    failures += 1;
                    delay = next_reload_backoff(delay);
                    if failures % 10 == 1 {
                        tracing::warn!(error = %e, "hot reload decryption failed, keeping old snapshot");
                    }
                }
            }
        }
    });
}

fn stamp(paths: &Paths) -> (u64, u64, u64) {
    fn one(path: &std::path::Path) -> u64 {
        let Ok(md) = std::fs::metadata(path) else {
            return 0;
        };
        let mtime = md
            .modified()
            .ok()
            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
            .map(|d| d.as_nanos() as u64)
            .unwrap_or(0);
        // Mix in the inode: atomic writes go through rename, which always
        // changes the inode, so even with coarse filesystem mtime granularity
        // (e.g. 1s) and identical sizes across two writes the change is not
        // missed.
        #[cfg(unix)]
        {
            use std::os::unix::fs::MetadataExt as _;
            mtime ^ md.len().rotate_left(17) ^ md.ino().rotate_left(41)
        }
        #[cfg(not(unix))]
        {
            mtime ^ md.len().rotate_left(17)
        }
    }
    (
        one(&paths.store()),
        one(&paths.master_key()),
        one(&paths.store_bak()),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::Auth;
    use std::collections::BTreeMap;

    fn route(auth: Auth) -> Route {
        Route::new(
            vkey::generate(),
            "https://api.example.com".into(),
            "real-key-123".into(),
            auth,
            BTreeMap::new(),
        )
    }

    #[test]
    fn extracts_vkey_case_insensitive_and_from_alt_headers() {
        let token = vkey::generate();
        let mut h = HeaderMap::new();
        h.insert(
            header::AUTHORIZATION,
            HeaderValue::from_str(&format!("BEARER {token}")).unwrap(),
        );
        assert_eq!(extract_vkey(&h).as_deref(), Some(token.as_str()));

        let mut h = HeaderMap::new();
        h.insert("x-api-key", HeaderValue::from_str(&token).unwrap());
        assert_eq!(extract_vkey(&h).as_deref(), Some(token.as_str()));

        let mut h = HeaderMap::new();
        h.insert(
            header::AUTHORIZATION,
            HeaderValue::from_static("Bearer sk-real"),
        );
        assert!(extract_vkey(&h).is_none());
    }

    #[test]
    fn rejects_forbidden_static_headers() {
        let mut r = route(Auth::Bearer);
        r.headers.insert("host".into(), "evil".into());
        assert!(r.validate("r").is_err());
    }

    #[test]
    fn detects_stream_flag() {
        assert!(is_stream_request(br#"{"stream":true}"#));
        assert!(is_stream_request(br#"{"stream": true, "x": 1}"#));
        assert!(!is_stream_request(br#"{"stream":false}"#));
        assert!(!is_stream_request(br#"{"model":"x"}"#));
        assert!(!is_stream_request(b"not json"));
        assert!(!is_stream_request(b""));
    }

    #[test]
    fn terminator_needles_fit_the_carry_window() {
        for needle in TERMINATOR_NEEDLES {
            assert!(
                needle.len() <= TERMINATOR_MAX_NEEDLE,
                "needle {needle:?} is longer than TERMINATOR_MAX_NEEDLE; raise the const so the boundary window still covers straddling markers"
            );
        }
    }

    #[test]
    fn scan_finds_markers_split_at_every_point() {
        for marker in TERMINATOR_NEEDLES {
            // two-chunk split at every interior point
            for split in 1..marker.len() {
                let mut scan = SseScan::new(Terminator::Auto, "R".into());
                scan.feed(&marker[..split]);
                assert!(
                    !scan.seen,
                    "{marker:?} split {split}: a partial marker must not match"
                );
                scan.feed(&marker[split..]);
                assert!(
                    scan.seen,
                    "{marker:?} split {split}: a completed marker must be found"
                );
            }
            // byte-by-byte arrival
            let mut scan = SseScan::new(Terminator::Auto, "R".into());
            for (i, byte) in marker.iter().enumerate() {
                scan.feed(std::slice::from_ref(byte));
                assert_eq!(
                    scan.seen,
                    i + 1 == marker.len(),
                    "{marker:?} byte {i}: seen must flip exactly at the last byte"
                );
            }
            // an ordinary event stream must not trip the scanner
            let mut scan = SseScan::new(Terminator::Auto, "R".into());
            scan.feed(b"event: delta\ndata: {\"i\":0}\n\n");
            assert!(!scan.seen);
            // terminator disabled: never scans, carry stays empty
            let mut scan = SseScan::new(Terminator::None, "R".into());
            scan.feed(b"event: message_stop\n\n");
            assert!(!scan.seen && scan.carry.is_empty());
        }
    }

    #[test]
    fn builds_url_with_path_and_query() {
        let url = build_upstream_url(
            "https://api.example.com/",
            "/v1/messages",
            Some("a=1&b=2"),
            &Auth::Bearer,
            "secret",
        )
        .unwrap();
        assert_eq!(url, "https://api.example.com/v1/messages?a=1&b=2");
    }

    #[test]
    fn query_auth_replaces_existing_param() {
        let url = build_upstream_url(
            "https://generativelanguage.googleapis.com",
            "/v1beta/models/x:generateContent",
            Some("alt=sse&key=old"),
            &Auth::Query {
                param: "key".into(),
            },
            "a b&c",
        )
        .unwrap();
        assert_eq!(
            url,
            "https://generativelanguage.googleapis.com/v1beta/models/x:generateContent?alt=sse&key=a%20b%26c"
        );
    }

    #[test]
    fn injects_bearer_and_strips_inbound_auth() {
        let mut src = HeaderMap::new();
        src.insert(
            header::AUTHORIZATION,
            HeaderValue::from_static("Bearer ks_xxx"),
        );
        src.insert("x-api-key", HeaderValue::from_static("ks_xxx"));
        src.insert("x-custom", HeaderValue::from_static("ok"));
        let out = forward_headers(&src, &route(Auth::Bearer), "real-secret", false).unwrap();
        assert_eq!(
            out.get(header::AUTHORIZATION).unwrap(),
            "Bearer real-secret"
        );
        assert!(out.get("x-api-key").is_none());
        assert_eq!(out.get("x-custom").unwrap(), "ok");
    }

    #[test]
    fn injects_x_api_key_and_static_headers() {
        let mut r = route(Auth::XApiKey);
        r.headers
            .insert("anthropic-version".into(), "2023-06-01".into());
        let out = forward_headers(&HeaderMap::new(), &r, "real", false).unwrap();
        assert_eq!(out.get("x-api-key").unwrap(), "real");
        assert_eq!(out.get("anthropic-version").unwrap(), "2023-06-01");
    }

    #[test]
    fn strips_accept_encoding_only_for_streaming_requests() {
        let mut src = HeaderMap::new();
        src.insert(
            header::ACCEPT_ENCODING,
            HeaderValue::from_static("gzip, deflate, br, zstd"),
        );
        let r = route(Auth::Bearer);

        let streamed = forward_headers(&src, &r, "k", true).unwrap();
        assert!(streamed.get(header::ACCEPT_ENCODING).is_none());

        let plain = forward_headers(&src, &r, "k", false).unwrap();
        assert_eq!(
            plain.get(header::ACCEPT_ENCODING).unwrap(),
            "gzip, deflate, br, zstd"
        );
    }

    #[test]
    fn streaming_route_static_accept_encoding_is_dropped() {
        // A statically configured accept-encoding blinds the SSE terminator
        // scan just the same, so streaming must drop it too.
        let mut r = route(Auth::Bearer);
        r.headers.insert("accept-encoding".into(), "gzip".into());
        r.headers.insert("ACCEPT-ENCODING".into(), "br".into());
        let out = forward_headers(&HeaderMap::new(), &r, "k", true).unwrap();
        assert!(out.get(header::ACCEPT_ENCODING).is_none());
        let plain = forward_headers(&HeaderMap::new(), &r, "k", false).unwrap();
        assert_eq!(plain.get(header::ACCEPT_ENCODING).unwrap(), "br");
    }

    #[test]
    fn detects_content_encoding_but_not_identity() {
        let mut headers = HeaderMap::new();
        assert!(!is_encoded(&headers));

        headers.insert(
            header::CONTENT_ENCODING,
            HeaderValue::from_static("identity"),
        );
        assert!(!is_encoded(&headers));

        headers.insert(header::CONTENT_ENCODING, HeaderValue::from_static("zstd"));
        assert!(is_encoded(&headers));

        headers.insert(
            header::CONTENT_ENCODING,
            HeaderValue::from_static("gzip, br"),
        );
        assert!(is_encoded(&headers));
    }

    #[test]
    fn basic_auth_encodes_pair() {
        let out = forward_headers(
            &HeaderMap::new(),
            &route(Auth::Basic {
                username: "user".into(),
            }),
            "pass",
            false,
        )
        .unwrap();
        assert_eq!(
            out.get(header::AUTHORIZATION).unwrap(),
            "Basic dXNlcjpwYXNz"
        );
    }

    #[test]
    fn detects_sse_terminators() {
        assert!(contains_terminator(b"data: [DONE]\n\n", Terminator::Auto));
        assert!(contains_terminator(
            b"event: message_stop\ndata: {}\n\n",
            Terminator::Auto
        ));
        assert!(!contains_terminator(
            b"data: {\"i\":0}\n\n",
            Terminator::Auto
        ));
        assert!(contains_terminator(b"DATA: [done]\n\n", Terminator::Openai));
        assert!(!contains_terminator(
            b"data: [DONE]\n\n",
            Terminator::Anthropic
        ));
        assert!(!contains_terminator(b"data: [DONE]\n\n", Terminator::None));
    }

    #[test]
    fn stream_probe_semantics() {
        // shapes real clients send
        assert!(is_stream_request(br#"{"model":"m","stream":true}"#));
        assert!(is_stream_request(br#"{"stream":true,"model":"m"}"#));
        assert!(!is_stream_request(br#"{"stream":null}"#));
        assert!(!is_stream_request(br#"{"stream":"true"}"#));
        assert!(!is_stream_request(br#"{"stream":1}"#));
        // escaped keys decode to the same member name; the prefilter needs a
        // literal `"stream"` somewhere, so pair the escaped key with one
        assert!(is_stream_request(
            br#"{"stre\u0061m":true,"note":"stream"}"#
        ));
        assert!(!is_stream_request(br#"{"stre\u0061m":true}"#));
        // documented divergences from the old full-parse probe (see
        // top_level_stream_true): only reachable on bodies that are not
        // valid LLM requests
        assert!(is_stream_request(br#"{"stream":true} trailing garbage"#));
        assert!(is_stream_request(br#"{"stream":true,"stream":false}"#));
        assert!(!is_stream_request(b"[true]"));
    }

    #[test]
    fn finds_sse_terminators_in_all_case_variants() {
        // find_memmem_ci edge positions: exact-length haystack (hit at 0),
        // hit at the very end, dense candidate bytes exercising the rescan
        // loop, non-letter first byte ('"' for the anthropic json marker),
        // and the miss paths (needle does not fit, no candidate at all).
        assert!(find_memmem_ci(b"data: [DONE]", b"data: [DONE]"));
        assert!(find_memmem_ci(
            b"xxxxxxxxxxxxxdata: [DONE]",
            b"data: [DONE]"
        ));
        let dense: Vec<u8> = [vec![b'd'; 30], b"data: [DONE]".to_vec()].concat();
        assert!(find_memmem_ci(&dense, b"data: [DONE]"));
        assert!(find_memmem_ci(
            b"{\"i\":0} \"TYPE\":\"MESSAGE_STOP\"",
            b"\"type\":\"message_stop\""
        ));
        // candidate present but the needle does not fit past it
        assert!(!find_memmem_ci(b"xxdata: [DON", b"data: [DONE]"));
        assert!(!find_memmem_ci(b"data: [DON", b"data: [DONE]"));
        assert!(!find_memmem_ci(b"no marker here", b"data: [DONE]"));
    }

    #[test]
    fn rid_grows_past_four_digits() {
        assert_eq!(rid_from(0), "0000");
        assert_eq!(rid_from(1), "0001");
        assert_eq!(rid_from(1679615), "ZZZZ");
        assert_eq!(rid_from(1679616), "10000");
        assert_eq!(rid_from(u64::MAX).len(), 13);
    }

    #[test]
    fn sse_error_event_matches_protocol() {
        let anthropic = sse_error_event("boom", Terminator::Anthropic);
        let text = std::str::from_utf8(&anthropic).unwrap();
        assert!(text.starts_with("event: error\n"));
        assert!(text.contains("\"type\":\"error\""));
        assert!(!text.contains("[DONE]"));

        let openai = sse_error_event("boom", Terminator::Openai);
        let text = std::str::from_utf8(&openai).unwrap();
        assert!(text.starts_with("data: {"));
        assert!(text.ends_with("data: [DONE]\n\n"));

        let auto = sse_error_event("boom", Terminator::Auto);
        assert_eq!(auto, openai);
    }

    #[test]
    fn proxy_clients_follow_route_config() {
        let clients = ProxyClients::new().unwrap();
        let mut r = route(Auth::Bearer);

        r.proxy = None;
        assert!(clients.for_route(&r, false).is_ok());
        assert!(clients.for_route(&r, true).is_ok());
        r.proxy = Some("direct".into());
        assert!(clients.for_route(&r, false).is_ok());
        r.proxy = Some("http://127.0.0.1:7890".into());
        assert!(clients.for_route(&r, true).is_ok());
        assert!(clients.for_route(&r, false).is_ok()); // cache-hit path

        r.proxy = Some("http://".into()); // valid scheme but empty host in the URL
        assert!(clients.for_route(&r, false).is_err());
    }

    #[test]
    fn retain_urls_evicts_stale_proxy_clients() {
        let clients = ProxyClients::new().unwrap();
        let mut r = route(Auth::Bearer);
        r.proxy = Some("http://127.0.0.1:7890".into());
        assert!(clients.for_route(&r, false).is_ok());

        let mut live = HashSet::new();
        clients.retain_urls(&live);
        assert!(clients.for_route(&r, false).is_ok()); // rebuilt (i.e. it had been evicted)

        live.insert("http://127.0.0.1:7890".into());
        clients.for_route(&r, false).unwrap();
        clients.retain_urls(&live);
        clients.for_route(&r, false).unwrap();
    }

    #[tokio::test]
    async fn classifies_length_limit_by_type_not_string_only() {
        // LengthLimitError is #[non_exhaustive] and cannot be constructed
        // directly in tests; take the real path: when to_bytes exceeds the
        // limit, it is in the axum::Error source chain.
        let e = axum::body::to_bytes(axum::body::Body::from("hello"), 2)
            .await
            .unwrap_err();
        assert!(is_length_limit_error(&e));
        let other = axum::Error::new(std::io::Error::other("boom"));
        assert!(!is_length_limit_error(&other));
    }

    #[test]
    fn watcher_never_downgrades_good_snapshot_to_backup() {
        // new snapshot is the main store → adopt unconditionally
        assert!(adopt_snapshot(false, Some(false)));
        // .bak wants to overwrite a good snapshot still being served → refuse
        assert!(!adopt_snapshot(true, Some(false)));
        // no current snapshot (startup path) → adopt
        assert!(adopt_snapshot(true, None));
        // the current snapshot itself is from .bak → a peer replacement is not a downgrade
        assert!(adopt_snapshot(true, Some(true)));
    }

    #[test]
    fn network_errors_retry_only_when_replay_safe() {
        // connect-class error: request definitely not delivered → replayable
        assert!(network_retry_allowed(true, false));
        // idempotent method: any network error is replayable
        assert!(network_retry_allowed(false, true));
        // POST + non-connect error (timeout/disconnect): upstream may have billed → not replayable
        assert!(!network_retry_allowed(false, false));
    }

    #[test]
    fn reload_backoff_doubles_and_caps() {
        let mut d = RELOAD_POLL;
        for _ in 0..10 {
            d = next_reload_backoff(d);
        }
        assert_eq!(d, MAX_RELOAD_BACKOFF);
        assert_eq!(
            next_reload_backoff(d),
            d,
            "once capped, backoff stays capped"
        );
    }

    #[cfg(unix)]
    #[test]
    fn transient_accept_errors_are_the_descriptor_pressure_kinds() {
        assert!(is_transient_accept_error(
            &std::io::Error::from_raw_os_error(libc::EMFILE)
        ));
        assert!(is_transient_accept_error(
            &std::io::Error::from_raw_os_error(libc::ENFILE)
        ));
        // A peer resetting mid-accept is none of our pressure; it stays fatal.
        assert!(!is_transient_accept_error(
            &std::io::Error::from_raw_os_error(libc::ECONNABORTED)
        ));
        assert!(!is_transient_accept_error(&std::io::Error::other("boom")));
    }

    #[tokio::test(start_paused = true)]
    async fn idle_bounded_passes_chunks_and_ends_cleanly() {
        let inner = stream::iter(vec![
            Ok::<Bytes, reqwest::Error>(Bytes::from_static(b"a")),
            Ok(Bytes::from_static(b"b")),
        ]);
        let mut s = Box::pin(idle_bounded(inner, Duration::from_secs(60)));
        assert_eq!(s.next().await.unwrap().unwrap(), Bytes::from_static(b"a"));
        assert_eq!(s.next().await.unwrap().unwrap(), Bytes::from_static(b"b"));
        assert!(s.next().await.is_none());
    }

    #[tokio::test(start_paused = true)]
    async fn idle_bounded_aborts_stalled_body_and_stops() {
        // one chunk, then the upstream goes silent forever
        let inner = stream::once(async { Ok::<Bytes, reqwest::Error>(Bytes::from_static(b"x")) })
            .chain(stream::pending::<reqwest::Result<Bytes>>());
        let mut s = Box::pin(idle_bounded(inner, Duration::from_secs(30)));
        assert_eq!(s.next().await.unwrap().unwrap(), Bytes::from_static(b"x"));
        let err = s.next().await.unwrap().unwrap_err();
        assert_eq!(err.kind(), std::io::ErrorKind::TimedOut);
        // after the timeout error the stream must end, not loop errors
        assert!(s.next().await.is_none());
    }

    #[tokio::test(start_paused = true)]
    async fn idle_bounded_tolerates_slow_but_alive_upstream() {
        // gaps well under the idle bound must not trip the abort
        let inner = stream::iter(0u8..3).then(|i| async move {
            tokio::time::sleep(Duration::from_secs(10)).await;
            Ok::<Bytes, reqwest::Error>(Bytes::from(vec![i]))
        });
        let mut s = Box::pin(idle_bounded(inner, Duration::from_secs(60)));
        for i in 0u8..3 {
            assert_eq!(s.next().await.unwrap().unwrap(), Bytes::from(vec![i]));
        }
        assert!(s.next().await.is_none());
    }
}

#[cfg(test)]
mod serve_inbound_tests {
    use super::*;
    use crate::model::Store;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    fn test_state() -> Arc<AppState> {
        Arc::new(AppState {
            snapshot: ArcSwap::from_pointee(Snapshot {
                store: Arc::new(Store::new()),
                table: RouteTable::build(&Store::new()).unwrap(),
                from_backup: false,
            }),
            clients: ProxyClients::new().unwrap(),
            retry: RetryPolicy::default(),
            body_limit: 1 << 20,
            body_read_idle: BODY_READ_IDLE,
            inbound_body_timeout: CLIENT_BODY_TIMEOUT,
            permit_queue_timeout: PERMIT_QUEUE_TIMEOUT,
            inbound_permits: Arc::new(tokio::sync::Semaphore::new(8)),
            audit: Audit::disabled(),
            started: Instant::now(),
        })
    }

    /// Regression: the reaping arm of the accept select must be disabled while
    /// the JoinSet is empty. `join_next` returns Ready(None) immediately for an
    /// empty set, so an unguarded arm is always ready — the loop spins on it
    /// and `listener.accept()` is never polled: the gateway accepts nothing
    /// (connections pile up in the kernel backlog) while burning CPU. A real
    /// round trip through serve_inbound is the only way to see it; handler-level
    /// tests bypass the accept loop entirely. The timeout guard turns the
    /// regression into a fast failure instead of a hang.
    #[tokio::test]
    async fn serve_inbound_accepts_and_answers_while_reaping() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = tokio::spawn(serve_inbound(
            listener,
            build_app(test_state()),
            InboundLimits {
                header_timeout: CLIENT_HEADER_TIMEOUT,
                max_connections: 64,
                loop_iterations: None,
            },
            std::future::pending(),
        ));

        // First connection is served (the empty-set spin never gets here).
        let buf = tokio::time::timeout(Duration::from_secs(10), async {
            let mut s = tokio::net::TcpStream::connect(addr).await?;
            s.write_all(b"GET /__keysink/health HTTP/1.1\r\nhost: t\r\nconnection: close\r\n\r\n")
                .await?;
            let mut buf = Vec::new();
            s.read_to_end(&mut buf).await?;
            Ok::<Vec<u8>, std::io::Error>(buf)
        })
        .await
        .expect("serve_inbound must accept and answer connections")
        .unwrap();
        assert!(
            buf.starts_with(b"HTTP/1.1 200"),
            "health must answer 200, got: {}",
            String::from_utf8_lossy(&buf)
        );

        // A finished connection task must be reaped: after the connection
        // closes, the JoinSet drains back to empty and the loop returns to
        // accept() — proven indirectly by a second full round trip.
        tokio::time::timeout(Duration::from_secs(10), async {
            loop {
                // The server task is polled concurrently; sleep a tick per probe.
                tokio::time::sleep(Duration::from_millis(20)).await;
                // Indirect probe: a second request must also be served, which
                // proves the loop returned to accept() after reaping.
                let mut s = tokio::net::TcpStream::connect(addr).await?;
                s.write_all(
                    b"GET /__keysink/health HTTP/1.1\r\nhost: t\r\nconnection: close\r\n\r\n",
                )
                .await?;
                let mut buf = Vec::new();
                s.read_to_end(&mut buf).await?;
                if buf.starts_with(b"HTTP/1.1 200") {
                    return Ok::<(), std::io::Error>(());
                }
            }
        })
        .await
        .expect("second connection must also be served after the first was reaped")
        .unwrap();

        server.abort();
    }

    /// Regression (idle spin): the same unguarded reaping arm spins the loop
    /// even with NO connections — join_next is always ready on an empty set,
    /// so the loop burns a core while idle and the round-trip test above
    /// cannot see it (its connections arrive fast enough that accept wins
    /// the select races anyway). The loop counter makes the spin directly
    /// assertable: an idle loop must pend on accept, not iterate.
    #[tokio::test]
    async fn serve_inbound_idle_loop_pends_instead_of_spinning() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let iterations = Arc::new(AtomicU64::new(0));
        let server = tokio::spawn(serve_inbound(
            listener,
            build_app(test_state()),
            InboundLimits {
                header_timeout: CLIENT_HEADER_TIMEOUT,
                max_connections: 8,
                loop_iterations: Some(iterations.clone()),
            },
            std::future::pending(),
        ));

        // Idle for 300ms: with the guard the loop sits in accept (1-2
        // iterations); the spin bug produces ~1e6 iterations per second.
        tokio::time::sleep(Duration::from_millis(300)).await;
        let count = iterations.load(Ordering::Relaxed);
        assert!(
            count < 1_000,
            "idle accept loop must pend on accept, not spin; iterations in 300ms: {count}"
        );

        // Still healthy afterwards: one round trip through the same loop.
        let buf = tokio::time::timeout(Duration::from_secs(10), async {
            let mut s = tokio::net::TcpStream::connect(addr).await?;
            s.write_all(b"GET /__keysink/health HTTP/1.1\r\nhost: t\r\nconnection: close\r\n\r\n")
                .await?;
            let mut buf = Vec::new();
            s.read_to_end(&mut buf).await?;
            Ok::<Vec<u8>, std::io::Error>(buf)
        })
        .await
        .expect("idle loop must still accept and answer")
        .unwrap();
        assert!(buf.starts_with(b"HTTP/1.1 200"));

        server.abort();
    }

    /// Regression (sniff DoS): a connection that never sends a byte must be
    /// dropped within the head timeout. Before the sniff read, such a
    /// connection parked a connection slot forever — hyper-util's auto
    /// builder polls for the 24-byte h2 preface with no bound, and neither
    /// header_read_timeout (http1-only) nor the h2 keep-alive PING
    /// (post-handshake only) reaches that phase.
    #[tokio::test]
    async fn serve_inbound_drops_silent_connection_within_head_timeout() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let head_timeout = Duration::from_millis(300);
        let server = tokio::spawn(serve_inbound(
            listener,
            build_app(test_state()),
            InboundLimits {
                header_timeout: head_timeout,
                max_connections: 8,
                loop_iterations: None,
            },
            std::future::pending(),
        ));

        // Connect and say nothing: the server must close the socket.
        // Without the sniff bound this read hangs until the test timeout —
        // exactly the parked-slot DoS. (The trickle variant is covered
        // deterministically, with paused time, in sniff_protocol_decides_or_times_out.)
        let closed = tokio::time::timeout(head_timeout * 10, async {
            let mut s = tokio::net::TcpStream::connect(addr).await?;
            let mut buf = [0u8; 16];
            loop {
                match s.read(&mut buf).await {
                    Ok(0) => return Ok::<(), std::io::Error>(()),
                    Ok(_) => continue,
                    Err(e) => return Err(e),
                }
            }
        })
        .await
        .expect("silent connection must be dropped within the head timeout");
        assert!(
            closed.is_ok(),
            "expected clean EOF, got {:?}",
            closed.unwrap_err()
        );

        server.abort();
    }

    /// sniff_protocol hands h2 bursts through whole (preface + first frames
    /// in one read is legal client behavior), stops at the first divergence
    /// (http1 needs no further sniffing), EOFs cleanly, and — the whole
    /// point — drops a silent or trickling peer at the whole-phase deadline
    /// instead of parking the connection slot forever.
    #[tokio::test(start_paused = true)]
    async fn sniff_protocol_decides_or_times_out() {
        // h2 burst: preface + a settings frame payload in one write; the
        // overshoot must come back intact for hyper to parse.
        let (mut client, mut server) = tokio::io::duplex(64);
        let mut burst = H2_PREFACE.to_vec();
        burst.extend_from_slice(&[0, 0, 0, 4, 0, 0, 0, 0]);
        client.write_all(&burst).await.unwrap();
        let seen = sniff_protocol(&mut server, Duration::from_secs(30))
            .await
            .unwrap();
        assert_eq!(seen, burst, "preface burst must pass through unmodified");

        // http1 divergence: first byte already decides, one read is enough.
        let (mut client, mut server) = tokio::io::duplex(64);
        client.write_all(b"GET /x HTTP/1.1\r\n").await.unwrap();
        let seen = sniff_protocol(&mut server, Duration::from_secs(30))
            .await
            .unwrap();
        assert_eq!(seen, b"GET /x HTTP/1.1\r\n".to_vec());

        // Silent peer: the deadline must fire, not hang.
        let (_client, mut server) = tokio::io::duplex(64);
        let err = sniff_protocol(&mut server, Duration::from_secs(30))
            .await
            .unwrap_err();
        assert_eq!(err.kind(), std::io::ErrorKind::TimedOut);

        // Trickle: preface bytes one at a time keeps the prefix forever
        // undecided, so only the whole-phase deadline (not a per-read one)
        // can end the sniff.
        let (mut client, mut server) = tokio::io::duplex(64);
        let dribble = tokio::spawn(async move {
            loop {
                for byte in H2_PREFACE {
                    if client.write_all(&[*byte]).await.is_err() {
                        return;
                    }
                    tokio::time::sleep(Duration::from_secs(10)).await;
                }
            }
        });
        let err = sniff_protocol(&mut server, Duration::from_secs(30))
            .await
            .unwrap_err();
        assert_eq!(err.kind(), std::io::ErrorKind::TimedOut);
        dribble.abort();
    }

    /// PrefaceIo must replay the sniffed bytes before the live stream, then
    /// disappear — hyper sees exactly the byte stream it would have read
    /// itself, across replay-buffer boundaries.
    #[tokio::test]
    async fn preface_io_replays_then_passes_through() {
        let (mut client, server) = tokio::io::duplex(8);
        let mut io = PrefaceIo {
            io: server,
            preface: b"PRI * HTTP/2.0".to_vec(),
            pos: 0,
        };
        client.write_all(b"|live|").await.unwrap();
        drop(client); // read_to_end needs the peer's EOF

        let mut seen = Vec::new();
        io.read_to_end(&mut seen).await.unwrap();
        assert_eq!(
            seen,
            b"PRI * HTTP/2.0|live|".to_vec(),
            "replayed preface must precede live bytes"
        );
    }
}