cellos-supervisor 0.5.1

CellOS execution-cell runner — boots cells in Firecracker microVMs or gVisor, enforces narrow typed authority, emits signed CloudEvents.
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
//! SEC-22 Phase 2 SNI-aware egress proxy.
//!
//! Inspects the first bytes of every TCP connection a workload opens and
//! enforces `dnsAuthority.hostnameAllowlist` at L7 by parsing either:
//!
//! - the TLS ClientHello's `server_name` extension ([`sni`]), or
//! - the HTTP/1.x `Host` header on cleartext requests ([`http`]),
//!
//! and matching the extracted hostname against the shared
//! [`cellos_core::hostname_allowlist::matches_allowlist`] helper. Allowed
//! flows are forwarded to a declared upstream via
//! `tokio::io::copy_bidirectional` (the proxy NEVER terminates TLS — the
//! ClientHello bytes that produced the SNI decision are written through to
//! the upstream as the first bytes of the forwarded stream). Denied flows
//! are dropped (TLS) or answered with `HTTP/1.1 403 Forbidden` (cleartext
//! HTTP). Each decision emits exactly one
//! `dev.cellos.events.cell.observability.v1.l7_egress_decision` CloudEvent
//! carrying one of the eight Phase 2 reason codes:
//!
//! - `l7_sni_allowlist_match`           — TLS allow
//! - `l7_sni_allowlist_miss`            — TLS deny (SNI not in allowlist)
//! - `l7_sni_missing`                   — TLS deny (no SNI in ClientHello)
//! - `l7_http_host_allowlist_match`     — HTTP allow
//! - `l7_http_host_allowlist_miss`      — HTTP deny (Host not in allowlist)
//! - `l7_http_host_missing`             — HTTP deny (no Host header)
//! - `l7_unknown_protocol`              — first bytes neither TLS nor HTTP/1.x
//! - `l7_peek_timeout`                  — workload sent no bytes within the
//!   peek window (defensive shutdown)
//!
//! ### Phase 3a (h2c) — additional reason codes
//!
//! - `l7_h2_authority_allowlist_match`  — h2c HEADERS-frame `:authority`
//!   matched the allowlist; bytes forwarded.
//! - `l7_h2_authority_allowlist_miss`   — h2c HEADERS-frame `:authority`
//!   did NOT match the allowlist; deny + GOAWAY (PROTOCOL_ERROR).
//! - `l7_h2_authority_missing`          — well-formed h2c frames but no
//!   `:authority` pseudo-header in the first HEADERS frame.
//! - `l7_h2_unparseable_headers`        — HPACK decode failure,
//!   CONTINUATION-fragmented HEADERS, oversized frame, or any other h2
//!   parse error Phase 3a does not handle. Deny + GOAWAY.
//!
//! The reason-code list extends the existing
//! `cell-observability-l7-egress-decision-v1.schema.json` `reasonCode`
//! description without breaking shape — only new string values are added.
//!
//! ## Honest scope
//!
//! - **TLS not terminated.** SNI ↔ Host alignment cannot be checked in
//!   Phase 2; that requires MITM termination and a CA the workload trusts.
//!   Fronting via mismatched SNI vs. Host on the same TLS session remains a
//!   Phase 3 residual risk per [`docs/sec22-residual-risk.md`].
//! - **HTTP/2 cleartext (h2c) inspected (Phase 3a).** When a workload
//!   sends the canonical 24-byte `PRI * HTTP/2.0` preface, the proxy
//!   peels it + the optional SETTINGS frame and parses the first HEADERS
//!   frame's `:authority` pseudo-header through the static-table-only
//!   HPACK decoder in [`h2`]. The same `dnsAuthority.hostnameAllowlist`
//!   that gates SNI + HTTP/1.x Host gates h2c. Allow path forwards the
//!   buffered preface + HEADERS verbatim; deny path emits an HTTP/2
//!   GOAWAY (PROTOCOL_ERROR) and closes.
//! - **HTTP/2 over TLS still residual.** Inspecting HEADERS inside an
//!   encrypted stream requires TLS termination — Phase 4. HTTP/3 / QUIC
//!   are also out of scope.
//! - **DoH residual.** When an operator allowlists a hostname that itself
//!   hosts DoH, the workload can tunnel DNS inside an allowed flow. This is
//!   an operator-policy residual; the proxy enforces what the allowlist
//!   declares, not the semantic intent.
//!
//! ## Module layout
//!
//! - [`sni`] — pure-byte ClientHello SNI extractor.
//! - [`http`] — HTTP/1.x request-line + Host extractor.
//! - [`run_one_shot`] (in this file) — async per-connection accept/probe/
//!   forward loop, platform-neutral.
//! - [`spawn`] — Linux-only `setns(2)` helper that places `run_one_shot`'s
//!   listener inside the cell's netns; mirrors [`crate::dns_proxy::spawn`].
//!
//! Reuses the shared
//! [`cellos_core::hostname_allowlist::matches_allowlist`] helper that the
//! W8 commit extracted from the W3 SEAM-1 dataplane proxy.

pub mod h2;
pub mod http;
pub mod sni;
pub mod spawn;

use std::net::SocketAddr;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;

use cellos_core::{CdnProvider, CloudEventV1, ExecutionCellSpec};
use serde_json::{json, Map, Value};
use tokio::io::AsyncWriteExt;
use tokio::net::{TcpListener, TcpStream};

/// Maximum bytes the proxy peeks before deciding probe/allow/deny.
///
/// scope: 16 KiB ceiling. The TLS / HTTP/1.x paths always decide well
/// under 4 KiB; the ceiling is sized for h2c HEADERS+CONTINUATION
/// reassembly. RFC 7540 §6.5.2 default `SETTINGS_MAX_FRAME_SIZE` is
/// 16 KiB so the worst-case single HEADERS-with-no-CONTINUATION frame
/// plus the leading SETTINGS frame fits in this buffer; longer header
/// blocks fragment over CONTINUATION up to [`h2::MAX_HEADER_BLOCK_SIZE`]
/// (64 KiB) — at which point the reassembler returns `Ok(None)` (need
/// more bytes) and the peek_timeout path triggers, so the connection is
/// denied with a `peek_timeout` rather than over-buffering memory per
/// connection.
pub const PEEK_BUF_LEN: usize = 16 * 1024;

/// Subset of [`ExecutionCellSpec`] that the proxy needs at run-time. Owned
/// so the supervisor can build it once and pass it through the
/// async-to-sync-thread boundary without lifetime gymnastics (mirrors
/// [`crate::dns_proxy::DnsProxyConfig`]).
#[derive(Debug, Clone)]
pub struct SniProxyConfig {
    /// Address the proxy listener is bound to inside the cell's netns.
    /// Used for diagnostics; the caller passes the actual pre-bound listener.
    pub bind_addr: SocketAddr,
    /// Address the proxy forwards allowed connections to. In a real
    /// deployment this is a transparent next-hop (egress NAT, sidecar) that
    /// re-emits the bytes onto the wire. In the unit tests it is a
    /// localhost echo / handshake stub.
    pub upstream_addr: SocketAddr,
    /// Hostname allowlist (literal or single-leading-`*.` wildcard). Same
    /// shape as [`crate::dns_proxy::DnsProxyConfig::hostname_allowlist`] —
    /// shared matcher in `cellos_core::hostname_allowlist`.
    pub hostname_allowlist: Vec<String>,
    /// CDN providers the workload's spec declares (`spec.authority.cdnAuthority.providers`).
    /// scope: retained for diagnostics and future SNI ↔ Host fronting
    /// detection; the current decision logic does not branch on it.
    pub cdn_providers: Vec<CdnProvider>,
    /// Cell identifier (mirrors `lifecycle.started.cellId`).
    pub cell_id: String,
    /// Run identifier (mirrors `lifecycle.started.runId`).
    pub run_id: String,
    /// Optional `policyDigest` to bind into emitted events.
    pub policy_digest: Option<String>,
    /// Optional `keysetId` to bind into emitted events.
    pub keyset_id: Option<String>,
    /// Optional `issuerKid` to bind into emitted events.
    pub issuer_kid: Option<String>,
    /// Optional `correlationId` to bind into emitted events.
    pub correlation_id: Option<String>,
    /// Resolver / proxy identifier stamped into events for audit trail.
    pub upstream_resolver_id: String,
    /// Maximum time to wait for first bytes from the workload. On timeout
    /// the connection is dropped and one `l7_peek_timeout` event is emitted.
    pub peek_timeout: Duration,
}

/// Sink the proxy uses to publish per-decision CloudEvents. Trait-erased
/// so unit tests can plug in an in-memory collector. Mirrors
/// [`crate::dns_proxy::DnsQueryEmitter`] — the same fire-and-forget shape
/// keeps the per-connection task synchronous from the emit-call's POV.
pub trait L7DecisionEmitter: Send + Sync + 'static {
    /// Publish a single CloudEvent. Implementations should not block.
    fn emit(&self, event: CloudEventV1);
}

/// Aggregate counters returned by [`run_one_shot`] when the loop terminates.
/// Mirrors [`crate::dns_proxy::DnsProxyStats`]; logged at teardown for
/// sanity-checking ratios.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct ProxyStats {
    pub connections_total: u64,
    pub connections_allowed: u64,
    pub connections_denied: u64,
    pub peek_timeouts: u64,
    pub upstream_failures: u64,
}

/// Reason codes for `l7_egress_decision` events emitted by the SNI proxy.
/// All twelve values extend the existing schema's open-ended `reasonCode`
/// description — no schema break.
mod reason_code {
    pub const SNI_ALLOWLIST_MATCH: &str = "l7_sni_allowlist_match";
    pub const SNI_ALLOWLIST_MISS: &str = "l7_sni_allowlist_miss";
    pub const SNI_MISSING: &str = "l7_sni_missing";
    pub const HTTP_HOST_ALLOWLIST_MATCH: &str = "l7_http_host_allowlist_match";
    pub const HTTP_HOST_ALLOWLIST_MISS: &str = "l7_http_host_allowlist_miss";
    pub const HTTP_HOST_MISSING: &str = "l7_http_host_missing";
    pub const UNKNOWN_PROTOCOL: &str = "l7_unknown_protocol";
    pub const PEEK_TIMEOUT: &str = "l7_peek_timeout";
    // ── Phase 3a (h2c HEADERS-frame :authority) ──────────────────────
    pub const H2_AUTHORITY_ALLOWLIST_MATCH: &str = "l7_h2_authority_allowlist_match";
    pub const H2_AUTHORITY_ALLOWLIST_MISS: &str = "l7_h2_authority_allowlist_miss";
    pub const H2_AUTHORITY_MISSING: &str = "l7_h2_authority_missing";
    pub const H2_UNPARSEABLE_HEADERS: &str = "l7_h2_unparseable_headers";
    // ── Phase 3g (full HPACK: dynamic-table state + Huffman) ─────────
    // Differentiate audit trail by HOW the authority was decoded so
    // operators can spot adversaries who deliberately use rare encoder
    // paths (Huffman + dynamic table) to obfuscate.
    pub const H2_AUTHORITY_ALLOWLIST_MATCH_HUFFMAN: &str =
        "l7_h2_authority_allowlist_match_huffman";
    pub const H2_AUTHORITY_ALLOWLIST_MISS_HUFFMAN: &str = "l7_h2_authority_allowlist_miss_huffman";
    pub const H2_AUTHORITY_ALLOWLIST_MATCH_DYNAMIC_INDEXED: &str =
        "l7_h2_authority_allowlist_match_dynamic_indexed";
    pub const H2_AUTHORITY_ALLOWLIST_MISS_DYNAMIC_INDEXED: &str =
        "l7_h2_authority_allowlist_miss_dynamic_indexed";
}

/// Map an HPACK [`h2::AuthorityProvenance`] to the right (allow, miss)
/// reason-code pair so the audit trail differentiates static-table refs
/// (P3c attacker simplicity), dynamic-table refs (Phase 3g — adversary
/// established prior context), and Huffman literals (Phase 3g — adversary
/// used encoder compression).
fn h2_reason_codes_for(provenance: h2::AuthorityProvenance) -> (&'static str, &'static str) {
    match provenance {
        h2::AuthorityProvenance::StaticIndexed | h2::AuthorityProvenance::StaticLiteral => (
            reason_code::H2_AUTHORITY_ALLOWLIST_MATCH,
            reason_code::H2_AUTHORITY_ALLOWLIST_MISS,
        ),
        h2::AuthorityProvenance::DynamicIndexed => (
            reason_code::H2_AUTHORITY_ALLOWLIST_MATCH_DYNAMIC_INDEXED,
            reason_code::H2_AUTHORITY_ALLOWLIST_MISS_DYNAMIC_INDEXED,
        ),
        h2::AuthorityProvenance::Huffman => (
            reason_code::H2_AUTHORITY_ALLOWLIST_MATCH_HUFFMAN,
            reason_code::H2_AUTHORITY_ALLOWLIST_MISS_HUFFMAN,
        ),
    }
}

