keysink 0.2.3

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
//! End-to-end proxy fuzzing against a mock upstream, SSE marker-split
//! fuzzing over real chunked streams, and performance scenarios.
//!
//! Everything here drives the real HTTP stack (axum server → keysink handler
//! → reqwest → mock upstream); invariants focus on credential isolation,
//! request fidelity, and the SSE truncation detector.

use axum::body::Body;
use axum::extract::{Request, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::{Json, Router};
use base64::Engine;
use bytes::Bytes;
use futures_util::{StreamExt, future::join_all};
use keysink::model::{Auth, Route, Store, Terminator};
use keysink::retry::RetryPolicy;
use keysink::vkey;
use serde_json::json;
use std::collections::{BTreeMap, HashMap};
use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use tokio::net::TcpListener;

const REAL_KEY: &str = "real-upstream-key-123";

/// Best-effort lift of the soft `RLIMIT_NOFILE` so the concurrent suites don't
/// trip over the OS default: macOS ships soft=256, and every in-flight request
/// pins ~4 fds inside this one process (test-client socket, gateway accept,
/// gateway→upstream socket, upstream accept) — the 100-way suite needs ~400
/// plus whatever the parallel test threads hold. Under EMFILE the gateway
/// surfaces 502s (upstream connect refused) or the client sees
/// IncompleteMessage: a limit of the test harness, not of the gateway (real
/// installs run under systemd's LimitNOFILE=16384). Raises to
/// min(hard, 10240) — macOS rejects soft values above OPEN_MAX. Failure is
/// fine (a hard cap at the default): the concurrent test degrades to
/// wave-limited concurrency instead.
#[cfg(unix)]
fn raise_fd_limit() {
    let mut lim: libc::rlimit = unsafe { std::mem::zeroed() };
    // SAFETY: getrlimit/setrlimit only touch the passed struct.
    unsafe {
        if libc::getrlimit(libc::RLIMIT_NOFILE, &mut lim) != 0 {
            return;
        }
        let target = lim.rlim_max.min(10_240);
        if lim.rlim_cur < target {
            lim.rlim_cur = target;
            let _ = libc::setrlimit(libc::RLIMIT_NOFILE, &lim);
        }
    }
}

/// Deterministic splitmix-style generator so failures reproduce.
struct Lcg(u64);

impl Lcg {
    fn next(&mut self) -> u64 {
        self.0 = self
            .0
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        self.0 >> 33
    }

    fn below(&mut self, n: usize) -> usize {
        if n == 0 {
            0
        } else {
            (self.next() % n as u64) as usize
        }
    }

    fn pick<'a, T>(&mut self, items: &'a [T]) -> &'a T {
        &items[self.below(items.len())]
    }
}

// ---------- mock upstream ----------

async fn spawn_mock() -> (SocketAddr, Arc<AtomicUsize>) {
    #[cfg(unix)]
    raise_fd_limit();
    let hits = Arc::new(AtomicUsize::new(0));
    let app = Router::new()
        .fallback(mock_handler)
        .with_state(hits.clone());
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    tokio::spawn(async move {
        axum::serve(listener, app).await.unwrap();
    });
    (addr, hits)
}

async fn mock_handler(State(hits): State<Arc<AtomicUsize>>, req: Request<Body>) -> Response {
    hits.fetch_add(1, Ordering::Relaxed);
    let (parts, body) = req.into_parts();
    let path = parts.uri.path().to_string();
    let query = parts.uri.query().unwrap_or("").to_string();
    let method = parts.method.to_string();

    if path == "/hang" {
        std::future::pending::<()>().await;
        unreachable!();
    }
    if path == "/stall-body" {
        // Headers arrive, one chunk is delivered, then the upstream goes
        // silent forever — the non-streaming body read idle must abort it.
        let stream = futures_util::stream::once(async {
            Ok::<_, std::io::Error>(Bytes::from_static(b"partial-"))
        })
        .chain(futures_util::stream::pending());
        return (
            StatusCode::OK,
            [("content-type", "application/json")],
            Body::from_stream(stream),
        )
            .into_response();
    }
    if path == "/stall-body-429" {
        // Headers arrive (429 = retryable), one chunk follows, then the
        // upstream goes silent: the retry path's discard must be bounded,
        // or the handler (and its inbound permit) parks forever.
        let stream = futures_util::stream::once(async {
            Ok::<_, std::io::Error>(Bytes::from_static(b"partial-"))
        })
        .chain(futures_util::stream::pending());
        return (
            StatusCode::TOO_MANY_REQUESTS,
            [("content-type", "application/json")],
            Body::from_stream(stream),
        )
            .into_response();
    }
    if let Some(code) = path.strip_prefix("/status/") {
        let status = StatusCode::from_u16(code.parse().unwrap_or(500)).unwrap_or(StatusCode::OK);
        return status.into_response();
    }
    if path == "/sse" {
        return sse_response(&query).await;
    }
    if path == "/trickle-sse" {
        // n chunks, one every pace_ms, then a clean end: long enough to
        // outlive a tiny whole-body budget while staying well inside the
        // per-chunk idle bound. Deterministic proxy for a long agent stream.
        let mut n = 10usize;
        let mut pace_ms = 100u64;
        for pair in query.split('&') {
            let mut kv = pair.splitn(2, '=');
            match (kv.next(), kv.next()) {
                (Some("n"), Some(v)) => n = v.parse().unwrap_or(10),
                (Some("pace_ms"), Some(v)) => pace_ms = v.parse().unwrap_or(100),
                _ => {}
            }
        }
        let stream = futures_util::stream::iter(0..n).then(move |i| async move {
            tokio::time::sleep(Duration::from_millis(pace_ms)).await;
            Ok::<_, std::io::Error>(Bytes::from(format!("data: {{\"i\":{i}}}\n\n")))
        });
        return (
            StatusCode::OK,
            [("content-type", "text/event-stream")],
            Body::from_stream(stream),
        )
            .into_response();
    }

    let headers: BTreeMap<String, String> = parts
        .headers
        .iter()
        .map(|(k, v)| {
            (
                k.to_string(),
                String::from_utf8_lossy(v.as_bytes()).into_owned(),
            )
        })
        .collect();
    let bytes = axum::body::to_bytes(body, 64 * 1024 * 1024)
        .await
        .unwrap_or_default();
    Json(json!({
        "method": method,
        "path": path,
        "query": query,
        "headers": headers,
        "body_b64": base64::engine::general_purpose::STANDARD.encode(&bytes),
    }))
    .into_response()
}

#[derive(serde::Deserialize)]
struct Echo {
    method: String,
    path: String,
    query: String,
    headers: BTreeMap<String, String>,
    body_b64: String,
}

async fn sse_response(query: &str) -> Response {
    let mut marker_kind = "openai";
    let mut seed = 0u64;
    let mut truncate = false;
    let mut tail = false;
    for pair in query.split('&') {
        let mut kv = pair.splitn(2, '=');
        match (kv.next(), kv.next()) {
            (Some("marker"), Some(v)) => marker_kind = v,
            (Some("seed"), Some(v)) => seed = v.parse().unwrap_or(0),
            (Some("truncate"), Some(v)) => truncate = v == "1",
            (Some("tail"), Some(v)) => tail = v == "1",
            _ => {}
        }
    }
    let marker: &[u8] = match marker_kind {
        "anth_ev" => b"event: message_stop\n\n",
        "anth_json" => b"data: {\"type\":\"message_stop\"}\n\n",
        _ => b"data: [DONE]\n\n",
    };
    let chunks = plan_sse(seed, marker, truncate, tail);
    let stream = futures_util::stream::unfold(chunks, |mut remaining| async move {
        if remaining.is_empty() {
            return None;
        }
        let (bytes, sleep) = remaining.remove(0);
        if sleep {
            tokio::time::sleep(Duration::from_millis(8)).await;
        }
        Some((Ok::<_, std::io::Error>(Bytes::from(bytes)), remaining))
    });
    (
        StatusCode::OK,
        [("content-type", "text/event-stream")],
        Body::from_stream(stream),
    )
        .into_response()
}