/// What the first peeked bytes look like.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ProtocolGuess {
    Tls,
    H2c,
    Http1,
    Unknown,
}

fn guess_protocol(buf: &[u8]) -> ProtocolGuess {
    if buf.is_empty() {
        return ProtocolGuess::Unknown;
    }
    if buf[0] == 22 {
        return ProtocolGuess::Tls;
    }
    // The h2c connection preface starts with `PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n`.
    // Probe BEFORE the HTTP/1.x method dispatch because `PRI` is a
    // "request method" only on h2 and any HTTP/1.x parser would mistake
    // the bytes that follow for a malformed request line.
    if h2::is_h2c_preface(buf) {
        return ProtocolGuess::H2c;
    }
    // HTTP/1.x request lines start with an ASCII method token. Cover the
    // common verbs the brief enumerates; anything else is unknown.
    const METHODS: &[&[u8]] = &[
        b"GET ",
        b"POST ",
        b"HEAD ",
        b"PUT ",
        b"DELETE ",
        b"OPTIONS ",
        b"PATCH ",
        b"CONNECT ",
    ];
    for m in METHODS {
        if buf.len() >= m.len() && &buf[..m.len()] == *m {
            return ProtocolGuess::Http1;
        }
    }
    ProtocolGuess::Unknown
}

/// Run the SNI proxy accept loop until `shutdown` is set.
///
/// Each accepted TCP connection is handed to a dedicated `tokio::spawn`
/// task that:
///
/// 1. Reads up to [`PEEK_BUF_LEN`] bytes within `cfg.peek_timeout`.
/// 2. Probes the protocol byte (TLS=22 / HTTP method / unknown).
/// 3. Calls the appropriate parser ([`sni::extract_sni`] or
///    [`http::extract_http_host`]) on the buffered preamble.
/// 4. Matches the extracted host against `cfg.hostname_allowlist`.
/// 5. On allow: connects to `cfg.upstream_addr`, writes the buffered
///    preamble, then `tokio::io::copy_bidirectional` until either side
///    closes.
/// 6. On deny: closes the client (TLS) or writes
///    `HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n`
///    (HTTP) and drops the stream.
/// 7. Emits exactly one `l7_egress_decision` CloudEvent regardless of path.
///
/// Each spawned task increments [`ProxyStats`] via shared atomics; the
/// returned snapshot reflects cumulative counts at loop exit.
///
/// Termination: the accept loop awakens at most once per `shutdown` flip
/// because `accept` blocks. The spawn helper's `signal_sni_proxy_shutdown`
/// connects-and-drops a TCP socket to wake `accept`; the loop then observes
/// `shutdown` and returns.
pub async fn run_one_shot(
    cfg: &SniProxyConfig,
    listener: TcpListener,
    emitter: Arc<dyn L7DecisionEmitter>,
    shutdown: Arc<AtomicBool>,
) -> std::io::Result<ProxyStats> {
    let total = Arc::new(std::sync::atomic::AtomicU64::new(0));
    let allowed = Arc::new(std::sync::atomic::AtomicU64::new(0));
    let denied = Arc::new(std::sync::atomic::AtomicU64::new(0));
    let timeouts = Arc::new(std::sync::atomic::AtomicU64::new(0));
    let upstream_failures = Arc::new(std::sync::atomic::AtomicU64::new(0));

    // Build the per-event spec stub once; the supervisor passes us
    // pre-derived fields, but `observability_l7_egress_decision_data_v1`
    // takes a `&ExecutionCellSpec` for `correlation` and `id`. We synthesise
    // a minimal spec carrying just the fields the builder reads.
    let event_spec = build_event_spec(cfg);

    while !shutdown.load(Ordering::SeqCst) {
        let (stream, peer) = match listener.accept().await {
            Ok(t) => t,
            Err(e) => {
                if shutdown.load(Ordering::SeqCst) {
                    break;
                }
                tracing::warn!(
                    target: "cellos.supervisor.sni_proxy",
                    error = %e,
                    "accept() failed"
                );
                continue;
            }
        };
        if shutdown.load(Ordering::SeqCst) {
            // Wake-connection from `signal_sni_proxy_shutdown` — drop and exit.
            drop(stream);
            break;
        }
        total.fetch_add(1, Ordering::SeqCst);

        let cfg = cfg.clone();
        let emitter = emitter.clone();
        let event_spec = event_spec.clone();
        let allowed = allowed.clone();
        let denied = denied.clone();
        let timeouts = timeouts.clone();
        let upstream_failures = upstream_failures.clone();

        tokio::spawn(async move {
            handle_connection(
                stream,
                peer,
                cfg,
                emitter,
                event_spec,
                allowed,
                denied,
                timeouts,
                upstream_failures,
            )
            .await;
        });
    }

    Ok(ProxyStats {
        connections_total: total.load(Ordering::SeqCst),
        connections_allowed: allowed.load(Ordering::SeqCst),
        connections_denied: denied.load(Ordering::SeqCst),
        peek_timeouts: timeouts.load(Ordering::SeqCst),
        upstream_failures: upstream_failures.load(Ordering::SeqCst),
    })
}

/// Per-connection worker. Encapsulated so [`run_one_shot`] stays focused on
/// the accept loop. Updates the shared atomics + emits exactly one event
/// per call.
#[allow(clippy::too_many_arguments)]
async fn handle_connection(
    mut stream: TcpStream,
    _peer: SocketAddr,
    cfg: SniProxyConfig,
    emitter: Arc<dyn L7DecisionEmitter>,
    event_spec: ExecutionCellSpec,
    allowed: Arc<std::sync::atomic::AtomicU64>,
    denied: Arc<std::sync::atomic::AtomicU64>,
    timeouts: Arc<std::sync::atomic::AtomicU64>,
    upstream_failures: Arc<std::sync::atomic::AtomicU64>,
) {
    // ── Step 1: peek with a bounded timeout. ──────────────────────────────
    let mut buf = vec![0u8; PEEK_BUF_LEN];
    let peek_result = tokio::time::timeout(cfg.peek_timeout, stream.peek(&mut buf)).await;

    let n = match peek_result {
        Err(_elapsed) => {
            // Peek timed out before any bytes arrived. Drop the client and
            // emit a peek_timeout event — this is the fallback path when
            // the workload opens a TCP connection but never sends bytes.
            timeouts.fetch_add(1, Ordering::SeqCst);
            denied.fetch_add(1, Ordering::SeqCst);
            emit_decision(
                &emitter,
                &cfg,
                &event_spec,
                "deny",
                "",
                reason_code::PEEK_TIMEOUT,
                None,
                None,
            );
            return;
        }
        Ok(Err(e)) => {
            tracing::debug!(
                target: "cellos.supervisor.sni_proxy",
                error = %e,
                "peek() error before any bytes"
            );
            denied.fetch_add(1, Ordering::SeqCst);
            emit_decision(
                &emitter,
                &cfg,
                &event_spec,
                "deny",
                "",
                reason_code::UNKNOWN_PROTOCOL,
                None,
                None,
            );
            return;
        }
        Ok(Ok(0)) => {
            // EOF before any data — treat as unknown.
            denied.fetch_add(1, Ordering::SeqCst);
            emit_decision(
                &emitter,
                &cfg,
                &event_spec,
                "deny",
                "",
                reason_code::UNKNOWN_PROTOCOL,
                None,
                None,
            );
            return;
        }
        Ok(Ok(n)) => n,
    };
    let preamble = &buf[..n];

    // ── Step 2: probe protocol + extract host. ────────────────────────────
    let guess = guess_protocol(preamble);
    let (host_opt, allow_reason, miss_reason, missing_reason, deny_response): (
        Option<String>,
        &'static str,
        &'static str,
        &'static str,
        DenyResponse,
    ) = match guess {
        ProtocolGuess::Tls => match sni::extract_sni(preamble) {
            Ok(opt) => (
                opt,
                reason_code::SNI_ALLOWLIST_MATCH,
                reason_code::SNI_ALLOWLIST_MISS,
                reason_code::SNI_MISSING,
                DenyResponse::Drop,
            ),
            Err(_e) => {
                denied.fetch_add(1, Ordering::SeqCst);
                emit_decision(
                    &emitter,
                    &cfg,
                    &event_spec,
                    "deny",
                    "",
                    reason_code::UNKNOWN_PROTOCOL,
                    None,
                    None,
                );
                return;
            }
        },
        ProtocolGuess::H2c => {
            // scope: per-stream allow/deny. Hand off to a dedicated
            // frame-by-frame handler that:
            //   - connects to upstream
            //   - parses every frame on both directions (frame layer is
            //     pure-byte; no h2 crate)
            //   - decides allow/deny per HEADERS+CONTINUATION block via
            //     H2ConnectionDecoder, and emits one l7_egress_decision
            //     per stream decision (each event carries streamId)
            //   - on deny: writes RST_STREAM(REFUSED_STREAM=7) to the
            //     workload, drops further frames on that stream, but
            //     keeps the connection alive for OTHER streams
            //   - allow path forwards verbatim to upstream
            //
            // The single-connection allow/deny lock from Phase 3g is
            // gone; the connection itself is no longer either "allowed"
            // or "denied" — only individual streams are.
            handle_h2c_connection(
                stream,
                preamble.to_vec(),
                cfg.clone(),
                emitter.clone(),
                event_spec.clone(),
                allowed.clone(),
                denied.clone(),
                upstream_failures.clone(),
            )
            .await;
            return;
        }
        ProtocolGuess::Http1 => match http::extract_http_host(preamble) {
            Ok(opt) => (
                opt,
                reason_code::HTTP_HOST_ALLOWLIST_MATCH,
                reason_code::HTTP_HOST_ALLOWLIST_MISS,
                reason_code::HTTP_HOST_MISSING,
                DenyResponse::Http403,
            ),
            Err(_e) => {
                denied.fetch_add(1, Ordering::SeqCst);
                emit_decision(
                    &emitter,
                    &cfg,
                    &event_spec,
                    "deny",
                    "",
                    reason_code::UNKNOWN_PROTOCOL,
                    None,
                    None,
                );
                return;
            }
        },
        ProtocolGuess::Unknown => {
            denied.fetch_add(1, Ordering::SeqCst);
            emit_decision(
                &emitter,
                &cfg,
                &event_spec,
                "deny",
                "",
                reason_code::UNKNOWN_PROTOCOL,
                None,
                None,
            );
            return;
        }
    };

    let host = match host_opt {
        Some(h) if !h.is_empty() => h,
        _ => {
            // TLS without SNI / HTTP without Host. Deny per protocol.
            denied.fetch_add(1, Ordering::SeqCst);
            send_deny_response(&mut stream, deny_response).await;
            emit_decision(
                &emitter,
                &cfg,
                &event_spec,
                "deny",
                "",
                missing_reason,
                None,
                None,
            );
            return;
        }
    };

    // ── Step 3: match against allowlist. ──────────────────────────────────
    if !cellos_core::hostname_allowlist::matches_allowlist(&host, &cfg.hostname_allowlist) {
        denied.fetch_add(1, Ordering::SeqCst);
        send_deny_response(&mut stream, deny_response).await;
        emit_decision(
            &emitter,
            &cfg,
            &event_spec,
            "deny",
            host.as_str(),
            miss_reason,
            None,
            None,
        );
        return;
    }

    // ── Step 4: allow → forward to upstream. ──────────────────────────────
    let upstream = match TcpStream::connect(cfg.upstream_addr).await {
        Ok(s) => s,
        Err(e) => {
            tracing::warn!(
                target: "cellos.supervisor.sni_proxy",
                error = %e,
                upstream = %cfg.upstream_addr,
                "upstream connect failed"
            );
            upstream_failures.fetch_add(1, Ordering::SeqCst);
            denied.fetch_add(1, Ordering::SeqCst);
            // Allowlist matched but upstream unreachable: send deny response so
            // the workload sees deterministic failure rather than hanging.
            send_deny_response(&mut stream, deny_response).await;
            emit_decision(
                &emitter,
                &cfg,
                &event_spec,
                "deny",
                host.as_str(),
                reason_code::UNKNOWN_PROTOCOL,
                None,
                None,
            );
            return;
        }
    };
    allowed.fetch_add(1, Ordering::SeqCst);
    emit_decision(
        &emitter,
        &cfg,
        &event_spec,
        "allow",
        host.as_str(),
        allow_reason,
        None,
        None,
    );

    // The peeked bytes are still in the kernel socket buffer (peek doesn't
    // consume), so `copy_bidirectional` will replay them to the upstream
    // automatically. This preserves the ClientHello / Host-bearing request
    // line so the upstream sees the original wire bytes verbatim.
    let mut client = stream;
    let mut up = upstream;
    if let Err(e) = tokio::io::copy_bidirectional(&mut client, &mut up).await {
        tracing::debug!(
            target: "cellos.supervisor.sni_proxy",
            error = %e,
            host = %host,
            "copy_bidirectional ended with error"
        );
    }
}

/// scope: dedicated h2c connection handler with per-stream
/// allow/deny semantics.
///
/// Supersedes a prior `tokio::io::copy_bidirectional` short-circuit
/// (which locked the entire connection to the FIRST `:authority`
/// observed) with a frame-by-frame parser:
///
/// 1. Connect to upstream; forward the buffered preface bytes.
/// 2. In one task, copy upstream → client verbatim (we don't inspect
///    server-emitted HEADERS — server-PUSH inspection is Phase 4).
/// 3. In the main task, read client; parse frames; for HEADERS or
///    CONTINUATION feed to `H2ConnectionDecoder.feed_frame`. For each
///    completed block, match `:authority` against the allowlist and
///    either forward verbatim (allow) or RST_STREAM(REFUSED_STREAM=7)
///    plus drop subsequent stream-bound frames (deny). Emit one
///    `l7_egress_decision` event per stream decision; each event
///    carries `streamId`.
/// 4. Control frames (SETTINGS / PING / WINDOW_UPDATE / GOAWAY) are
///    forwarded verbatim regardless of any per-stream deny — they
///    govern the connection itself.
///
/// Honest scope: server-PUSH'd stream `:authority` (PUSH_PROMISE
/// HEADERS) and TRAILERS-frame inspection both remain Phase 4 — this
/// handler reads only client→server HEADERS/CONTINUATION. TLS-encrypted
/// h2 (h2 over TLS) is still ADR-0004 territory.
///
/// CONTINUATION-fragmented HEADERS across MULTIPLE streams on the same
/// connection: per RFC 7540 §6.10, only one stream may have an open
/// HEADERS at a time on a connection (the §6.10 PROTOCOL_ERROR contract
/// is enforced inside `H2StreamReassembler`). For the single-stream
/// CONTINUATION case the handler buffers the raw HEADERS+CONTINUATION
/// frame bytes against the stream id and forwards them on allow / drops
/// them on deny.
#[allow(clippy::too_many_arguments)]
/// Lazy upstream connection for the h2c handler.
///
/// **Zero-byte invariant on deny.** The handler MUST NOT open a TCP
/// connection to the upstream until the first `:authority`-bearing
/// HEADERS frame has been parsed AND the authority decision is `allow`.
/// Until then, every byte the parse loop wants to forward (the 24-byte
/// HTTP/2 preface, the workload's SETTINGS, WINDOW_UPDATE, and any
/// other control frames that arrive on stream 0) is buffered in
/// memory. If the first authority decision is `deny`, the buffer is
/// dropped and no connection is ever made — the
/// `break_attempt_sni_mismatch_h2c::h2c_authority_mismatch_is_denied_with_zero_upstream_bytes`
/// regression guard locks this in.
enum UpstreamSink {
    /// No upstream socket yet. `buffer` accumulates bytes the parse
    /// loop wanted to forward; on the first allow they are flushed in
    /// order.
    Pending { addr: SocketAddr, buffer: Vec<u8> },
    /// Connected: bytes flow through the split write half; the read
    /// half is exposed to the bidirectional select! loop.
    Open {
        rd: tokio::net::tcp::OwnedReadHalf,
        wr: tokio::net::tcp::OwnedWriteHalf,
    },
}

impl UpstreamSink {
    fn pending(addr: SocketAddr) -> Self {
        Self::Pending {
            addr,
            buffer: Vec::new(),
        }
    }

    /// Buffer or write — never opens the connection.
    async fn write(&mut self, bytes: &[u8]) -> std::io::Result<()> {
        match self {
            Self::Pending { buffer, .. } => {
                buffer.extend_from_slice(bytes);
                Ok(())
            }
            Self::Open { wr, .. } => wr.write_all(bytes).await,
        }
    }

    /// Connect (idempotent). On first call: opens the TCP socket and
    /// flushes the pending buffer. On subsequent calls: no-op.
    async fn commit(&mut self) -> std::io::Result<()> {
        if let Self::Pending { addr, buffer } = self {
            let stream = TcpStream::connect(*addr).await?;
            let (rd, mut wr) = stream.into_split();
            if !buffer.is_empty() {
                wr.write_all(buffer).await?;
            }
            *self = Self::Open { rd, wr };
        }
        Ok(())
    }

    async fn shutdown(&mut self) {
        if let Self::Open { wr, .. } = self {
            let _ = wr.shutdown().await;
        }
    }
}

/// `select!`-friendly read: returns the upstream's next bytes when
/// connected, otherwise an unfullfillable future so the select branch
/// is effectively dormant until the first allow opens the socket.
async fn read_upstream(sink: &mut UpstreamSink, buf: &mut [u8]) -> std::io::Result<usize> {
    use tokio::io::AsyncReadExt;
    match sink {
        UpstreamSink::Open { rd, .. } => rd.read(buf).await,
        UpstreamSink::Pending { .. } => std::future::pending().await,
    }
}

#[allow(clippy::too_many_arguments)]
async fn handle_h2c_connection(
    stream: TcpStream,
    preamble: Vec<u8>,
    cfg: SniProxyConfig,
    emitter: Arc<dyn L7DecisionEmitter>,
    event_spec: ExecutionCellSpec,
    allowed: Arc<std::sync::atomic::AtomicU64>,
    denied: Arc<std::sync::atomic::AtomicU64>,
    upstream_failures: Arc<std::sync::atomic::AtomicU64>,
) {
    use tokio::io::AsyncReadExt;

    // Step 1: stage the upstream sink in `Pending` mode. The TCP
    // connection is NOT opened yet — only the first allow decision
    // commits it. Until then every "to upstream" write goes into the
    // sink's buffer; on a connection that only ever sees denied
    // streams we never connect, never leak the preface, never leak
    // SETTINGS.
    let mut upstream = UpstreamSink::pending(cfg.upstream_addr);

    // Step 2: consume the buffered preamble from the kernel socket.
    // The peek didn't consume; do a real read so subsequent reads
    // start AFTER the preamble.
    let mut client = stream;
    let mut consumed = vec![0u8; preamble.len()];
    if let Err(e) = client.read_exact(&mut consumed).await {
        tracing::debug!(
            target: "cellos.supervisor.sni_proxy",
            error = %e,
            "h2c read_exact(preamble) failed"
        );
        return;
    }
    debug_assert_eq!(
        consumed, preamble,
        "kernel returned different bytes than peek"
    );

    // Step 3: split the client side now (we own both halves) and queue
    // the 24-byte preface against the deferred upstream sink. The
    // preface is part of every h2 connection's wire shape, but it is
    // not committed to the upstream until the first allow.
    let (mut client_rd, mut client_wr) = client.into_split();

    if let Err(e) = upstream.write(&preamble[..h2::HTTP2_PREFACE.len()]).await {
        tracing::debug!(
            target: "cellos.supervisor.sni_proxy",
            error = %e,
            "h2c buffer(preface) failed"
        );
        return;
    }

    // Bidirectional copy is driven inline via tokio::select! below so
    // the same task that owns `client_wr` can both forward upstream→
    // client bytes verbatim AND emit RST_STREAM frames on the workload
    // side when a per-stream allow/deny decision lands. Server-PUSH
    // HEADERS inspection is Phase 4.
    let mut decoder = h2::H2ConnectionDecoder::new();
    let mut denied_streams: std::collections::HashSet<u32> = std::collections::HashSet::new();
    // Per-stream pending HEADERS+CONTINUATION raw frame buffer. The
    // handler buffers raw frame bytes against the stream id and
    // forwards them on the block-level allow decision (or drops on
    // deny). RFC 7540 §6.10 forbids interleaving multiple streams'
    // HEADERS+CONTINUATION sequences, so only ONE entry will ever be
    // live at a time.
    let mut pending_headers: std::collections::HashMap<u32, Vec<u8>> =
        std::collections::HashMap::new();
    let mut frame_buf: Vec<u8> = preamble[h2::HTTP2_PREFACE.len()..].to_vec();
    let mut read_chunk = vec![0u8; 16 * 1024];
    let mut up_read_chunk = vec![0u8; 16 * 1024];

    'outer: loop {
        // Try to parse as many full frames as the buffer holds.
        loop {
            match h2::frame::parse_one_frame(&frame_buf) {
                Ok(Some((header, payload, _rest))) => {
                    let frame_total = 9 + header.length as usize;
                    let frame_bytes = frame_buf[..frame_total].to_vec();
                    let payload_owned = payload.to_vec();
                    let frame_type = header.frame_type;
                    let stream_id = header.stream_id;
                    let is_stream_bound = stream_id != 0;
                    let is_headers_or_continuation = frame_type == h2::frame::FRAME_TYPE_HEADERS
                        || frame_type == h2::frame::FRAME_TYPE_CONTINUATION;

                    if is_headers_or_continuation {
                        // Buffer the raw frame bytes against stream id;
                        // they'll be forwarded together on allow.
                        pending_headers
                            .entry(stream_id)
                            .or_default()
                            .extend_from_slice(&frame_bytes);

                        match decoder.feed_frame(&header, &payload_owned) {
                            Ok(Some(decoded)) => {
                                let sid = decoded.stream_id;
                                let host_norm = decoded.authority.clone();
                                let provenance = if decoded.via_huffman {
                                    h2::AuthorityProvenance::Huffman
                                } else if decoded.via_dynamic_table {
                                    h2::AuthorityProvenance::DynamicIndexed
                                } else {
                                    h2::AuthorityProvenance::StaticLiteral
                                };
                                let (allow_r, miss_r) = h2_reason_codes_for(provenance);
                                let allow = match host_norm.as_deref() {
                                    Some(h) if !h.is_empty() => {
                                        cellos_core::hostname_allowlist::matches_allowlist(
                                            h,
                                            &cfg.hostname_allowlist,
                                        )
                                    }
                                    _ => false,
                                };
                                let pending = pending_headers.remove(&sid).unwrap_or_default();
                                if host_norm.is_none() {
                                    denied.fetch_add(1, Ordering::SeqCst);
                                    denied_streams.insert(sid);
                                    let rst = build_rst_stream_refused(sid);
                                    let _ = client_wr.write_all(&rst).await;
                                    emit_decision(
                                        &emitter,
                                        &cfg,
                                        &event_spec,
                                        "deny",
                                        "",
                                        reason_code::H2_AUTHORITY_MISSING,
                                        None,
                                        Some(sid),
                                    );
                                } else if allow {
                                    allowed.fetch_add(1, Ordering::SeqCst);
                                    // First allow gates the TCP commit:
                                    // open the upstream socket and flush
                                    // the preface + any buffered control
                                    // frames (SETTINGS, WINDOW_UPDATE).
                                    // Idempotent — second + subsequent
                                    // allows just write through.
                                    if let Err(e) = upstream.commit().await {
                                        tracing::warn!(
                                            target: "cellos.supervisor.sni_proxy",
                                            error = %e,
                                            upstream = %cfg.upstream_addr,
                                            "h2c upstream connect failed (deferred)"
                                        );
                                        upstream_failures.fetch_add(1, Ordering::SeqCst);
                                        denied.fetch_add(1, Ordering::SeqCst);
                                        let _ = client_wr.write_all(H2_GOAWAY_PROTOCOL_ERROR).await;
                                        let _ = client_wr.shutdown().await;
                                        emit_decision(
                                            &emitter,
                                            &cfg,
                                            &event_spec,
                                            "deny",
                                            "",
                                            reason_code::UNKNOWN_PROTOCOL,
                                            None,
                                            None,
                                        );
                                        break 'outer;
                                    }
                                    if let Err(e) = upstream.write(&pending).await {
                                        tracing::debug!(
                                            target: "cellos.supervisor.sni_proxy",
                                            error = %e,
                                            "h2c forward(allowed HEADERS block) failed"
                                        );
                                        break 'outer;
                                    }
                                    emit_decision(
                                        &emitter,
                                        &cfg,
                                        &event_spec,
                                        "allow",
                                        host_norm.as_deref().unwrap_or(""),
                                        allow_r,
                                        None,
                                        Some(sid),
                                    );
                                } else {
                                    denied.fetch_add(1, Ordering::SeqCst);
                                    denied_streams.insert(sid);
                                    let rst = build_rst_stream_refused(sid);
                                    let _ = client_wr.write_all(&rst).await;
                                    emit_decision(
                                        &emitter,
                                        &cfg,
                                        &event_spec,
                                        "deny",
                                        host_norm.as_deref().unwrap_or(""),
                                        miss_r,
                                        None,
                                        Some(sid),
                                    );
                                }
                            }
                            Ok(None) => {
                                // Block not yet complete; keep buffering.
                            }
                            Err(_e) => {
                                denied.fetch_add(1, Ordering::SeqCst);
                                denied_streams.insert(stream_id);
                                pending_headers.remove(&stream_id);
                                let rst = build_rst_stream_refused(stream_id);
                                let _ = client_wr.write_all(&rst).await;
                                emit_decision(
                                    &emitter,
                                    &cfg,
                                    &event_spec,
                                    "deny",
                                    "",
                                    reason_code::H2_UNPARSEABLE_HEADERS,
                                    None,
                                    Some(stream_id),
                                );
                            }
                        }
                    } else if is_stream_bound && denied_streams.contains(&stream_id) {
                        // Drop stream-bound frames on a denied stream.
                    } else {
                        // Control frames (stream id 0) + stream-bound
                        // on undenied streams: queue or forward. The
                        // sink buffers if upstream isn't connected yet
                        // (deferred-connect invariant for the deny path)
                        // and writes through once the first allow has
                        // committed the connection.
                        if let Err(e) = upstream.write(&frame_bytes).await {
                            tracing::debug!(
                                target: "cellos.supervisor.sni_proxy",
                                error = %e,
                                "h2c forward(frame) failed"
                            );
                            break 'outer;
                        }
                    }

                    frame_buf.drain(..frame_total);
                    continue;
                }
                Ok(None) => break, // need more bytes
                Err(_e) => {
                    // Connection-level frame parse error (oversized
                    // frame, malformed header). Send GOAWAY and bail.
                    let _ = client_wr.write_all(H2_GOAWAY_PROTOCOL_ERROR).await;
                    upstream.shutdown().await;
                    break 'outer;
                }
            }
        }

        // Bidirectional read: prefer client (so we keep parsing) but
        // also drain upstream → client to avoid stalling the upstream
        // when it sends responses (HEADERS / DATA / WINDOW_UPDATE).
        tokio::select! {
            biased;
            r = client_rd.read(&mut read_chunk) => match r {
                Ok(0) => break 'outer,
                Ok(n) => frame_buf.extend_from_slice(&read_chunk[..n]),
                Err(e) => {
                    tracing::debug!(
                        target: "cellos.supervisor.sni_proxy",
                        error = %e,
                        "h2c client read error"
                    );
                    break 'outer;
                }
            },
            r = read_upstream(&mut upstream, &mut up_read_chunk) => match r {
                Ok(0) => break 'outer,
                Ok(n) => {
                    if let Err(e) = client_wr.write_all(&up_read_chunk[..n]).await {
                        tracing::debug!(
                            target: "cellos.supervisor.sni_proxy",
                            error = %e,
                            "h2c upstream→client write failed"
                        );
                        break 'outer;
                    }
                }
                Err(e) => {
                    tracing::debug!(
                        target: "cellos.supervisor.sni_proxy",
                        error = %e,
                        "h2c upstream read error"
                    );
                    break 'outer;
                }
            },
        }
    }

    upstream.shutdown().await;
    let _ = client_wr.shutdown().await;
}