/// Chunk plan for one SSE response: the marker is deliberately split at
/// random interior points and continuation chunks are delayed, forcing the
/// terminator to straddle separate TCP reads at the keysink scanner.
fn plan_sse(seed: u64, marker: &[u8], truncate: bool, tail: bool) -> Vec<(Vec<u8>, bool)> {
    let mut rng = Lcg(seed | 1);
    let prefix: Vec<u8> = b"event: delta\ndata: {\"i\":0}\n\ndata: {\"i\":1}\n\n".to_vec();

    let mut chunks: Vec<(Vec<u8>, bool)> = Vec::new();
    if truncate {
        let mut body = prefix;
        body.extend_from_slice(&marker[..marker.len() / 2]);
        chunks.push((body, false));
        return chunks;
    }

    // prefix split into up to 3 pieces (no sleeps needed)
    let mut cuts = [rng.below(prefix.len()), rng.below(prefix.len())];
    cuts.sort_unstable();
    let mut start = 0;
    for cut in cuts {
        if cut > start {
            chunks.push((prefix[start..cut].to_vec(), false));
            start = cut;
        }
    }
    chunks.push((prefix[start..].to_vec(), false));

    // marker split at 1-2 interior points; continuation pieces are delayed so
    // they arrive as separate reads
    let mut points = vec![
        1 + rng.below(marker.len() - 2),
        1 + rng.below(marker.len() - 2),
    ];
    points.sort_unstable();
    points.dedup();
    let mut mstart = 0;
    for (i, p) in points.into_iter().enumerate() {
        chunks.push((marker[mstart..p].to_vec(), i > 0));
        mstart = p;
    }
    chunks.push((marker[mstart..].to_vec(), !chunks.is_empty()));

    if tail {
        chunks.push((b"data: {\"i\":2}\n\n".to_vec(), false));
    }
    chunks
}

fn raw_sse_body(seed: u64, marker: &[u8], truncate: bool, tail: bool) -> Vec<u8> {
    plan_sse(seed, marker, truncate, tail)
        .into_iter()
        .flat_map(|(c, _)| c)
        .collect()
}

// ---------- keysink gateway ----------

fn route_to(base: &str, terminator: Terminator, auth: Auth, enabled: bool) -> Route {
    let mut r = Route::new(
        vkey::generate(),
        base.to_string(),
        REAL_KEY.into(),
        auth,
        BTreeMap::new(),
    );
    r.sse_terminator = terminator;
    r.enabled = enabled;
    r
}

async fn spawn_gateway(
    store: Store,
    retry: RetryPolicy,
    body_limit: usize,
) -> (SocketAddr, HashMap<String, String>) {
    spawn_gateway_with_idle(store, retry, body_limit, keysink::proxy::BODY_READ_IDLE).await
}

fn build_state(
    store: Store,
    retry: RetryPolicy,
    body_limit: usize,
    body_read_idle: Duration,
    inbound_body_timeout: Duration,
    max_inbound: usize,
    permit_queue_timeout: Duration,
) -> (Arc<keysink::proxy::AppState>, HashMap<String, String>) {
    let mut vkeys = HashMap::new();
    for (name, r) in &store.routes {
        vkeys.insert(name.clone(), r.vkey.clone());
    }
    let table = keysink::vkey::RouteTable::build(&store).unwrap();
    let snapshot = keysink::proxy::Snapshot {
        store: Arc::new(store),
        table,
        from_backup: false,
    };
    let state = Arc::new(keysink::proxy::AppState {
        snapshot: arc_swap::ArcSwap::from_pointee(snapshot),
        clients: keysink::proxy::ProxyClients::new().unwrap(),
        retry,
        body_limit,
        body_read_idle,
        inbound_body_timeout,
        permit_queue_timeout,
        body_total_budget: keysink::proxy::BODY_TOTAL_BUDGET,
        forward_total_budget: keysink::proxy::FORWARD_TOTAL_BUDGET,
        reload: Arc::new(keysink::proxy::ReloadStatus::default()),
        counters: Arc::new(keysink::proxy::ServeCounters::default()),
        inbound_permits: Arc::new(tokio::sync::Semaphore::new(max_inbound)),
        audit: keysink::audit::Audit::disabled(),
        started: Instant::now(),
    });
    (state, vkeys)
}

async fn spawn_gateway_with_idle(
    store: Store,
    retry: RetryPolicy,
    body_limit: usize,
    body_read_idle: Duration,
) -> (SocketAddr, HashMap<String, String>) {
    #[cfg(unix)]
    raise_fd_limit();
    let (state, vkeys) = build_state(
        store,
        retry,
        body_limit,
        body_read_idle,
        keysink::proxy::CLIENT_BODY_TIMEOUT,
        64,
        keysink::proxy::PERMIT_QUEUE_TIMEOUT,
    );
    let app = keysink::proxy::build_app(state);
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    tokio::spawn(async move {
        axum::serve(listener, app).await.unwrap();
    });
    (addr, vkeys)
}

// ---------- e2e request fuzz ----------