/// Build a 13-byte RST_STREAM frame (RFC 7540 §6.4) on `stream_id` with
/// error code `REFUSED_STREAM` (0x7). Layout:
///
/// ```text
///   00 00 04          length = 4
///   03                type = RST_STREAM
///   00                flags = 0
///   ?? ?? ?? ??       stream id (R bit clear)
///   00 00 00 07       error code = REFUSED_STREAM
/// ```
fn build_rst_stream_refused(stream_id: u32) -> [u8; 13] {
    let mut out = [0u8; 13];
    out[0] = 0x00;
    out[1] = 0x00;
    out[2] = 0x04; // length
    out[3] = 0x03; // type = RST_STREAM
    out[4] = 0x00; // flags
    let sid = stream_id & 0x7FFF_FFFF;
    out[5..9].copy_from_slice(&sid.to_be_bytes());
    out[9..13].copy_from_slice(&7u32.to_be_bytes()); // REFUSED_STREAM
    out
}

#[derive(Debug, Clone, Copy)]
enum DenyResponse {
    Drop,
    Http403,
    /// scope: retained for connection-level h2c errors that bail out
    /// before the per-stream handler — see [`handle_h2c_connection`].
    /// The per-stream allow/deny path uses
    /// `RST_STREAM(REFUSED_STREAM=7)` directly via
    /// [`build_rst_stream_refused`] instead so the connection stays
    /// alive for other streams.
    #[allow(dead_code)]
    H2Goaway,
}

/// Minimal HTTP/2 GOAWAY frame (RFC 7540 §6.8) carrying error code
/// `PROTOCOL_ERROR` (0x1) on stream 0 with `last-stream-id = 1`. Layout:
///
/// ```text
///   00 00 08    length = 8
///   07          type = GOAWAY
///   00          flags = 0
///   00 00 00 00 stream id = 0 (R bit clear)
///   00 00 00 01 last-stream-id = 1
///   00 00 00 01 error code = PROTOCOL_ERROR
/// ```
const H2_GOAWAY_PROTOCOL_ERROR: &[u8; 17] = &[
    0x00, 0x00, 0x08, // length
    0x07, // type=GOAWAY
    0x00, // flags
    0x00, 0x00, 0x00, 0x00, // stream id=0
    0x00, 0x00, 0x00, 0x01, // last-stream-id=1
    0x00, 0x00, 0x00, 0x01, // error code = PROTOCOL_ERROR
];

async fn send_deny_response(stream: &mut TcpStream, mode: DenyResponse) {
    match mode {
        DenyResponse::Http403 => {
            const RESP: &[u8] =
                b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
            if let Err(e) = stream.write_all(RESP).await {
                tracing::debug!(
                    target: "cellos.supervisor.sni_proxy",
                    error = %e,
                    "writing 403 response failed"
                );
            }
            let _ = stream.shutdown().await;
        }
        DenyResponse::H2Goaway => {
            if let Err(e) = stream.write_all(H2_GOAWAY_PROTOCOL_ERROR).await {
                tracing::debug!(
                    target: "cellos.supervisor.sni_proxy",
                    error = %e,
                    "writing h2 GOAWAY failed"
                );
            }
            let _ = stream.shutdown().await;
        }
        DenyResponse::Drop => {
            // Nothing to write — letting `stream` drop closes it.
        }
    }
}

/// Build a synthetic [`ExecutionCellSpec`] carrying just the fields
/// [`cellos_core::observability_l7_egress_decision_data_v1`] reads (id +
/// correlation). The supervisor's full spec is large and we do not need it
/// inside the proxy thread; a thin shim keeps the API surface narrow.
fn build_event_spec(cfg: &SniProxyConfig) -> ExecutionCellSpec {
    use cellos_core::{AuthorityBundle, Correlation, Lifetime};
    let correlation = cfg.correlation_id.as_ref().map(|c| Correlation {
        correlation_id: Some(c.clone()),
        ..Default::default()
    });
    ExecutionCellSpec {
        id: format!("sni-proxy/{}/{}", cfg.cell_id, cfg.run_id),
        correlation,
        ingress: None,
        environment: None,
        placement: None,
        policy: None,
        identity: None,
        run: None,
        authority: AuthorityBundle::default(),
        lifetime: Lifetime { ttl_seconds: 0 },
        export: None,
        telemetry: None,
    }
}

/// Build + emit one `l7_egress_decision` CloudEvent.
#[allow(clippy::too_many_arguments)]
fn emit_decision(
    emitter: &Arc<dyn L7DecisionEmitter>,
    cfg: &SniProxyConfig,
    spec: &ExecutionCellSpec,
    action: &str,
    sni_host: &str,
    reason_code_str: &str,
    rule_ref: Option<&str>,
    // scope: per-stream correlation id for h2 paths. None for
    // SNI / HTTP/1.x / unknown / peek-timeout paths.
    stream_id: Option<u32>,
) {
    let decision_id = uuid::Uuid::new_v4().to_string();
    let policy_digest = cfg.policy_digest.clone().unwrap_or_default();
    let keyset_id = cfg.keyset_id.clone().unwrap_or_default();
    let issuer_kid = cfg.issuer_kid.clone().unwrap_or_default();
    let data = match cellos_core::observability_l7_egress_decision_data_v1(
        spec,
        cfg.cell_id.as_str(),
        Some(cfg.run_id.as_str()),
        decision_id.as_str(),
        action,
        // Schema requires sniHost.minLength=1; substitute a conventional
        // placeholder when the proxy could not extract a hostname (peek
        // timeout, missing SNI / Host, unknown protocol). The reasonCode
        // preserves the underlying signal.
        if sni_host.is_empty() {
            "(unknown)"
        } else {
            sni_host
        },
        policy_digest.as_str(),
        keyset_id.as_str(),
        issuer_kid.as_str(),
        reason_code_str,
        rule_ref,
        stream_id,
    ) {
        Ok(v) => v,
        Err(e) => {
            tracing::warn!(
                target: "cellos.supervisor.sni_proxy",
                error = %e,
                "build l7_egress_decision data failed"
            );
            return;
        }
    };
    let observed_at = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
    let event = CloudEventV1 {
        specversion: "1.0".into(),
        id: uuid::Uuid::new_v4().to_string(),
        source: "cellos-sni-proxy".into(),
        ty: "dev.cellos.events.cell.observability.v1.l7_egress_decision".into(),
        datacontenttype: Some("application/json".into()),
        data: Some(data),
        time: Some(observed_at),
        traceparent: None,
    };
    emitter.emit(event);
}

/// Best-effort field-value extractor used by tests + supervisor diagnostics.
/// Walks the event's `data` object and returns the JSON value at `key`.
#[allow(dead_code)]
fn event_data_get<'a>(event: &'a CloudEventV1, key: &str) -> Option<&'a Value> {
    event.data.as_ref()?.as_object()?.get(key)
}

/// Construct an empty `Map<String, Value>` with the standard event-data
/// shape; reserved for future use if tests need to fabricate events without
/// going through the emitter path.
#[allow(dead_code)]
fn empty_data_map() -> Map<String, Value> {
    let mut m = Map::new();
    m.insert("decisionId".into(), json!(uuid::Uuid::new_v4().to_string()));
    m
}

#[cfg(test)]
pub(crate) mod test_helpers {
    /// Minimal but well-formed TLS ClientHello bytes carrying the given
    /// SNI value(s). Mirrors the synth fixture in `sni::tests` so other
    /// tests can build records without re-implementing the wire format.
    pub fn build_client_hello(snis: &[&str]) -> Vec<u8> {
        let mut body = Vec::new();
        body.extend_from_slice(&[0x03, 0x03]); // legacy_version TLS 1.2
        body.extend_from_slice(&[0u8; 32]); // random
        body.push(0); // session id length
        body.extend_from_slice(&[0x00, 0x02, 0x13, 0x01]); // 1 cipher suite
        body.extend_from_slice(&[0x01, 0x00]); // compression methods

        let mut ext_section = Vec::new();
        if !snis.is_empty() {
            let mut sn_body = Vec::new();
            let mut inner = Vec::new();
            for s in snis {
                inner.push(0u8); // host_name type
                inner.extend_from_slice(&(s.len() as u16).to_be_bytes());
                inner.extend_from_slice(s.as_bytes());
            }
            sn_body.extend_from_slice(&(inner.len() as u16).to_be_bytes());
            sn_body.extend_from_slice(&inner);
            ext_section.extend_from_slice(&[0x00, 0x00]);
            ext_section.extend_from_slice(&(sn_body.len() as u16).to_be_bytes());
            ext_section.extend_from_slice(&sn_body);
        }
        body.extend_from_slice(&(ext_section.len() as u16).to_be_bytes());
        body.extend_from_slice(&ext_section);

        let mut hs = Vec::new();
        hs.push(1);
        let body_len_bytes = (body.len() as u32).to_be_bytes();
        hs.extend_from_slice(&body_len_bytes[1..]);
        hs.extend_from_slice(&body);

        let mut rec = Vec::new();
        rec.push(22);
        rec.extend_from_slice(&[0x03, 0x01]);
        rec.extend_from_slice(&(hs.len() as u16).to_be_bytes());
        rec.extend_from_slice(&hs);
        rec
    }
}

#[cfg(test)]
mod tests {
    use super::test_helpers::build_client_hello;
    use super::*;
    use std::sync::Mutex;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::{TcpListener, TcpStream};

    /// In-memory event collector for proxy unit tests.
    #[derive(Default)]
    struct MemEmitter {
        events: Mutex<Vec<CloudEventV1>>,
    }
    impl L7DecisionEmitter for MemEmitter {
        fn emit(&self, event: CloudEventV1) {
            self.events.lock().unwrap().push(event);
        }
    }

    fn cfg_with(allowlist: &[&str], upstream: SocketAddr, peek_ms: u64) -> SniProxyConfig {
        SniProxyConfig {
            bind_addr: "127.0.0.1:0".parse().unwrap(),
            upstream_addr: upstream,
            hostname_allowlist: allowlist.iter().map(|s| s.to_string()).collect(),
            cdn_providers: vec![],
            cell_id: "test-cell".into(),
            run_id: "test-run".into(),
            policy_digest: Some("digest-test".into()),
            keyset_id: Some("keyset-test".into()),
            issuer_kid: Some("kid-test".into()),
            correlation_id: None,
            upstream_resolver_id: "sni-proxy-test".into(),
            peek_timeout: Duration::from_millis(peek_ms),
        }
    }

    /// Spawn a tiny localhost echo server: accepts one connection, reads
    /// everything until EOF, echoes it back. Returns the bound address +
    /// a join handle. Used as the upstream for allow-path tests.
    async fn spawn_echo_upstream() -> (SocketAddr, tokio::task::JoinHandle<Vec<u8>>) {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let h = tokio::spawn(async move {
            let (mut s, _) = listener.accept().await.unwrap();
            let mut buf = Vec::new();
            // Read until EOF or first 64KiB; the proxy's
            // copy_bidirectional may keep the half-open stream alive
            // longer than the client wants, so cap.
            let mut tmp = [0u8; 4096];
            for _ in 0..32 {
                match s.read(&mut tmp).await {
                    Ok(0) => break,
                    Ok(n) => buf.extend_from_slice(&tmp[..n]),
                    Err(_) => break,
                }
            }
            buf
        });
        (addr, h)
    }

    /// Spawn the proxy; return its listen addr + a shutdown flag + the
    /// accept-loop join handle.
    async fn spawn_proxy(
        cfg: SniProxyConfig,
        emitter: Arc<MemEmitter>,
    ) -> (
        SocketAddr,
        Arc<AtomicBool>,
        tokio::task::JoinHandle<std::io::Result<ProxyStats>>,
    ) {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let shutdown = Arc::new(AtomicBool::new(false));
        let shutdown2 = shutdown.clone();
        let h = tokio::spawn(async move {
            run_one_shot(
                &cfg,
                listener,
                emitter as Arc<dyn L7DecisionEmitter>,
                shutdown2,
            )
            .await
        });
        (addr, shutdown, h)
    }

    fn poke_shutdown(addr: SocketAddr) {
        // Connect-and-drop wakes accept().
        let _ = std::net::TcpStream::connect_timeout(&addr, Duration::from_millis(200));
    }

    #[tokio::test]
    async fn proxy_allows_tls_with_matching_sni() {
        let (upstream, upstream_h) = spawn_echo_upstream().await;
        let emitter = Arc::new(MemEmitter::default());
        let cfg = cfg_with(&["api.example.com"], upstream, 500);
        let (listen, shutdown, h) = spawn_proxy(cfg, emitter.clone()).await;

        let ch = build_client_hello(&["api.example.com"]);
        let mut s = TcpStream::connect(listen).await.unwrap();
        s.write_all(&ch).await.unwrap();
        s.shutdown().await.ok();
        // Give upstream time to drain.
        let upstream_bytes = tokio::time::timeout(Duration::from_secs(2), upstream_h)
            .await
            .expect("upstream task")
            .expect("upstream join");
        // Upstream should have received exactly the ClientHello bytes
        // (peek didn't consume; copy_bidirectional replayed them).
        assert_eq!(
            upstream_bytes, ch,
            "upstream did not receive forwarded ClientHello bytes verbatim"
        );

        shutdown.store(true, Ordering::SeqCst);
        poke_shutdown(listen);
        let _ = tokio::time::timeout(Duration::from_secs(2), h).await;

        let evs = emitter.events.lock().unwrap();
        assert_eq!(evs.len(), 1, "expected exactly one event");
        let data = evs[0].data.as_ref().unwrap();
        assert_eq!(data["action"], "allow");
        assert_eq!(data["reasonCode"], "l7_sni_allowlist_match");
        assert_eq!(data["sniHost"], "api.example.com");
    }

    #[tokio::test]
    async fn proxy_denies_tls_with_unmatched_sni() {
        let (upstream, _upstream_h) = spawn_echo_upstream().await;
        let emitter = Arc::new(MemEmitter::default());
        let cfg = cfg_with(&["api.example.com"], upstream, 500);
        let (listen, shutdown, h) = spawn_proxy(cfg, emitter.clone()).await;

        let ch = build_client_hello(&["evil.example.com"]);
        let mut s = TcpStream::connect(listen).await.unwrap();
        s.write_all(&ch).await.unwrap();
        // For TLS deny, the proxy drops — read should return EOF quickly.
        let mut sink = Vec::new();
        let read_timeout =
            tokio::time::timeout(Duration::from_millis(800), s.read_to_end(&mut sink)).await;
        assert!(
            read_timeout.is_ok(),
            "TLS deny should close the stream promptly; got peek timeout"
        );

        shutdown.store(true, Ordering::SeqCst);
        poke_shutdown(listen);
        let _ = tokio::time::timeout(Duration::from_secs(2), h).await;

        let evs = emitter.events.lock().unwrap();
        assert_eq!(evs.len(), 1);
        let data = evs[0].data.as_ref().unwrap();
        assert_eq!(data["action"], "deny");
        assert_eq!(data["reasonCode"], "l7_sni_allowlist_miss");
        assert_eq!(data["sniHost"], "evil.example.com");
    }

    #[tokio::test]
    async fn proxy_denies_tls_without_sni() {
        let (upstream, _upstream_h) = spawn_echo_upstream().await;
        let emitter = Arc::new(MemEmitter::default());
        let cfg = cfg_with(&["api.example.com"], upstream, 500);
        let (listen, shutdown, h) = spawn_proxy(cfg, emitter.clone()).await;

        let ch = build_client_hello(&[]); // no SNI
        let mut s = TcpStream::connect(listen).await.unwrap();
        s.write_all(&ch).await.unwrap();
        let mut sink = Vec::new();
        let _ = tokio::time::timeout(Duration::from_millis(800), s.read_to_end(&mut sink)).await;

        shutdown.store(true, Ordering::SeqCst);
        poke_shutdown(listen);
        let _ = tokio::time::timeout(Duration::from_secs(2), h).await;

        let evs = emitter.events.lock().unwrap();
        assert_eq!(evs.len(), 1);
        let data = evs[0].data.as_ref().unwrap();
        assert_eq!(data["action"], "deny");
        assert_eq!(data["reasonCode"], "l7_sni_missing");
    }

    #[tokio::test]
    async fn proxy_allows_http_with_matching_host() {
        let (upstream, upstream_h) = spawn_echo_upstream().await;
        let emitter = Arc::new(MemEmitter::default());
        let cfg = cfg_with(&["api.example.com"], upstream, 500);
        let (listen, shutdown, h) = spawn_proxy(cfg, emitter.clone()).await;

        let req = b"GET / HTTP/1.1\r\nHost: api.example.com\r\nConnection: close\r\n\r\n";
        let mut s = TcpStream::connect(listen).await.unwrap();
        s.write_all(req).await.unwrap();
        s.shutdown().await.ok();
        let upstream_bytes = tokio::time::timeout(Duration::from_secs(2), upstream_h)
            .await
            .expect("upstream task")
            .expect("upstream join");
        assert_eq!(upstream_bytes, req.to_vec());

        shutdown.store(true, Ordering::SeqCst);
        poke_shutdown(listen);
        let _ = tokio::time::timeout(Duration::from_secs(2), h).await;

        let evs = emitter.events.lock().unwrap();
        assert_eq!(evs.len(), 1);
        let data = evs[0].data.as_ref().unwrap();
        assert_eq!(data["action"], "allow");
        assert_eq!(data["reasonCode"], "l7_http_host_allowlist_match");
        assert_eq!(data["sniHost"], "api.example.com");
    }

    #[tokio::test]
    async fn proxy_denies_http_with_unmatched_host_and_returns_403() {
        let (upstream, _upstream_h) = spawn_echo_upstream().await;
        let emitter = Arc::new(MemEmitter::default());
        let cfg = cfg_with(&["api.example.com"], upstream, 500);
        let (listen, shutdown, h) = spawn_proxy(cfg, emitter.clone()).await;

        let req = b"GET / HTTP/1.1\r\nHost: evil.example.com\r\nConnection: close\r\n\r\n";
        let mut s = TcpStream::connect(listen).await.unwrap();
        s.write_all(req).await.unwrap();
        // Read whatever the proxy sends back. On a clean shutdown we get
        // the full 403 response; on platforms where the immediate drop
        // races into a TCP RST we may see ConnectionReset before EOF —
        // either path is acceptable as long as the buffered bytes start
        // with the expected status line.
        let mut response = Vec::new();
        let read_result =
            tokio::time::timeout(Duration::from_secs(2), s.read_to_end(&mut response))
                .await
                .expect("read deadline");
        // Treat ConnectionReset as a successful read of whatever bytes
        // were already buffered (kernel will surface RST after the FIN
        // bytes are consumed on most platforms — macOS, in particular,
        // returns the bytes first then ECONNRESET on the next read).
        match read_result {
            Ok(_) => {}
            Err(e) if e.kind() == std::io::ErrorKind::ConnectionReset => {}
            Err(e) => panic!("unexpected read error: {e}"),
        }
        let resp_str = String::from_utf8_lossy(&response);
        assert!(
            resp_str.starts_with("HTTP/1.1 403 Forbidden\r\n"),
            "expected 403 response, got: {resp_str:?}"
        );

        shutdown.store(true, Ordering::SeqCst);
        poke_shutdown(listen);
        let _ = tokio::time::timeout(Duration::from_secs(2), h).await;

        let evs = emitter.events.lock().unwrap();
        assert_eq!(evs.len(), 1);
        let data = evs[0].data.as_ref().unwrap();
        assert_eq!(data["action"], "deny");
        assert_eq!(data["reasonCode"], "l7_http_host_allowlist_miss");
        assert_eq!(data["sniHost"], "evil.example.com");
    }