#[tokio::test]
async fn proxy_end_to_end_fuzz() {
    let (mock, _hits) = spawn_mock().await;
    let mut store = Store::new();
    store.routes.insert(
        "main".into(),
        route_to(
            &format!("http://{mock}"),
            Terminator::Auto,
            Auth::Bearer,
            true,
        ),
    );
    store.routes.insert(
        "disabled".into(),
        route_to(
            &format!("http://{mock}"),
            Terminator::Auto,
            Auth::Bearer,
            false,
        ),
    );
    let (gw, vks) = spawn_gateway(store, RetryPolicy::default(), 1 << 20).await;
    let vk_main = vks["main"].clone();
    let vk_disabled = vks["disabled"].clone();

    let client = reqwest::Client::new();
    let mut rng = Lcg(0xBEEF_0001);

    let methods = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"];
    let paths: Vec<String> = vec![
        "/v1/chat/completions".into(),
        "/v1/messages".into(),
        "/seg-1".into(),
        "/a//b".into(),
        "/x%20y".into(),
        "/v1/embedded%2Fslash".into(),
        format!("/{}", "p".repeat(512)),
        "/".into(),
    ];
    let queries = ["", "a=1&b=2", "alt=sse&key=stale", "x=1%202&flag"];

    for case in 0..60 {
        let method = *rng.pick(&methods);
        let path = rng.pick(&paths).clone();
        let query = *rng.pick(&queries);
        let url_path = if query.is_empty() {
            path.clone()
        } else {
            format!("{path}?{query}")
        };
        let body: Option<Vec<u8>> = if matches!(method, "POST" | "PUT" | "PATCH" | "DELETE") {
            match rng.below(4) {
                0 => Some(b"{}".to_vec()),
                1 => Some(br#"{"stream":false,"model":"m"}"#.to_vec()),
                2 => Some((0..1024).map(|i| (i % 251) as u8).collect()),
                _ => Some(vec![0x61u8; 100_000]),
            }
        } else {
            None
        };

        // which header carries the vkey, or whether it is present at all
        let channel = rng.below(7);
        let auth_header = match channel {
            0 => Some(("authorization", format!("Bearer {vk_main}"))),
            1 => Some(("x-api-key", vk_main.clone())),
            2 => Some(("api-key", vk_main.clone())),
            3 => Some(("x-goog-api-key", vk_main.clone())),
            4 => None, // missing
            5 => Some((
                "authorization",
                "Bearer ks_fffffffffffffffffffffffffffffffffffffffffff0".into(),
            )), // unknown token
            _ => Some(("authorization", format!("Bearer {vk_disabled}"))), // disabled route
        };

        let mut req = client.request(
            reqwest::Method::from_bytes(method.as_bytes()).unwrap(),
            format!("http://{gw}{url_path}"),
        );
        if let Some((h, v)) = &auth_header {
            req = req.header(*h, v.clone());
        }
        if case % 3 == 0 {
            req = req.header("x-custom-trace", "trace-42");
        }
        if let Some(b) = &body {
            req = req.body(b.clone());
        }
        // Early rejects (401/403) answer before the request body is drained,
        // so the gateway closes that connection while body bytes may still be
        // in flight → the OS turns the close into an RST, and under load the
        // very next request can be handed the just-died pooled connection and
        // fail with a SendRequest error even though nothing was delivered.
        // No response was received, so one retry on a fresh connection is
        // faithful to the invariant under test (this used to flake ~50% under
        // parallel test load).
        let retry = req.try_clone().expect("request must be cloneable");
        let resp = match req.send().await {
            Ok(r) => r,
            Err(e) if e.status().is_none() && !e.is_timeout() => {
                retry.send().await.expect("gateway must answer")
            }
            Err(e) => panic!("gateway must answer: {e}"),
        };
        let rid = resp
            .headers()
            .get("x-keysink-request-id")
            .map(|v| v.to_str().unwrap().to_string());
        assert!(
            rid.map(|r| !r.is_empty()).unwrap_or(false),
            "case {case}: missing x-keysink-request-id"
        );

        match channel {
            4 | 5 => assert_eq!(
                resp.status(),
                401,
                "case {case}: unauthenticated must be 401"
            ),
            6 => assert_eq!(
                resp.status(),
                403,
                "case {case}: disabled route must be 403"
            ),
            _ => {
                assert_eq!(resp.status(), 200, "case {case}: proxied request failed");
                if method == "HEAD" {
                    // hyper strips the body of HEAD responses; nothing to echo
                    continue;
                }
                let echo: Echo = resp.json().await.expect("case {case}: echo must be JSON");
                assert_eq!(echo.method, method, "case {case}");
                assert_eq!(echo.path, path, "case {case}: path fidelity");
                assert_eq!(echo.query, query, "case {case}: query fidelity");
                // credential isolation: upstream sees exactly the injected
                // bearer, never the vkey or any inbound auth material
                assert_eq!(
                    echo.headers.get("authorization").map(String::as_str),
                    Some("Bearer real-upstream-key-123"),
                    "case {case}: upstream authorization must be the injected key"
                );
                assert!(
                    !echo.headers.contains_key("x-api-key"),
                    "case {case}: x-api-key must not leak upstream"
                );
                assert!(
                    !echo
                        .headers
                        .values()
                        .any(|v| v.contains(&vk_main) || v.contains(&vk_disabled)),
                    "case {case}: vkey leaked upstream"
                );
                if case % 3 == 0 {
                    assert_eq!(
                        echo.headers.get("x-custom-trace").map(String::as_str),
                        Some("trace-42"),
                        "case {case}: benign headers must pass through"
                    );
                }
                if let Some(b) = &body {
                    let got = base64::engine::general_purpose::STANDARD
                        .decode(&echo.body_b64)
                        .expect("case {case}: body_b64 must decode");
                    assert_eq!(got, *b, "case {case}: body fidelity");
                }
            }
        }
    }
}

// ---------- targeted error paths ----------

#[tokio::test]
async fn rejects_oversized_bodies_both_framings() {
    let (mock, _hits) = spawn_mock().await;
    let mut store = Store::new();
    store.routes.insert(
        "main".into(),
        route_to(
            &format!("http://{mock}"),
            Terminator::Auto,
            Auth::Bearer,
            true,
        ),
    );
    let (gw, vks) = spawn_gateway(store, RetryPolicy::default(), 1024).await;
    let vk = &vks["main"];
    let client = reqwest::Client::new();

    // content-length framing: rejected by the early header check
    let resp = client
        .post(format!("http://{gw}/v1/x"))
        .header("authorization", format!("Bearer {vk}"))
        .body(vec![0x61; 4096])
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 413);
    let v: serde_json::Value = resp.json().await.unwrap();
    assert_eq!(v["error"]["type"], "request_too_large");

    // chunked framing (no content-length): rejected by the bounded read
    let stream = futures_util::stream::iter(vec![
        Ok::<_, std::io::Error>(Bytes::from(vec![0x62; 800])),
        Ok(Bytes::from(vec![0x63; 800])),
    ]);
    let resp = client
        .post(format!("http://{gw}/v1/x"))
        .header("authorization", format!("Bearer {vk}"))
        .body(reqwest::Body::wrap_stream(stream))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 413);
}

#[tokio::test]
async fn rejects_websocket_upgrade_before_auth() {
    let (mock, _hits) = spawn_mock().await;
    let mut store = Store::new();
    store.routes.insert(
        "main".into(),
        route_to(
            &format!("http://{mock}"),
            Terminator::Auto,
            Auth::Bearer,
            true,
        ),
    );
    let (gw, _vks) = spawn_gateway(store, RetryPolicy::default(), 1 << 20).await;
    let client = reqwest::Client::new();
    let resp = client
        .get(format!("http://{gw}/v1/x"))
        .header("connection", "Upgrade")
        .header("upgrade", "websocket")
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 501);
    let v: serde_json::Value = resp.json().await.unwrap();
    assert_eq!(v["error"]["type"], "unsupported");
}

#[tokio::test]
async fn upstream_failures_map_to_clean_errors() {
    // unreachable host → 502 upstream_error (POST: connect errors are
    // replay-safe but max_retries=0 keeps the test fast)
    let mut store = Store::new();
    store.routes.insert(
        "dead".into(),
        route_to("http://127.0.0.1:1", Terminator::Auto, Auth::Bearer, true),
    );
    let policy = RetryPolicy {
        max_retries: 0,
        ..RetryPolicy::default()
    };
    let (gw, vks) = spawn_gateway(store, policy, 1 << 20).await;
    let client = reqwest::Client::new();
    let resp = client
        .post(format!("http://{gw}/v1/x"))
        .header("authorization", format!("Bearer {}", vks["dead"]))
        .body(b"{}".to_vec())
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 502);
    let v: serde_json::Value = resp.json().await.unwrap();
    assert_eq!(v["error"]["type"], "upstream_error");

    // hanging upstream → 504 once the header timeout fires
    let (mock, _hits) = spawn_mock().await;
    let mut store = Store::new();
    store.routes.insert(
        "slow".into(),
        route_to(
            &format!("http://{mock}"),
            Terminator::Auto,
            Auth::Bearer,
            true,
        ),
    );
    let policy = RetryPolicy {
        max_retries: 0,
        header_timeout: Duration::from_millis(400),
        ..RetryPolicy::default()
    };
    let (gw, vks) = spawn_gateway(store, policy, 1 << 20).await;
    let started = Instant::now();
    let resp = client
        .post(format!("http://{gw}/hang"))
        .header("authorization", format!("Bearer {}", vks["slow"]))
        .body(b"{}".to_vec())
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 504);
    let v: serde_json::Value = resp.json().await.unwrap();
    assert_eq!(v["error"]["type"], "upstream_timeout");
    assert!(
        started.elapsed() < Duration::from_secs(5),
        "timeout must fire promptly"
    );
}

#[tokio::test]
async fn stalled_non_streaming_body_aborts_instead_of_hanging() {
    // Regression: an upstream that sent response headers and then went
    // silent mid-body used to hang the handler forever on the non-streaming
    // path (the plain client has no client-level read idle) — and a hung
    // handler also stalled graceful shutdown.
    let (mock, _hits) = spawn_mock().await;
    let mut store = Store::new();
    store.routes.insert(
        "main".into(),
        route_to(
            &format!("http://{mock}"),
            Terminator::Auto,
            Auth::Bearer,
            true,
        ),
    );
    let (gw, vks) = spawn_gateway_with_idle(
        store,
        RetryPolicy::default(),
        1 << 20,
        Duration::from_millis(300),
    )
    .await;
    let client = reqwest::Client::new();

    let started = Instant::now();
    let resp = client
        .post(format!("http://{gw}/stall-body"))
        .header("authorization", format!("Bearer {}", vks["main"]))
        .body(b"{}".to_vec())
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200, "response headers must still arrive");
    let body = resp.bytes().await;
    assert!(
        body.is_err(),
        "stalled body must be aborted, not delivered: {body:?}"
    );
    assert!(
        started.elapsed() < Duration::from_secs(10),
        "abort must be prompt, took {:?}",
        started.elapsed()
    );
}