    #[tokio::test]
    async fn proxy_emits_one_event_per_connection() {
        let (upstream, _upstream_h) = spawn_echo_upstream().await;
        let emitter = Arc::new(MemEmitter::default());
        let cfg = cfg_with(&["api.example.com"], upstream, 500);
        let (listen, shutdown, h) = spawn_proxy(cfg, emitter.clone()).await;

        // Three independent connections: TLS allow, TLS deny, HTTP deny.
        // The TLS allow consumes the only echo upstream slot.
        for ch in [build_client_hello(&["api.example.com"])] {
            let mut s = TcpStream::connect(listen).await.unwrap();
            s.write_all(&ch).await.unwrap();
            s.shutdown().await.ok();
            tokio::time::sleep(Duration::from_millis(80)).await;
        }
        for ch in [build_client_hello(&["evil.example.com"])] {
            let mut s = TcpStream::connect(listen).await.unwrap();
            s.write_all(&ch).await.unwrap();
            // TLS deny: drop. read until EOF.
            let mut sink = Vec::new();
            let _ =
                tokio::time::timeout(Duration::from_millis(400), s.read_to_end(&mut sink)).await;
        }
        let req = b"GET / HTTP/1.1\r\nHost: blocked.example.com\r\n\r\n";
        let mut s = TcpStream::connect(listen).await.unwrap();
        s.write_all(req).await.unwrap();
        let mut sink = Vec::new();
        let _ = tokio::time::timeout(Duration::from_millis(400), s.read_to_end(&mut sink)).await;

        shutdown.store(true, Ordering::SeqCst);
        poke_shutdown(listen);
        let _ = tokio::time::timeout(Duration::from_secs(2), h).await;

        let evs = emitter.events.lock().unwrap();
        assert_eq!(
            evs.len(),
            3,
            "expected exactly one event per connection, got {}: {:#?}",
            evs.len(),
            evs.iter().map(|e| &e.data).collect::<Vec<_>>()
        );
    }

    #[tokio::test]
    async fn proxy_returns_peek_timeout_when_client_silent() {
        let (upstream, _upstream_h) = spawn_echo_upstream().await;
        let emitter = Arc::new(MemEmitter::default());
        let cfg = cfg_with(&["api.example.com"], upstream, 50); // 50ms peek timeout
        let (listen, shutdown, h) = spawn_proxy(cfg, emitter.clone()).await;

        // Open the connection but never send anything.
        let s = TcpStream::connect(listen).await.unwrap();
        // Wait past the peek_timeout so the proxy fires its timeout path.
        tokio::time::sleep(Duration::from_millis(250)).await;
        drop(s);

        shutdown.store(true, Ordering::SeqCst);
        poke_shutdown(listen);
        let _ = tokio::time::timeout(Duration::from_secs(2), h).await;

        let evs = emitter.events.lock().unwrap();
        assert!(!evs.is_empty(), "expected at least one peek_timeout event");
        let data = evs[0].data.as_ref().unwrap();
        assert_eq!(data["action"], "deny");
        assert_eq!(data["reasonCode"], "l7_peek_timeout");
    }

    #[test]
    fn guess_protocol_classifies_correctly() {
        assert_eq!(guess_protocol(&[22, 0x03, 0x03]), ProtocolGuess::Tls);
        assert_eq!(guess_protocol(b"GET / HTTP/1.1\r\n"), ProtocolGuess::Http1);
        assert_eq!(guess_protocol(b"POST / HTTP/1.1"), ProtocolGuess::Http1);
        assert_eq!(guess_protocol(b"\x00\x00\x00\x00"), ProtocolGuess::Unknown);
        assert_eq!(guess_protocol(b""), ProtocolGuess::Unknown);
        // The h2c preface MUST classify as H2c, not Http1, even though
        // it starts with `PRI` (an HTTP-shaped token).
        assert_eq!(guess_protocol(h2::HTTP2_PREFACE), ProtocolGuess::H2c);
    }

    // ── SEC-22 Phase 3a integration tests (h2c HEADERS-frame :authority) ──

    /// Build a complete h2c stream prefix: 24-byte preface + SETTINGS +
    /// HEADERS frame carrying a literal `:authority` HPACK entry whose
    /// name index = 1 (static-table) and value = `authority`.
    fn build_h2c_stream(authority: &str) -> Vec<u8> {
        let mut out = h2::HTTP2_PREFACE.to_vec();
        let block = h2::test_helpers::hpack_literal_indexed_name(1, authority);
        out.extend_from_slice(&h2::test_helpers::settings_then_headers(&block));
        out
    }

    /// Build an h2c stream whose first HEADERS frame carries no
    /// `:authority` (only a `:method` reference, static index 2 = GET).
    fn build_h2c_stream_no_authority() -> Vec<u8> {
        let mut out = h2::HTTP2_PREFACE.to_vec();
        // Indexed header field, index 2 (`:method: GET`) — present in
        // the static table; ignored by the authority extractor.
        let block = h2::test_helpers::hpack_indexed(2);
        out.extend_from_slice(&h2::test_helpers::settings_then_headers(&block));
        out
    }

    /// Build an h2c stream whose HEADERS frame is fragmented across
    /// CONTINUATION (END_HEADERS not set), with the END_HEADERS-bearing
    /// CONTINUATION present. Phase 3g reassembles cleanly.
    fn build_h2c_stream_continuation_reassemblable(authority: &str) -> Vec<u8> {
        let mut out = h2::HTTP2_PREFACE.to_vec();
        let block = h2::test_helpers::hpack_literal_indexed_name(1, authority);
        let mid = block.len() / 2;
        let (a, b) = block.split_at(mid);
        let mut sequence = h2::test_helpers::empty_settings_frame();
        sequence.extend_from_slice(&h2::test_helpers::continuation_fragmented_headers(a));
        sequence.extend_from_slice(&h2::test_helpers::continuation_frame(b, true));
        out.extend_from_slice(&sequence);
        out
    }

    /// Build an h2c stream whose first HEADERS frame is genuinely
    /// unparseable: an HPACK indexed-header reference at index 200 (well
    /// beyond static + empty dynamic — `HpackInvalidIndex`).
    fn build_h2c_stream_unparseable() -> Vec<u8> {
        let mut out = h2::HTTP2_PREFACE.to_vec();
        let block = h2::test_helpers::hpack_indexed(200);
        out.extend_from_slice(&h2::test_helpers::settings_then_headers(&block));
        out
    }

    /// Build an h2c stream whose `:authority` value is Huffman-coded.
    fn build_h2c_stream_huffman(authority: &str) -> Vec<u8> {
        let mut out = h2::HTTP2_PREFACE.to_vec();
        let block = h2::test_helpers::hpack_literal_indexed_name_huffman(1, authority);
        out.extend_from_slice(&h2::test_helpers::settings_then_headers(&block));
        out
    }

    /// Build an h2c stream whose `:authority` is reachable only through
    /// the dynamic table. Strategy: in a SINGLE header block, emit
    ///   (1) literal-with-incremental-indexing for `:authority = "<a>"`
    ///       — but with the value EMPTY so the decoder's
    ///       `!value.is_empty()` skip leaves it unmatched, while STILL
    ///       inserting `(":authority", "")` at dynamic index 62. (Empty
    ///       value is unusual but valid HPACK.)
    ///   (2) literal-with-incremental-indexing for a non-`:authority`
    ///       name (`:scheme = "<authority>"` to keep the bytes
    ///       interesting) — pushes (1) to dynamic index 63.
    ///   (3) literal-with-incremental-indexing referencing dynamic index
    ///       63 for the name (`:authority`) and the real authority value
    ///       — this is a literal whose NAME is dynamic-indexed, so its
    ///       provenance is `DynamicIndexed`. This is the FIRST non-empty
    ///       `:authority` and locks the proxy's decision.
    fn build_h2c_stream_dynamic_indexed_name(authority: &str) -> Vec<u8> {
        let mut out = h2::HTTP2_PREFACE.to_vec();
        let mut block: Vec<u8> = Vec::new();
        // (1) literal-with-incremental-indexing :authority = "" (empty)
        block.extend_from_slice(&h2::test_helpers::hpack_literal_indexed_name(1, ""));
        // (2) literal-with-incremental-indexing :scheme = authority
        block.extend_from_slice(&h2::test_helpers::hpack_literal_indexed_name(6, authority));
        // (3) literal-with-incremental-indexing name=dyn63 ":authority",
        //     value = authority. Name index 63 in a 6-bit prefix needs
        //     multi-octet integer encoding: 63 = mask(6=0x3F) + 0 → 0x7F
        //     in prefix-bits-saturated form; first byte is 0x40 | 0x3F =
        //     0x7F, then the multi-octet continuation 0x00.
        block.push(0x40 | 0x3F); // 01 + saturated 6-bit prefix
        block.push(0x00); // continuation: value = 0 → total = 63
        h2::test_helpers::encode_literal_string(&mut block, authority);
        out.extend_from_slice(&h2::test_helpers::settings_then_headers(&block));
        out
    }

    #[tokio::test]
    async fn proxy_allows_h2c_with_matching_authority() {
        let (upstream, upstream_h) = spawn_echo_upstream().await;
        let emitter = Arc::new(MemEmitter::default());
        let cfg = cfg_with(&["api.example.com"], upstream, 500);
        let (listen, shutdown, h) = spawn_proxy(cfg, emitter.clone()).await;

        let stream_bytes = build_h2c_stream("api.example.com");
        let mut s = TcpStream::connect(listen).await.unwrap();
        s.write_all(&stream_bytes).await.unwrap();
        s.shutdown().await.ok();

        let upstream_bytes = tokio::time::timeout(Duration::from_secs(2), upstream_h)
            .await
            .expect("upstream task")
            .expect("upstream join");
        // The proxy must forward the buffered preface + HEADERS verbatim
        // — copy_bidirectional replays the peeked bytes after the allow
        // decision, just like the SNI / HTTP/1.x paths.
        assert_eq!(
            upstream_bytes, stream_bytes,
            "upstream did not receive the forwarded h2c bytes verbatim"
        );

        shutdown.store(true, Ordering::SeqCst);
        poke_shutdown(listen);
        let _ = tokio::time::timeout(Duration::from_secs(2), h).await;

        let evs = emitter.events.lock().unwrap();
        assert_eq!(evs.len(), 1, "expected exactly one event");
        let data = evs[0].data.as_ref().unwrap();
        assert_eq!(data["action"], "allow");
        assert_eq!(data["reasonCode"], "l7_h2_authority_allowlist_match");
        assert_eq!(data["sniHost"], "api.example.com");
    }

    #[tokio::test]
    async fn proxy_denies_h2c_with_unmatched_authority() {
        let (upstream, _upstream_h) = spawn_echo_upstream().await;
        let emitter = Arc::new(MemEmitter::default());
        let cfg = cfg_with(&["api.example.com"], upstream, 500);
        let (listen, shutdown, h) = spawn_proxy(cfg, emitter.clone()).await;

        let stream_bytes = build_h2c_stream("evil.example.com");
        let mut s = TcpStream::connect(listen).await.unwrap();
        s.write_all(&stream_bytes).await.unwrap();
        let mut sink = Vec::new();
        let _ = tokio::time::timeout(Duration::from_millis(800), s.read_to_end(&mut sink)).await;

        shutdown.store(true, Ordering::SeqCst);
        poke_shutdown(listen);
        let _ = tokio::time::timeout(Duration::from_secs(2), h).await;

        let evs = emitter.events.lock().unwrap();
        assert_eq!(evs.len(), 1);
        let data = evs[0].data.as_ref().unwrap();
        assert_eq!(data["action"], "deny");
        assert_eq!(data["reasonCode"], "l7_h2_authority_allowlist_miss");
        assert_eq!(data["sniHost"], "evil.example.com");
    }

    #[tokio::test]
    async fn proxy_emits_event_for_h2_unparseable_headers() {
        // scope: CONTINUATION-fragmented HEADERS reassemble cleanly when the
        // END_HEADERS-bearing CONTINUATION is present, so the remaining
        // "unparseable" cases are HPACK errors (invalid index, invalid
        // Huffman, oversized header block, etc.). This test uses an HPACK
        // indexed reference at index 200 (well beyond static + empty dynamic).
        let (upstream, _upstream_h) = spawn_echo_upstream().await;
        let emitter = Arc::new(MemEmitter::default());
        let cfg = cfg_with(&["api.example.com"], upstream, 500);
        let (listen, shutdown, h) = spawn_proxy(cfg, emitter.clone()).await;

        let stream_bytes = build_h2c_stream_unparseable();
        let mut s = TcpStream::connect(listen).await.unwrap();
        s.write_all(&stream_bytes).await.unwrap();
        let mut sink = Vec::new();
        let _ = tokio::time::timeout(Duration::from_millis(800), s.read_to_end(&mut sink)).await;

        shutdown.store(true, Ordering::SeqCst);
        poke_shutdown(listen);
        let _ = tokio::time::timeout(Duration::from_secs(2), h).await;

        let evs = emitter.events.lock().unwrap();
        assert_eq!(evs.len(), 1);
        let data = evs[0].data.as_ref().unwrap();
        assert_eq!(data["action"], "deny");
        assert_eq!(data["reasonCode"], "l7_h2_unparseable_headers");
    }