#[tokio::test]
async fn retryable_status_with_stalled_body_does_not_wedge_the_handler() {
    // Regression: the retry path discards a retryable response's body to give
    // the connection back, and that drain had no bound. The non-streaming
    // client carries no client-level read timeout, so an upstream that
    // answered 429 and then stalled the body parked the handler forever —
    // with its inbound permit. `max_concurrent` such responses turned the
    // whole gateway into 503s for everyone else.
    let (mock, _hits) = spawn_mock().await;
    let mut store = Store::new();
    store.routes.insert(
        "main".into(),
        route_to(
            &format!("http://{mock}"),
            Terminator::Auto,
            Auth::Bearer,
            true,
        ),
    );
    let policy = RetryPolicy {
        max_retries: 2,
        statuses: vec![429].into(),
        initial_backoff: Duration::from_millis(10),
        max_backoff: Duration::from_millis(30),
        header_timeout: Duration::from_secs(5),
    };
    let (gw, vks) =
        spawn_gateway_with_idle(store, policy, 1 << 20, Duration::from_millis(300)).await;
    let client = reqwest::Client::new();

    let started = Instant::now();
    let resp = tokio::time::timeout(
        Duration::from_secs(5),
        client
            .post(format!("http://{gw}/stall-body-429"))
            .header("authorization", format!("Bearer {}", vks["main"]))
            .body(b"{}".to_vec())
            .send(),
    )
    .await
    .expect("the retry-discard path must be bounded, not hang the handler")
    .unwrap();
    assert_eq!(resp.status(), 429, "the last attempt's status is returned");
    assert!(
        started.elapsed() < Duration::from_secs(5),
        "discard must give up at the read idle, took {:?}",
        started.elapsed()
    );
}

#[tokio::test]
async fn total_forward_budget_bounds_a_retry_storm() {
    // Regression: per-attempt header_timeout alone let a route with
    // max_retries = 10 hold an inbound permit for ~20 minutes. The
    // whole-forward budget must end the retry storm instead, and the last
    // response seen is returned to the client.
    let (mock, hits) = spawn_mock().await;
    let mut store = Store::new();
    store.routes.insert(
        "main".into(),
        route_to(
            &format!("http://{mock}"),
            Terminator::Auto,
            Auth::Bearer,
            true,
        ),
    );
    let policy = RetryPolicy {
        max_retries: 10,
        statuses: vec![503].into(),
        // Each attempt burns its full header timeout against /hang: the
        // whole-forward budget is what has to stop the ladder.
        initial_backoff: Duration::from_millis(10),
        max_backoff: Duration::from_millis(20),
        header_timeout: Duration::from_millis(50),
    };
    let (mut state, vks) = build_state(
        store,
        policy,
        1 << 20,
        keysink::proxy::BODY_READ_IDLE,
        keysink::proxy::CLIENT_BODY_TIMEOUT,
        64,
        keysink::proxy::PERMIT_QUEUE_TIMEOUT,
    );
    Arc::get_mut(&mut state)
        .expect("the test holds the only Arc to the state")
        .forward_total_budget = Duration::from_millis(200);
    let app = keysink::proxy::build_app(state);
    #[cfg(unix)]
    raise_fd_limit();
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let server = tokio::spawn(keysink::proxy::serve_inbound(
        listener,
        app,
        keysink::proxy::InboundLimits {
            header_timeout: Duration::from_secs(30),
            max_connections: 8,
            drain_timeout: Some(Duration::from_secs(5)),
            loop_iterations: None,
            live_connections: None,
            counters: None,
        },
        std::future::pending(),
    ));

    let started = Instant::now();
    let resp = tokio::time::timeout(
        Duration::from_secs(5),
        // GET so the header timeout is replayable: this exercises the retry
        // ladder rather than the POST-replay guard.
        reqwest::Client::new()
            .get(format!("http://{addr}/hang"))
            .header("authorization", format!("Bearer {}", vks["main"]))
            .send(),
    )
    .await
    .expect("the forward budget must end the retry storm")
    .unwrap();
    assert_eq!(resp.status(), 504, "the budget ends as an upstream timeout");
    assert!(
        started.elapsed() < Duration::from_secs(3),
        "the request must stop near the 200ms budget, took {:?}",
        started.elapsed()
    );
    assert!(
        hits.load(Ordering::Relaxed) < 11,
        "the budget must cut the retries short, saw {} attempts",
        hits.load(Ordering::Relaxed)
    );

    server.abort();
}

#[tokio::test]
async fn sse_stream_without_terminator_scan_has_no_total_budget() {
    // Regression: `Terminator::None` routes pass SSE through raw (no scan),
    // and that passthrough used to inherit the whole-body budget — a stream
    // that legitimately outlives it (a long agent session) was cut off
    // mid-stream. Content-type says SSE ⇒ only the per-chunk read idle
    // applies. The production budget is 10 minutes, so the test injects a
    // tiny one via a hand-built state and races the stream against the
    // budget: the stream (paced well inside the idle bound, but far longer
    // than the injected budget) must complete instead of ending in a
    // TimedOut abort.
    let (mock, _hits) = spawn_mock().await;
    let mut store = Store::new();
    store.routes.insert(
        "main".into(),
        route_to(
            &format!("http://{mock}"),
            Terminator::None,
            Auth::Bearer,
            true,
        ),
    );
    let tiny_budget = Duration::from_millis(500);
    let (mut state, vks) = build_state(
        store,
        RetryPolicy::default(),
        1 << 20,
        // idle bound far above the chunk pacing; the budget is what would
        // trip first if SSE inherited it
        Duration::from_secs(30),
        keysink::proxy::CLIENT_BODY_TIMEOUT,
        64,
        keysink::proxy::PERMIT_QUEUE_TIMEOUT,
    );
    // The SSE passthrough must ignore the budget entirely: hand the state a
    // budget far shorter than the stream and expect the stream to win.
    Arc::get_mut(&mut state)
        .expect("the test holds the only Arc to the state")
        .body_total_budget = tiny_budget;
    let app = keysink::proxy::build_app(state);
    #[cfg(unix)]
    raise_fd_limit();
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let server = tokio::spawn(keysink::proxy::serve_inbound(
        listener,
        app,
        keysink::proxy::InboundLimits {
            header_timeout: Duration::from_secs(30),
            max_connections: 64,
            drain_timeout: Some(Duration::from_secs(5)),
            loop_iterations: None,
            live_connections: None,
            counters: None,
        },
        std::future::pending(),
    ));

    let client = reqwest::Client::new();
    // 30 chunks × 100ms = a 3s stream: 6× past the injected 500ms budget,
    // every chunk inside the 30s idle bound. If SSE inherited the budget,
    // the body would abort with TimedOut ~0.5s in.
    let resp = client
        .post(format!("http://{addr}/trickle-sse?n=30&pace_ms=100"))
        .header("authorization", format!("Bearer {}", vks["main"]))
        .body(br#"{"stream":true,"model":"m"}"#.to_vec())
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    let body = resp
        .bytes()
        .await
        .expect("an SSE stream must not be aborted by the whole-body budget");
    let mut expected = String::new();
    for i in 0..30 {
        expected.push_str(&format!("data: {{\"i\":{i}}}\n\n"));
    }
    assert_eq!(body, expected.as_bytes());
    server.abort();
}

#[tokio::test]
async fn retry_policy_replays_and_returns_final_status() {
    let (mock, hits) = spawn_mock().await;
    let mut store = Store::new();
    store.routes.insert(
        "main".into(),
        route_to(
            &format!("http://{mock}"),
            Terminator::Auto,
            Auth::Bearer,
            true,
        ),
    );
    let policy = RetryPolicy {
        max_retries: 2,
        statuses: vec![503].into(),
        initial_backoff: Duration::from_millis(10),
        max_backoff: Duration::from_millis(30),
        header_timeout: Duration::from_secs(5),
    };
    let (gw, vks) = spawn_gateway(store, policy, 1 << 20).await;
    let client = reqwest::Client::new();
    let resp = client
        .post(format!("http://{gw}/status/503"))
        .header("authorization", format!("Bearer {}", vks["main"]))
        .body(b"{}".to_vec())
        .send()
        .await
        .unwrap();
    // status-based retries are not method-gated by design: a 503 means the
    // upstream refused the request before processing it
    assert_eq!(resp.status(), 503);
    assert_eq!(
        hits.load(Ordering::Relaxed),
        3,
        "POST + 503 must be retried twice"
    );
}

#[tokio::test]
async fn broken_static_header_maps_to_configuration_error() {
    let (mock, _hits) = spawn_mock().await;
    let mut store = Store::new();
    let mut r = route_to(
        &format!("http://{mock}"),
        Terminator::Auto,
        Auth::Bearer,
        true,
    );
    r.headers.insert("x-trace".into(), "bad\nvalue".into());
    store.routes.insert("broken".into(), r);
    let (gw, vks) = spawn_gateway(store, RetryPolicy::default(), 1 << 20).await;
    let client = reqwest::Client::new();
    let resp = client
        .post(format!("http://{gw}/v1/x"))
        .header("authorization", format!("Bearer {}", vks["broken"]))
        .body(b"{}".to_vec())
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 500);
    let v: serde_json::Value = resp.json().await.unwrap();
    assert_eq!(v["error"]["type"], "configuration_error");
}