    // ── SEC-22 Phase 3g integration tests (full HPACK + CONTINUATION) ──

    #[tokio::test]
    async fn proxy_allows_h2c_with_continuation_fragmented_authority() {
        let (upstream, upstream_h) = spawn_echo_upstream().await;
        let emitter = Arc::new(MemEmitter::default());
        let cfg = cfg_with(&["api.example.com"], upstream, 500);
        let (listen, shutdown, h) = spawn_proxy(cfg, emitter.clone()).await;

        let stream_bytes = build_h2c_stream_continuation_reassemblable("api.example.com");
        let mut s = TcpStream::connect(listen).await.unwrap();
        s.write_all(&stream_bytes).await.unwrap();
        s.shutdown().await.ok();

        let upstream_bytes = tokio::time::timeout(Duration::from_secs(2), upstream_h)
            .await
            .expect("upstream task")
            .expect("upstream join");
        assert_eq!(upstream_bytes, stream_bytes);

        shutdown.store(true, Ordering::SeqCst);
        poke_shutdown(listen);
        let _ = tokio::time::timeout(Duration::from_secs(2), h).await;

        let evs = emitter.events.lock().unwrap();
        assert_eq!(evs.len(), 1);
        let data = evs[0].data.as_ref().unwrap();
        assert_eq!(data["action"], "allow");
        // CONTINUATION reassembly + literal-indexed name → StaticLiteral.
        assert_eq!(data["reasonCode"], "l7_h2_authority_allowlist_match");
        assert_eq!(data["sniHost"], "api.example.com");
    }

    #[tokio::test]
    async fn proxy_allows_h2c_with_huffman_encoded_authority() {
        let (upstream, _upstream_h) = spawn_echo_upstream().await;
        let emitter = Arc::new(MemEmitter::default());
        let cfg = cfg_with(&["api.example.com"], upstream, 500);
        let (listen, shutdown, h) = spawn_proxy(cfg, emitter.clone()).await;

        let stream_bytes = build_h2c_stream_huffman("api.example.com");
        let mut s = TcpStream::connect(listen).await.unwrap();
        s.write_all(&stream_bytes).await.unwrap();
        s.shutdown().await.ok();

        // Allow the proxy worker to settle.
        tokio::time::sleep(Duration::from_millis(200)).await;

        shutdown.store(true, Ordering::SeqCst);
        poke_shutdown(listen);
        let _ = tokio::time::timeout(Duration::from_secs(2), h).await;

        let evs = emitter.events.lock().unwrap();
        assert_eq!(evs.len(), 1);
        let data = evs[0].data.as_ref().unwrap();
        assert_eq!(data["action"], "allow");
        assert_eq!(
            data["reasonCode"], "l7_h2_authority_allowlist_match_huffman",
            "Huffman provenance must surface as the differentiated reason code"
        );
        assert_eq!(data["sniHost"], "api.example.com");
    }

    #[tokio::test]
    async fn proxy_allows_h2c_with_dynamic_table_indexed_authority() {
        let (upstream, _upstream_h) = spawn_echo_upstream().await;
        let emitter = Arc::new(MemEmitter::default());
        let cfg = cfg_with(&["api.example.com"], upstream, 500);
        let (listen, shutdown, h) = spawn_proxy(cfg, emitter.clone()).await;

        let stream_bytes = build_h2c_stream_dynamic_indexed_name("api.example.com");
        let mut s = TcpStream::connect(listen).await.unwrap();
        s.write_all(&stream_bytes).await.unwrap();
        s.shutdown().await.ok();

        tokio::time::sleep(Duration::from_millis(200)).await;

        shutdown.store(true, Ordering::SeqCst);
        poke_shutdown(listen);
        let _ = tokio::time::timeout(Duration::from_secs(2), h).await;

        let evs = emitter.events.lock().unwrap();
        assert_eq!(evs.len(), 1, "expected one event, got {evs:#?}");
        let data = evs[0].data.as_ref().unwrap();
        assert_eq!(data["action"], "allow");
        assert_eq!(
            data["reasonCode"], "l7_h2_authority_allowlist_match_dynamic_indexed",
            "dynamic-table-name provenance must surface as the differentiated reason code"
        );
    }

    #[tokio::test]
    async fn proxy_denies_h2c_with_authority_extracted_from_huffman_literal_not_in_allowlist() {
        let (upstream, _upstream_h) = spawn_echo_upstream().await;
        let emitter = Arc::new(MemEmitter::default());
        let cfg = cfg_with(&["api.example.com"], upstream, 500);
        let (listen, shutdown, h) = spawn_proxy(cfg, emitter.clone()).await;

        let stream_bytes = build_h2c_stream_huffman("evil.example.com");
        let mut s = TcpStream::connect(listen).await.unwrap();
        s.write_all(&stream_bytes).await.unwrap();
        let mut sink = Vec::new();
        let _ = tokio::time::timeout(Duration::from_millis(800), s.read_to_end(&mut sink)).await;

        shutdown.store(true, Ordering::SeqCst);
        poke_shutdown(listen);
        let _ = tokio::time::timeout(Duration::from_secs(2), h).await;

        let evs = emitter.events.lock().unwrap();
        assert_eq!(evs.len(), 1);
        let data = evs[0].data.as_ref().unwrap();
        assert_eq!(data["action"], "deny");
        assert_eq!(
            data["reasonCode"], "l7_h2_authority_allowlist_miss_huffman",
            "Huffman provenance must surface in the deny reason code"
        );
        assert_eq!(data["sniHost"], "evil.example.com");
    }

    #[tokio::test]
    async fn proxy_emits_event_with_extracted_authority_when_huffman_used() {
        // Defence-in-depth audit signal: even on the allow path, the
        // emitted event MUST carry the extracted hostname so operators
        // see what got through. Phase 3g delivers this for Huffman where
        // P3c could only emit `l7_h2_unparseable_headers` with empty
        // sniHost.
        let (upstream, _upstream_h) = spawn_echo_upstream().await;
        let emitter = Arc::new(MemEmitter::default());
        let cfg = cfg_with(&["my-service.example.com"], upstream, 500);
        let (listen, shutdown, h) = spawn_proxy(cfg, emitter.clone()).await;

        let stream_bytes = build_h2c_stream_huffman("my-service.example.com");
        let mut s = TcpStream::connect(listen).await.unwrap();
        s.write_all(&stream_bytes).await.unwrap();
        s.shutdown().await.ok();

        tokio::time::sleep(Duration::from_millis(200)).await;

        shutdown.store(true, Ordering::SeqCst);
        poke_shutdown(listen);
        let _ = tokio::time::timeout(Duration::from_secs(2), h).await;

        let evs = emitter.events.lock().unwrap();
        assert_eq!(evs.len(), 1);
        let data = evs[0].data.as_ref().unwrap();
        // The hostname is present (no longer redacted to empty as P3c did
        // for the `l7_h2_unparseable_headers` Huffman path).
        assert_eq!(data["sniHost"], "my-service.example.com");
        assert_eq!(data["action"], "allow");
        assert_eq!(
            data["reasonCode"],
            "l7_h2_authority_allowlist_match_huffman",
        );
    }

    #[tokio::test]
    async fn proxy_emits_event_for_h2_missing_authority() {
        let (upstream, _upstream_h) = spawn_echo_upstream().await;
        let emitter = Arc::new(MemEmitter::default());
        let cfg = cfg_with(&["api.example.com"], upstream, 500);
        let (listen, shutdown, h) = spawn_proxy(cfg, emitter.clone()).await;

        let stream_bytes = build_h2c_stream_no_authority();
        let mut s = TcpStream::connect(listen).await.unwrap();
        s.write_all(&stream_bytes).await.unwrap();
        let mut sink = Vec::new();
        let _ = tokio::time::timeout(Duration::from_millis(800), s.read_to_end(&mut sink)).await;

        shutdown.store(true, Ordering::SeqCst);
        poke_shutdown(listen);
        let _ = tokio::time::timeout(Duration::from_secs(2), h).await;

        let evs = emitter.events.lock().unwrap();
        assert_eq!(evs.len(), 1);
        let data = evs[0].data.as_ref().unwrap();
        assert_eq!(data["action"], "deny");
        assert_eq!(data["reasonCode"], "l7_h2_authority_missing");
    }

    /// scope: deny-response shape on a denied h2c stream. A prior shape
    /// returned `GOAWAY(PROTOCOL_ERROR)` and closed the whole connection;
    /// the current shape keeps the connection alive and emits
    /// `RST_STREAM(REFUSED_STREAM=7)` for the offending stream only —
    /// see [`build_rst_stream_refused`]. This test asserts the wire shape.
    #[tokio::test]
    async fn proxy_h2c_deny_responds_with_rst_stream_refused() {
        let (upstream, _upstream_h) = spawn_echo_upstream().await;
        let emitter = Arc::new(MemEmitter::default());
        let cfg = cfg_with(&["api.example.com"], upstream, 500);
        let (listen, shutdown, h) = spawn_proxy(cfg, emitter.clone()).await;

        let stream_bytes = build_h2c_stream("evil.example.com");
        let mut s = TcpStream::connect(listen).await.unwrap();
        s.write_all(&stream_bytes).await.unwrap();
        // The proxy keeps the connection alive after a single-stream deny;
        // close from our side so the read_to_end below returns rather
        // than hanging on the open connection.
        s.shutdown().await.ok();
        let mut response = Vec::new();
        let read_result =
            tokio::time::timeout(Duration::from_secs(2), s.read_to_end(&mut response))
                .await
                .expect("read deadline");
        match read_result {
            Ok(_) => {}
            Err(e) if e.kind() == std::io::ErrorKind::ConnectionReset => {}
            Err(e) => panic!("unexpected read error: {e}"),
        }
        // The 13-byte RST_STREAM(REFUSED_STREAM=7) frame must be present.
        // Length=4, type=RST_STREAM (0x03), flags=0, stream id=1,
        // error code=REFUSED_STREAM (7).
        assert!(
            response.len() >= 13,
            "expected at least one full RST_STREAM frame, got {} bytes: {:02x?}",
            response.len(),
            response
        );
        assert_eq!(&response[0..3], &[0x00, 0x00, 0x04], "RST_STREAM length");
        assert_eq!(response[3], 0x03, "RST_STREAM frame type");
        assert_eq!(response[4], 0x00, "RST_STREAM flags");
        assert_eq!(&response[5..9], &[0x00, 0x00, 0x00, 0x01], "stream id 1");
        assert_eq!(
            &response[9..13],
            &[0x00, 0x00, 0x00, 0x07],
            "RST_STREAM error code = REFUSED_STREAM"
        );
        // The deny event MUST carry the streamId for audit correlation.
        // Drop the guard before awaiting the proxy join below
        // (clippy::await_holding_lock).
        {
            let evs = emitter.events.lock().unwrap();
            assert!(!evs.is_empty(), "expected at least one deny event");
            let data = evs[0].data.as_ref().unwrap();
            assert_eq!(data["action"], "deny");
            assert_eq!(data["streamId"], 1);
        }

        shutdown.store(true, Ordering::SeqCst);
        poke_shutdown(listen);
        let _ = tokio::time::timeout(Duration::from_secs(2), h).await;
    }

    /// Original GOAWAY assertion structure preserved as a no-op stub
    /// — the test is renamed and rewritten above. (No-op helper kept
    /// to avoid an artificial diff in the asserted wire-shape match
    /// arms below.)
    #[allow(dead_code)]
    fn _legacy_goaway_assertions(response: &[u8]) {
        assert_eq!(&response[0..3], &[0x00, 0x00, 0x08], "GOAWAY length");
        assert_eq!(response[3], 0x07, "GOAWAY frame type");
        assert_eq!(response[4], 0x00, "GOAWAY flags");
        assert_eq!(&response[5..9], &[0x00, 0x00, 0x00, 0x00], "stream id 0");
        assert_eq!(
            &response[13..17],
            &[0x00, 0x00, 0x00, 0x01],
            "GOAWAY error code = PROTOCOL_ERROR"
        );
    }

    // ── SEC-22 Phase 3g.1 integration tests (per-stream allow/deny) ──