#[tokio::test]
async fn query_auth_replaces_inbound_param() {
    let (mock, _hits) = spawn_mock().await;
    let mut store = Store::new();
    store.routes.insert(
        "q".into(),
        route_to(
            &format!("http://{mock}"),
            Terminator::Auto,
            Auth::Query {
                param: "key".into(),
            },
            true,
        ),
    );
    let (gw, vks) = spawn_gateway(store, RetryPolicy::default(), 1 << 20).await;
    let client = reqwest::Client::new();
    let resp = client
        .post(format!("http://{gw}/v1/x?key=stale&alt=sse"))
        .header("authorization", format!("Bearer {}", vks["q"]))
        .body(b"{}".to_vec())
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    let echo: Echo = resp.json().await.unwrap();
    assert_eq!(echo.query, "alt=sse&key=real-upstream-key-123");
    assert!(
        !echo.headers.contains_key("authorization"),
        "query auth must not inject a header credential"
    );
}

#[tokio::test]
async fn deeply_nested_body_survives_the_full_proxy_path() {
    // Stack-overflow audit PoC, kept as a regression: an attacker-controlled
    // request body can be arbitrarily deep JSON. serde_json's ignored-field
    // skipper is iterative, so the real axum → handler → reqwest path must
    // survive it — this drives the full stack, not just the parser.
    let (mock, _hits) = spawn_mock().await;
    let mut store = Store::new();
    store.routes.insert(
        "main".into(),
        route_to(
            &format!("http://{mock}"),
            Terminator::Auto,
            Auth::Bearer,
            true,
        ),
    );
    let (gw, vks) = spawn_gateway(store, RetryPolicy::default(), 1 << 20).await;
    let client = reqwest::Client::new();

    let depth = 100_000usize;
    let deep = format!("{}{}", "[".repeat(depth), "]".repeat(depth));
    let body = format!(r#"{{"pad":{deep},"stream":false}}"#).into_bytes();
    assert!(body.len() < 1 << 20, "PoC body must fit the 1MB test limit");

    let resp = client
        .post(format!("http://{gw}/v1/x"))
        .header("authorization", format!("Bearer {}", vks["main"]))
        .body(body)
        .send()
        .await
        .expect("gateway must survive a deeply nested body");
    assert_eq!(resp.status(), 200);
    let echo: Echo = resp.json().await.unwrap();
    assert_eq!(echo.path, "/v1/x");
}

// ---------- inbound read bounds (serve_inbound) ----------

#[tokio::test]
async fn serve_inbound_reaps_stalled_request_head() {
    // slowloris defense: a client that opens a connection and stalls mid-head
    // must be disconnected within the header bound — while healthy requests
    // on other connections keep working.
    let (mock, _hits) = spawn_mock().await;
    let mut store = Store::new();
    store.routes.insert(
        "main".into(),
        route_to(
            &format!("http://{mock}"),
            Terminator::Auto,
            Auth::Bearer,
            true,
        ),
    );
    let (state, _vks) = build_state(
        store,
        RetryPolicy::default(),
        1 << 20,
        keysink::proxy::BODY_READ_IDLE,
        keysink::proxy::CLIENT_BODY_TIMEOUT,
        64,
        keysink::proxy::PERMIT_QUEUE_TIMEOUT,
    );
    let app = keysink::proxy::build_app(state);
    #[cfg(unix)]
    raise_fd_limit();
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let server = tokio::spawn(keysink::proxy::serve_inbound(
        listener,
        app,
        keysink::proxy::InboundLimits {
            header_timeout: Duration::from_millis(300),
            max_connections: 16,
            drain_timeout: Some(Duration::from_secs(5)),
            loop_iterations: None,
            live_connections: None,
            counters: None,
        },
        std::future::pending(),
    ));

    // healthy requests on other connections are unaffected
    let client = reqwest::Client::new();
    let resp = client
        .get(format!("http://{addr}/__keysink/health"))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);

    // stalled head: hyper closes the connection within the bound
    use tokio::io::AsyncReadExt;
    use tokio::io::AsyncWriteExt;
    let mut sock = tokio::net::TcpStream::connect(addr).await.unwrap();
    sock.write_all(b"GET /__keysink/health HTTP/1.1\r\nHost: gw\r\n")
        .await
        .unwrap(); // head deliberately not terminated (no final CRLF)
    let started = Instant::now();
    let mut buf = [0u8; 64];
    loop {
        let n = tokio::time::timeout(Duration::from_secs(5), sock.read(&mut buf))
            .await
            .expect("connection must close within the header bound")
            .unwrap_or(0);
        if n == 0 {
            break; // EOF or reset: the server reaped the stalled connection
        }
    }
    assert!(
        started.elapsed() < Duration::from_secs(5),
        "reap must be prompt, took {:?}",
        started.elapsed()
    );
    server.abort();
}

#[tokio::test]
async fn serve_inbound_sheds_connections_beyond_the_cap() {
    // --allow-remote hardening: connections beyond the cap are closed on
    // accept instead of accumulating tasks and fds. A held idle connection
    // occupies its slot; the next one is shed; after it closes, the slot
    // frees and new connections are served again.
    let (mock, _hits) = spawn_mock().await;
    let mut store = Store::new();
    store.routes.insert(
        "main".into(),
        route_to(
            &format!("http://{mock}"),
            Terminator::Auto,
            Auth::Bearer,
            true,
        ),
    );
    let (state, _vks) = build_state(
        store,
        RetryPolicy::default(),
        1 << 20,
        keysink::proxy::BODY_READ_IDLE,
        keysink::proxy::CLIENT_BODY_TIMEOUT,
        64,
        keysink::proxy::PERMIT_QUEUE_TIMEOUT,
    );
    let app = keysink::proxy::build_app(state);
    #[cfg(unix)]
    raise_fd_limit();
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let server = tokio::spawn(keysink::proxy::serve_inbound(
        listener,
        app,
        keysink::proxy::InboundLimits {
            header_timeout: Duration::from_secs(30),
            max_connections: 1,
            drain_timeout: Some(Duration::from_secs(5)),
            loop_iterations: None,
            live_connections: None,
            counters: None,
        },
        std::future::pending(),
    ));

    use tokio::io::AsyncReadExt;
    // Slot holder: an open connection parked before sending anything.
    let mut holder = tokio::net::TcpStream::connect(addr).await.unwrap();
    // Next connection is shed (closed promptly, no response).
    let mut shed = tokio::net::TcpStream::connect(addr).await.unwrap();
    let mut buf = [0u8; 16];
    let closed = tokio::time::timeout(Duration::from_secs(3), shed.read(&mut buf)).await;
    assert!(
        matches!(closed, Ok(Ok(0)) | Ok(Err(_))),
        "connection beyond the cap must be closed promptly, got {closed:?}"
    );
    // The slot holder is untouched and can still complete a request over its
    // own socket (reqwest would open a new connection, which is shed).
    let req = b"GET /__keysink/health HTTP/1.1\r\nHost: gw\r\nConnection: close\r\n\r\n";
    use tokio::io::AsyncWriteExt;
    holder.write_all(req).await.unwrap();
    let mut response = Vec::new();
    loop {
        let n = tokio::time::timeout(Duration::from_secs(3), holder.read(&mut buf))
            .await
            .expect("holder connection must stay usable")
            .unwrap();
        if n == 0 {
            break;
        }
        response.extend_from_slice(&buf[..n]);
    }
    let text = String::from_utf8_lossy(&response);
    assert!(
        text.starts_with("HTTP/1.1 200"),
        "slot holder must still be served, got: {text}"
    );
    server.abort();
}