    /// Build the canonical h2c stream prefix carrying TWO HEADERS frames
    /// — first on stream 1, then on stream 3 — each with a different
    /// `:authority`. Phase 3g.1 must inspect each stream's authority
    /// independently rather than locking the connection to the first
    /// observed authority.
    fn build_h2c_two_streams(authority_a: &str, authority_b: &str) -> Vec<u8> {
        let mut out = h2::HTTP2_PREFACE.to_vec();
        out.extend_from_slice(&h2::test_helpers::empty_settings_frame());
        let block_a = h2::test_helpers::hpack_literal_indexed_name(1, authority_a);
        out.extend_from_slice(&h2::test_helpers::headers_frame_on_stream(&block_a, 1));
        let block_b = h2::test_helpers::hpack_literal_indexed_name(1, authority_b);
        out.extend_from_slice(&h2::test_helpers::headers_frame_on_stream(&block_b, 3));
        out
    }

    /// Build an h2c stream that denies one stream then sends a DATA
    /// frame on that denied stream — used to verify the proxy drops
    /// the DATA frame instead of forwarding it.
    fn build_h2c_denied_stream_then_data(
        authority_allowed: &str,
        authority_denied: &str,
        data_payload: &[u8],
    ) -> Vec<u8> {
        let mut out = h2::HTTP2_PREFACE.to_vec();
        out.extend_from_slice(&h2::test_helpers::empty_settings_frame());
        // Stream 1: denied.
        let block_d = h2::test_helpers::hpack_literal_indexed_name(1, authority_denied);
        out.extend_from_slice(&h2::test_helpers::headers_frame_on_stream(&block_d, 1));
        // DATA on stream 1 — must be dropped by proxy.
        out.extend_from_slice(&h2::test_helpers::data_frame_on_stream(data_payload, 1));
        // Stream 3: allowed.
        let block_a = h2::test_helpers::hpack_literal_indexed_name(1, authority_allowed);
        out.extend_from_slice(&h2::test_helpers::headers_frame_on_stream(&block_a, 3));
        out
    }

    #[tokio::test]
    async fn proxy_allows_two_streams_with_matching_authority_on_same_connection() {
        let (upstream, upstream_h) = spawn_echo_upstream().await;
        let emitter = Arc::new(MemEmitter::default());
        let cfg = cfg_with(&["api.example.com", "api.other.com"], upstream, 500);
        let (listen, shutdown, h) = spawn_proxy(cfg, emitter.clone()).await;

        let stream_bytes = build_h2c_two_streams("api.example.com", "api.other.com");
        let mut s = TcpStream::connect(listen).await.unwrap();
        s.write_all(&stream_bytes).await.unwrap();
        s.shutdown().await.ok();

        let upstream_bytes = tokio::time::timeout(Duration::from_secs(2), upstream_h)
            .await
            .expect("upstream task")
            .expect("upstream join");
        // Upstream sees the preface + SETTINGS + both HEADERS frames
        // verbatim — the per-stream handler forwarded each on allow.
        assert_eq!(upstream_bytes, stream_bytes);

        shutdown.store(true, Ordering::SeqCst);
        poke_shutdown(listen);
        let _ = tokio::time::timeout(Duration::from_secs(2), h).await;

        let evs = emitter.events.lock().unwrap();
        assert_eq!(
            evs.len(),
            2,
            "expected one allow event per stream, got {evs:#?}"
        );
        let mut stream_ids: Vec<i64> = evs
            .iter()
            .map(|e| {
                e.data
                    .as_ref()
                    .unwrap()
                    .get("streamId")
                    .and_then(|v| v.as_i64())
                    .expect("event must carry streamId")
            })
            .collect();
        stream_ids.sort_unstable();
        assert_eq!(stream_ids, vec![1, 3]);
        for ev in evs.iter() {
            let data = ev.data.as_ref().unwrap();
            assert_eq!(data["action"], "allow");
        }
    }

    #[tokio::test]
    async fn proxy_denies_one_stream_keeps_connection_open_for_other_streams() {
        let (upstream, _upstream_h) = spawn_echo_upstream().await;
        let emitter = Arc::new(MemEmitter::default());
        let cfg = cfg_with(&["api.example.com"], upstream, 500);
        let (listen, shutdown, h) = spawn_proxy(cfg, emitter.clone()).await;

        // Stream 1 = evil (deny → RST_STREAM); stream 3 = allowed.
        let stream_bytes = build_h2c_two_streams("evil.example.com", "api.example.com");
        let mut s = TcpStream::connect(listen).await.unwrap();
        s.write_all(&stream_bytes).await.unwrap();
        // Read whatever the proxy sends back. We expect the
        // RST_STREAM(REFUSED_STREAM=7) for stream 1.
        let mut response = vec![0u8; 13];
        let read_n = tokio::time::timeout(Duration::from_secs(2), s.read_exact(&mut response))
            .await
            .expect("read deadline");
        assert!(read_n.is_ok(), "expected to read 13 bytes (RST_STREAM)");
        assert_eq!(&response[0..3], &[0x00, 0x00, 0x04], "RST_STREAM length");
        assert_eq!(response[3], 0x03, "RST_STREAM type");
        assert_eq!(&response[5..9], &[0x00, 0x00, 0x00, 0x01], "stream id 1");
        assert_eq!(
            &response[9..13],
            &[0x00, 0x00, 0x00, 0x07],
            "REFUSED_STREAM"
        );

        s.shutdown().await.ok();

        shutdown.store(true, Ordering::SeqCst);
        poke_shutdown(listen);
        let _ = tokio::time::timeout(Duration::from_secs(2), h).await;

        let evs = emitter.events.lock().unwrap();
        assert_eq!(evs.len(), 2, "expected one event per stream");
        // Stream 1 = deny; stream 3 = allow.
        let mut by_stream: std::collections::HashMap<i64, &CloudEventV1> =
            std::collections::HashMap::new();
        for ev in evs.iter() {
            let sid = ev
                .data
                .as_ref()
                .unwrap()
                .get("streamId")
                .and_then(|v| v.as_i64())
                .unwrap();
            by_stream.insert(sid, ev);
        }
        assert_eq!(by_stream[&1].data.as_ref().unwrap()["action"], "deny");
        assert_eq!(by_stream[&3].data.as_ref().unwrap()["action"], "allow");
    }

    #[tokio::test]
    async fn proxy_emits_one_event_per_stream_decision() {
        let (upstream, _upstream_h) = spawn_echo_upstream().await;
        let emitter = Arc::new(MemEmitter::default());
        let cfg = cfg_with(&["api.example.com"], upstream, 500);
        let (listen, shutdown, h) = spawn_proxy(cfg, emitter.clone()).await;

        // 3 streams: 1=allow, 3=deny, 5=deny
        let mut bytes = h2::HTTP2_PREFACE.to_vec();
        bytes.extend_from_slice(&h2::test_helpers::empty_settings_frame());
        bytes.extend_from_slice(&h2::test_helpers::headers_frame_on_stream(
            &h2::test_helpers::hpack_literal_indexed_name(1, "api.example.com"),
            1,
        ));
        bytes.extend_from_slice(&h2::test_helpers::headers_frame_on_stream(
            &h2::test_helpers::hpack_literal_indexed_name(1, "evil1.example.com"),
            3,
        ));
        bytes.extend_from_slice(&h2::test_helpers::headers_frame_on_stream(
            &h2::test_helpers::hpack_literal_indexed_name(1, "evil2.example.com"),
            5,
        ));

        let mut s = TcpStream::connect(listen).await.unwrap();
        s.write_all(&bytes).await.unwrap();
        // Drain the deny frames.
        let mut sink = vec![0u8; 64];
        let _ = tokio::time::timeout(Duration::from_millis(400), s.read(&mut sink)).await;
        s.shutdown().await.ok();

        shutdown.store(true, Ordering::SeqCst);
        poke_shutdown(listen);
        let _ = tokio::time::timeout(Duration::from_secs(2), h).await;

        let evs = emitter.events.lock().unwrap();
        assert_eq!(
            evs.len(),
            3,
            "expected exactly one event per stream, got {evs:#?}"
        );
        let mut per_action: std::collections::HashMap<String, usize> =
            std::collections::HashMap::new();
        for ev in evs.iter() {
            let action = ev.data.as_ref().unwrap()["action"]
                .as_str()
                .unwrap()
                .to_string();
            *per_action.entry(action).or_default() += 1;
            // Every event must carry a streamId.
            assert!(
                ev.data
                    .as_ref()
                    .unwrap()
                    .get("streamId")
                    .and_then(|v| v.as_i64())
                    .is_some(),
                "event missing streamId: {ev:?}"
            );
        }
        assert_eq!(per_action.get("allow").copied(), Some(1));
        assert_eq!(per_action.get("deny").copied(), Some(2));
    }

    #[tokio::test]
    async fn proxy_drops_data_frames_on_denied_stream() {
        let (upstream, upstream_h) = spawn_echo_upstream().await;
        let emitter = Arc::new(MemEmitter::default());
        let cfg = cfg_with(&["api.example.com"], upstream, 500);
        let (listen, shutdown, h) = spawn_proxy(cfg, emitter.clone()).await;

        // Stream 1 = denied (evil), then a DATA frame on stream 1
        // (must be dropped), then stream 3 = allowed.
        let secret = b"do-not-exfiltrate";
        let stream_bytes =
            build_h2c_denied_stream_then_data("api.example.com", "evil.example.com", secret);
        let mut s = TcpStream::connect(listen).await.unwrap();
        s.write_all(&stream_bytes).await.unwrap();
        s.shutdown().await.ok();

        let upstream_bytes = tokio::time::timeout(Duration::from_secs(2), upstream_h)
            .await
            .expect("upstream task")
            .expect("upstream join");
        // The denied DATA payload MUST NOT appear in what upstream
        // received.
        let upstream_str = String::from_utf8_lossy(&upstream_bytes);
        assert!(
            !upstream_str.contains("do-not-exfiltrate"),
            "denied-stream DATA leaked to upstream: {upstream_str:?}"
        );
        // The allowed stream's HEADERS DID reach upstream.
        // (The simplest end-to-end check: upstream got non-zero bytes
        // from the allowed stream.)
        assert!(!upstream_bytes.is_empty(), "upstream got no bytes");

        shutdown.store(true, Ordering::SeqCst);
        poke_shutdown(listen);
        let _ = tokio::time::timeout(Duration::from_secs(2), h).await;
    }

    #[tokio::test]
    async fn proxy_forwards_settings_and_window_update_verbatim() {
        let (upstream, upstream_h) = spawn_echo_upstream().await;
        let emitter = Arc::new(MemEmitter::default());
        let cfg = cfg_with(&["api.example.com"], upstream, 500);
        let (listen, shutdown, h) = spawn_proxy(cfg, emitter.clone()).await;

        // preface + SETTINGS + HEADERS(allow) + WINDOW_UPDATE on stream 0.
        // WINDOW_UPDATE: type=0x08, length=4, flags=0, stream id=0,
        // payload = 4-byte window-size-increment (32-bit BE).
        let mut bytes = h2::HTTP2_PREFACE.to_vec();
        bytes.extend_from_slice(&h2::test_helpers::empty_settings_frame());
        bytes.extend_from_slice(&h2::test_helpers::headers_frame_on_stream(
            &h2::test_helpers::hpack_literal_indexed_name(1, "api.example.com"),
            1,
        ));
        // WINDOW_UPDATE frame: 4-byte payload (window-size-increment = 1024).
        let mut wu = h2::test_helpers::frame_header(4, 0x08, 0x00, 0);
        wu.extend_from_slice(&1024u32.to_be_bytes());
        bytes.extend_from_slice(&wu);

        let mut s = TcpStream::connect(listen).await.unwrap();
        s.write_all(&bytes).await.unwrap();
        s.shutdown().await.ok();

        let upstream_bytes = tokio::time::timeout(Duration::from_secs(2), upstream_h)
            .await
            .expect("upstream task")
            .expect("upstream join");
        // Upstream sees the SETTINGS, HEADERS, AND the WINDOW_UPDATE
        // verbatim. Asserting full equality is the strongest possible
        // shape check: every byte of the input arrived.
        assert_eq!(upstream_bytes, bytes);

        shutdown.store(true, Ordering::SeqCst);
        poke_shutdown(listen);
        let _ = tokio::time::timeout(Duration::from_secs(2), h).await;
    }
}