#[tokio::test]
async fn inbound_body_trickle_times_out() {
    // A client that sends the head and then trickles the body forever must
    // get a 408 instead of holding the handler — the byte limit alone does
    // not provide this bound.
    let (mock, _hits) = spawn_mock().await;
    let mut store = Store::new();
    store.routes.insert(
        "main".into(),
        route_to(
            &format!("http://{mock}"),
            Terminator::Auto,
            Auth::Bearer,
            true,
        ),
    );
    let (state, vks) = build_state(
        store,
        RetryPolicy::default(),
        1 << 20,
        keysink::proxy::BODY_READ_IDLE,
        Duration::from_millis(300),
        64,
        keysink::proxy::PERMIT_QUEUE_TIMEOUT,
    );
    let app = keysink::proxy::build_app(state);
    #[cfg(unix)]
    raise_fd_limit();
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    tokio::spawn(async move {
        axum::serve(listener, app).await.unwrap();
    });

    use tokio::io::AsyncReadExt;
    use tokio::io::AsyncWriteExt;
    let mut sock = tokio::net::TcpStream::connect(addr).await.unwrap();
    let head = format!(
        "POST /v1/x HTTP/1.1\r\nHost: gw\r\nAuthorization: Bearer {}\r\nContent-Type: application/json\r\nContent-Length: 1000000\r\n\r\n{{",
        vks["main"]
    );
    sock.write_all(head.as_bytes()).await.unwrap();

    let started = Instant::now();
    let mut buf = Vec::new();
    loop {
        let mut chunk = [0u8; 512];
        let n = tokio::time::timeout(Duration::from_secs(5), sock.read(&mut chunk))
            .await
            .expect("response must arrive within the body bound")
            .unwrap();
        if n == 0 {
            break; // server closed the connection after the 408
        }
        buf.extend_from_slice(&chunk[..n]);
    }
    let text = String::from_utf8_lossy(&buf);
    assert!(text.starts_with("HTTP/1.1 408"), "got: {text}");
    assert!(text.contains("request_timeout"), "got: {text}");
    assert!(
        started.elapsed() < Duration::from_secs(5),
        "timeout must fire promptly, took {:?}",
        started.elapsed()
    );
}

#[tokio::test]
async fn serve_inbound_passes_sse_streams() {
    // serve_inbound is the production serve loop: an SSE request must stream
    // through it byte-for-byte, terminator detection included.
    let (mock, _hits) = spawn_mock().await;
    let mut store = Store::new();
    store.routes.insert(
        "openai".into(),
        route_to(
            &format!("http://{mock}"),
            Terminator::Openai,
            Auth::Bearer,
            true,
        ),
    );
    let (state, vks) = build_state(
        store,
        RetryPolicy::default(),
        1 << 20,
        keysink::proxy::BODY_READ_IDLE,
        keysink::proxy::CLIENT_BODY_TIMEOUT,
        64,
        keysink::proxy::PERMIT_QUEUE_TIMEOUT,
    );
    let app = keysink::proxy::build_app(state);
    #[cfg(unix)]
    raise_fd_limit();
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let server = tokio::spawn(keysink::proxy::serve_inbound(
        listener,
        app,
        keysink::proxy::InboundLimits {
            header_timeout: Duration::from_secs(30),
            max_connections: 64,
            drain_timeout: Some(Duration::from_secs(5)),
            loop_iterations: None,
            live_connections: None,
            counters: None,
        },
        std::future::pending(),
    ));

    let client = reqwest::Client::new();
    let resp = client
        .post(format!(
            "http://{addr}/sse?marker=openai&seed=1&truncate=0&tail=1"
        ))
        .header("authorization", format!("Bearer {}", vks["openai"]))
        .body(br#"{"stream":true,"model":"m"}"#.to_vec())
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    let got = resp.bytes().await.unwrap();
    let raw = raw_sse_body(1, b"data: [DONE]\n\n", false, true);
    assert_eq!(
        got.as_ref(),
        raw.as_slice(),
        "SSE bytes must pass through serve_inbound untouched"
    );
    server.abort();
}

#[tokio::test]
async fn concurrent_requests_bounded_by_inbound_permits() {
    // The permit spans body read + upstream response-header wait: a second
    // request must queue while the first is still waiting for its upstream,
    // and proceed as soon as the permit is released. (SSE body streaming
    // happens after the handler returns, so streams never hold a permit.)
    let gate = Arc::new(tokio::sync::Notify::new());
    let gate_for_mock = gate.clone();
    #[cfg(unix)]
    raise_fd_limit();
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let mock = listener.local_addr().unwrap();
    tokio::spawn(async move {
        let app: Router = Router::new().fallback(move |req: axum::extract::Request<Body>| {
            let gate = gate_for_mock.clone();
            async move {
                if req.uri().path() == "/gate" {
                    gate.notified().await;
                }
                (StatusCode::OK, "ok").into_response()
            }
        });
        axum::serve(listener, app).await.unwrap();
    });

    let mut store = Store::new();
    store.routes.insert(
        "main".into(),
        route_to(
            &format!("http://{mock}"),
            Terminator::Auto,
            Auth::Bearer,
            true,
        ),
    );
    let (state, vks) = build_state(
        store,
        RetryPolicy {
            max_retries: 0,
            ..RetryPolicy::default()
        },
        1 << 20,
        keysink::proxy::BODY_READ_IDLE,
        keysink::proxy::CLIENT_BODY_TIMEOUT,
        1,
        keysink::proxy::PERMIT_QUEUE_TIMEOUT,
    );
    let app = keysink::proxy::build_app(state);
    #[cfg(unix)]
    raise_fd_limit();
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let gw = listener.local_addr().unwrap();
    tokio::spawn(async move {
        axum::serve(listener, app).await.unwrap();
    });

    let client = reqwest::Client::new();
    let vk = vks["main"].clone();

    // A takes the only permit and parks on the gated upstream.
    let a = {
        let client = client.clone();
        let vk = vk.clone();
        tokio::spawn(async move {
            client
                .post(format!("http://{gw}/gate"))
                .header("authorization", format!("Bearer {vk}"))
                .body(b"{}".to_vec())
                .send()
                .await
                .unwrap()
                .status()
        })
    };
    tokio::time::sleep(Duration::from_millis(300)).await;

    // B must still be queued while A holds the permit.
    let b = {
        let client = client.clone();
        let vk = vk.clone();
        tokio::spawn(async move {
            client
                .post(format!("http://{gw}/echo"))
                .header("authorization", format!("Bearer {vk}"))
                .body(b"{}".to_vec())
                .send()
                .await
                .unwrap()
                .status()
        })
    };
    tokio::time::sleep(Duration::from_millis(200)).await;
    assert!(!b.is_finished(), "B must queue while A holds the permit");

    gate.notify_one();
    assert_eq!(a.await.unwrap(), 200);
    let b_status = tokio::time::timeout(Duration::from_secs(5), b)
        .await
        .expect("B must proceed once the permit frees")
        .unwrap();
    assert_eq!(b_status, 200);
}

#[tokio::test]
async fn health_endpoint_reports_route_count() {
    let (mock, _hits) = spawn_mock().await;
    let mut store = Store::new();
    for i in 0..3 {
        store.routes.insert(
            format!("r{i}"),
            route_to(
                &format!("http://{mock}"),
                Terminator::Auto,
                Auth::Bearer,
                true,
            ),
        );
    }
    let (gw, _vks) = spawn_gateway(store, RetryPolicy::default(), 1 << 20).await;
    let client = reqwest::Client::new();
    let resp = client
        .get(format!("http://{gw}/__keysink/health"))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    let v: serde_json::Value = resp.json().await.unwrap();
    assert_eq!(v["ok"], true);
    assert_eq!(v["routes"], 3);
    assert_eq!(v["degraded"], false);
}

// ---------- SSE marker-split fuzz ----------

#[tokio::test]
async fn sse_split_and_truncation_fuzz() {
    let (mock, _hits) = spawn_mock().await;
    let mut store = Store::new();
    for name in ["openai", "anth-ev", "anth-json", "auto", "none"] {
        let terminator = match name {
            "openai" => Terminator::Openai,
            "anth-ev" | "anth-json" => Terminator::Anthropic,
            "auto" => Terminator::Auto,
            _ => Terminator::None,
        };
        store.routes.insert(
            name.into(),
            route_to(&format!("http://{mock}"), terminator, Auth::Bearer, true),
        );
    }
    let (gw, vks) = spawn_gateway(store, RetryPolicy::default(), 1 << 20).await;
    let client = reqwest::Client::new();

    let markers: &[(&str, &[u8])] = &[
        ("openai", b"data: [DONE]\n\n"),
        ("anth_ev", b"event: message_stop\n\n"),
        ("anth_json", b"data: {\"type\":\"message_stop\"}\n\n"),
    ];

    for (kind, marker) in markers {
        let matching_route = if *kind == "openai" {
            "openai"
        } else {
            "anth-ev"
        };
        for term_route in [matching_route, "auto", "none"] {
            for truncate in [false, true] {
                for seed in 0..3u64 {
                    let url = format!(
                        "http://{gw}/sse?marker={kind}&seed={seed}&truncate={}&tail=1",
                        u8::from(truncate)
                    );
                    let resp = client
                        .post(url)
                        .header("authorization", format!("Bearer {}", vks[term_route]))
                        .body(br#"{"stream":true,"model":"m"}"#.to_vec())
                        .send()
                        .await
                        .unwrap();
                    assert_eq!(resp.status(), 200);
                    let got = resp.bytes().await.unwrap();
                    let raw = raw_sse_body(seed, marker, truncate, true);
                    let label = format!("{kind}/{term_route}/truncate={truncate}/seed={seed}");

                    match (term_route, truncate) {
                        ("none", _) | (_, false) => {
                            // terminator disabled, or terminator seen: bytes
                            // must pass through untouched
                            assert_eq!(got.as_ref(), raw.as_slice(), "case {label}");
                        }
                        (_, true) => {
                            // truncated without terminator: the injected error
                            // tail must appear exactly once, after the raw bytes
                            assert!(
                                got.starts_with(&raw),
                                "case {label}: injected tail must follow the raw prefix"
                            );
                            assert!(got.len() > raw.len(), "case {label}: tail missing");
                            let tail_text = String::from_utf8_lossy(&got[raw.len()..]);
                            let anthropic_shape =
                                term_route == "anth-ev" || term_route == "anth-json";
                            if !anthropic_shape {
                                assert!(
                                    tail_text.ends_with("data: [DONE]\n\n")
                                        && tail_text.contains("upstream_stream_error"),
                                    "case {label}: openai tail shape wrong: {tail_text:?}"
                                );
                            } else {
                                assert!(
                                    tail_text.contains("event: error")
                                        && tail_text.contains("api_error")
                                        && !tail_text.contains("message_stop"),
                                    "case {label}: anthropic tail shape wrong: {tail_text:?}"
                                );
                            }
                        }
                    }
                }
            }
        }
    }

    // non-streaming requests must never get an injected tail, even when the
    // upstream stream is cut short
    let resp = client
        .post(format!(
            "http://{gw}/sse?marker=openai&seed=7&truncate=1&tail=1"
        ))
        .header("authorization", format!("Bearer {}", vks["openai"]))
        .body(b"{}".to_vec())
        .send()
        .await
        .unwrap();
    let got = resp.bytes().await.unwrap();
    let raw = raw_sse_body(7, b"data: [DONE]\n\n", true, true);
    assert_eq!(
        got.as_ref(),
        raw.as_slice(),
        "non-stream requests pass through untouched"
    );
}

// ---------- performance scenarios ----------

fn timed(name: &str, budget: Duration, elapsed: Duration) {
    println!("perf/{name}: {elapsed:?} (budget {budget:?})");
    assert!(
        elapsed <= budget,
        "{name} exceeded budget: {elapsed:?} > {budget:?}"
    );
}

#[test]
fn perf_route_table_10k() {
    let mut store = Store::new();
    for i in 0..10_000 {
        store.routes.insert(
            format!("route-{i}"),
            Route::new(
                vkey::generate(),
                "https://up.invalid".into(),
                "k".into(),
                Auth::Bearer,
                BTreeMap::new(),
            ),
        );
    }
    let t0 = Instant::now();
    let table = keysink::vkey::RouteTable::build(&store).unwrap();
    timed("build_10k_routes", Duration::from_secs(5), t0.elapsed());

    let hashes: Vec<[u8; 32]> = store
        .routes
        .values()
        .take(2_000)
        .map(|r| vkey::hash(&r.vkey))
        .collect();
    let t1 = Instant::now();
    for _ in 0..100 {
        for h in &hashes {
            assert!(table.lookup_hash(h).is_some());
        }
    }
    timed("lookup_200k_hits", Duration::from_secs(3), t1.elapsed());
}

#[test]
fn perf_audit_flood_never_blocks() {
    let dir = tempfile::tempdir().unwrap();
    let audit = keysink::audit::Audit::new(dir.path().join("audit.jsonl"));
    let t0 = Instant::now();
    for i in 0..5_000 {
        let mut entry = keysink::audit::AuditEntry::new(
            format!("rid{i}"),
            "route",
            "fp",
            "POST",
            format!("/v1/entry-{i}/emoji-🦀"),
            128,
            i % 2 == 0,
        );
        entry.status = 200;
        audit.record(entry);
    }
    audit.close();
    timed("audit_5k_records", Duration::from_secs(10), t0.elapsed());

    let text = std::fs::read_to_string(dir.path().join("audit.jsonl")).unwrap();
    let lines: Vec<&str> = text.lines().collect();
    assert!(
        !lines.is_empty() && lines.len() <= 5_000,
        "queue drops are allowed but lines must be valid"
    );
    for l in lines {
        let v: serde_json::Value = serde_json::from_str(l)
            .unwrap_or_else(|e| panic!("audit line is not valid JSON: {e}: {l}"));
        assert!(v["path"].as_str().unwrap().contains("entry-"));
    }
}

#[tokio::test]
async fn perf_concurrent_e2e_throughput() {
    let (mock, _hits) = spawn_mock().await;
    let mut store = Store::new();
    store.routes.insert(
        "main".into(),
        route_to(
            &format!("http://{mock}"),
            Terminator::Auto,
            Auth::Bearer,
            true,
        ),
    );
    let (gw, vks) = spawn_gateway(store, RetryPolicy::default(), 1 << 20).await;
    let client = reqwest::Client::new();
    let vk = vks["main"].clone();

    let t0 = Instant::now();
    // Each in-flight request pins ~4 fds inside this one process (the test
    // client's socket, the gateway's accepted socket, the gateway→upstream
    // socket, and the upstream's accepted socket), so 100 at once needs ~400 —
    // past macOS's default 256 soft RLIMIT_NOFILE. The OS then hands the
    // gateway EMFILE, surfacing as 502s (upstream connect refused) or
    // IncompleteMessage on the client: a limit of the test harness, not of the
    // gateway (systemd installs are capped at LimitNOFILE=16384). Two waves of
    // 50 keep the peak under 200 fds — safe on any default limit. The pooled-
    // connection retry below stays: a connection can still die between
    // checkout and send, and POSTs are not retried by the client; no response
    // was received, so one retry is faithful to the throughput invariant.
    for wave in 0..2 {
        let client = client.clone();
        let vk = vk.clone();
        let futs = (0..50).map(move |i| {
            let client = client.clone();
            let vk = vk.clone();
            async move {
                let req = client
                    .post(format!("http://{gw}/v1/concurrent-{}", wave * 50 + i))
                    .header("authorization", format!("Bearer {vk}"))
                    .body(b"{\"stream\":false}".to_vec());
                let retry = req.try_clone().expect("request must be cloneable");
                let resp = match req.send().await {
                    Ok(r) => r,
                    Err(e) if e.status().is_none() && !e.is_timeout() => {
                        retry.send().await.expect("gateway must answer")
                    }
                    Err(e) => panic!("gateway must answer: {e}"),
                };
                assert_eq!(resp.status(), 200);
                let echo: Echo = resp.json().await.unwrap();
                assert_eq!(echo.path, format!("/v1/concurrent-{}", wave * 50 + i));
            }
        });
        join_all(futs).await;
    }
    timed(
        "concurrent_100_requests_2_waves_of_50",
        Duration::from_secs(30),
        t0.elapsed(),
    );
}

// ---------- admission control ----------

/// Head screening (missing/unknown vkey, disabled route, oversized declared
/// body) must reject BEFORE queueing for a permit: with the permit first, a
/// credential-less flood could pin every permit and turn its cheap 401/403
/// rejects into queue hangs. Zero permits + a short queue bound makes any
/// permit-dependent path answer 503, so fast non-503 answers prove the
/// screening happens pre-permit.
#[tokio::test]
async fn head_screening_rejects_before_permit() {
    let (mock, _hits) = spawn_mock().await;
    let mut store = Store::new();
    store.routes.insert(
        "main".into(),
        route_to(
            &format!("http://{mock}"),
            Terminator::Auto,
            Auth::Bearer,
            true,
        ),
    );
    store.routes.insert(
        "off".into(),
        route_to(
            &format!("http://{mock}"),
            Terminator::Auto,
            Auth::Bearer,
            false,
        ),
    );
    let (state, vks) = build_state(
        store,
        RetryPolicy::default(),
        1 << 20,
        keysink::proxy::BODY_READ_IDLE,
        keysink::proxy::CLIENT_BODY_TIMEOUT,
        0,
        Duration::from_millis(200),
    );
    let vk_off = vks["off"].clone();

    let cases: Vec<(&'static str, String, StatusCode)> = vec![
        (
            "authorization",
            "Bearer ks_fffffffffffffffffffffffffffffffffffffffffff0".into(),
            StatusCode::UNAUTHORIZED,
        ),
        (
            "authorization",
            "Bearer no ks prefix at all".into(),
            StatusCode::UNAUTHORIZED,
        ),
        (
            "authorization",
            format!("Bearer {vk_off}"),
            StatusCode::FORBIDDEN,
        ),
    ];
    for (header, value, want) in cases {
        let req = Request::builder()
            .method("POST")
            .uri("/v1/messages")
            .header(header, value)
            .body(Body::empty())
            .unwrap();
        let started = Instant::now();
        let resp = keysink::proxy::handler(State(state.clone()), req).await;
        assert_eq!(resp.status(), want);
        assert!(
            started.elapsed() < Duration::from_millis(150),
            "{want} must reject before the permit queue, took {:?}",
            started.elapsed()
        );
    }

    // Oversized declared Content-Length is also screenable from the head
    // alone: 2 MiB against a 1 MiB limit.
    let req = Request::builder()
        .method("POST")
        .uri("/v1/messages")
        .header("authorization", format!("Bearer {}", vks["main"]))
        .header("content-length", (2 << 20).to_string())
        .body(Body::empty())
        .unwrap();
    let started = Instant::now();
    let resp = keysink::proxy::handler(State(state.clone()), req).await;
    assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
    assert!(started.elapsed() < Duration::from_millis(150));
}

/// A valid request past an exhausted permit pool must be shed at the queue
/// bound (503 + Retry-After), not hang until the client's own timeout —
/// the scenario of a wedged upstream pinning every permit for
/// attempts × header_timeout + backoff.
#[tokio::test]
async fn queue_bound_sheds_valid_request_with_503() {
    let (mock, _hits) = spawn_mock().await;
    let mut store = Store::new();
    store.routes.insert(
        "main".into(),
        route_to(
            &format!("http://{mock}"),
            Terminator::Auto,
            Auth::Bearer,
            true,
        ),
    );
    let (state, vks) = build_state(
        store,
        RetryPolicy::default(),
        1 << 20,
        keysink::proxy::BODY_READ_IDLE,
        keysink::proxy::CLIENT_BODY_TIMEOUT,
        0,
        Duration::from_millis(200),
    );

    let req = Request::builder()
        .method("POST")
        .uri("/v1/messages")
        .header("authorization", format!("Bearer {}", vks["main"]))
        .body(Body::empty())
        .unwrap();
    let started = Instant::now();
    let resp = keysink::proxy::handler(State(state), req).await;
    assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
    assert_eq!(
        resp.headers()
            .get("retry-after")
            .and_then(|v| v.to_str().ok()),
        Some("1"),
        "shed responses must carry Retry-After"
    );
    assert!(
        started.elapsed() >= Duration::from_millis(195),
        "shed must happen at the queue bound, not before: {:?}",
        started.elapsed()
    );
}

// ---------- refusals at the gateway edge (path dot segments, proxy methods) ----------

/// Sends one raw HTTP/1.1 request over a fresh TCP connection: unlike a real
/// HTTP client, this bypasses client-side URL normalization, so the gateway
/// sees the path exactly as an attacker would send it.
async fn raw_request(addr: SocketAddr, request: &str) -> (u16, String) {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    let mut sock = tokio::net::TcpStream::connect(addr).await.unwrap();
    sock.write_all(request.as_bytes()).await.unwrap();
    let mut buf = Vec::new();
    let _ = tokio::time::timeout(Duration::from_secs(5), sock.read_to_end(&mut buf)).await;
    let text = String::from_utf8_lossy(&buf).into_owned();
    let status = text
        .split("\r\n")
        .next()
        .and_then(|l| l.split_whitespace().nth(1))
        .and_then(|c| c.parse::<u16>().ok())
        .unwrap_or(0);
    (status, text)
}

#[tokio::test]
async fn dot_segment_paths_and_proxy_methods_are_refused_before_the_upstream() {
    let (mock, hits) = spawn_mock().await;
    let mut store = Store::new();
    store.routes.insert(
        "main".into(),
        route_to(
            &format!("http://{mock}"),
            Terminator::Auto,
            Auth::Bearer,
            true,
        ),
    );
    let (gw, vks) = spawn_gateway(store, RetryPolicy::default(), 1 << 20).await;
    let vk = vks["main"].clone();
    let host = format!("127.0.0.1:{}", gw.port());
    let head = |target: &str| {
        format!(
            "{target}\r\nHost: {host}\r\nAuthorization: Bearer {vk}\r\nConnection: close\r\n\r\n"
        )
    };

    // CONNECT/TRACE/TRACK are refused with 405 before any upstream work. A
    // TRACE the upstream implements would echo the forwarded headers — the
    // injected real key included — back into the agent's view.
    for (line, name) in [
        (format!("CONNECT {host} HTTP/1.1"), "CONNECT"),
        ("TRACE /v1/x HTTP/1.1".to_string(), "TRACE"),
        ("TRACK /v1/x HTTP/1.1".to_string(), "TRACK"),
    ] {
        let (status, body) = raw_request(gw, &head(&line)).await;
        assert_eq!(status, 405, "{name} must be 405: {body}");
        assert!(body.contains("does not proxy"), "{name}: {body}");
    }
    let (status, body) = raw_request(gw, &head("TRACE /v1/x HTTP/1.1")).await;
    assert_eq!(status, 405);
    assert!(
        body.to_lowercase().contains("allow: "),
        "405 must advertise Allow: {body}"
    );

    // Dot segments (literal, percent-encoded, backslash-separated) are refused
    // with 404: the downstream URL parser would collapse them and let the
    // request escape the route's base_url prefix on the upstream host.
    for path in ["/../x", "/v1/%2e%2e/x", "/a\\..\\b", "/a/./b"] {
        let (status, body) = raw_request(gw, &head(&format!("GET {path} HTTP/1.1"))).await;
        assert_eq!(status, 404, "dot-segment path {path:?} must be 404: {body}");
    }

    // Asterisk-form targets are refused as the client error they are, instead
    // of surfacing as a 500 configuration_error from the URL builder.
    let (status, body) = raw_request(gw, &head("OPTIONS * HTTP/1.1")).await;
    assert_eq!(status, 400, "asterisk-form must be 400: {body}");

    // And a plain in-prefix request still forwards normally.
    let (status, _) = raw_request(gw, &head("GET /v1/models HTTP/1.1")).await;
    assert_eq!(status, 200);

    assert_eq!(
        hits.load(Ordering::Relaxed),
        1,
        "only the plain request may have reached the upstream"
    );
}