sozu-lib 2.1.0

sozu library to build hot reconfigurable HTTP reverse proxies
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
//! HPACK decode + pseudo-header validation + RFC 9218 priority parsing.
//!
//! Lifts decoded HPACK blocks into the Kawa request/response shape used by
//! the rest of the stack, enforces pseudo-header ordering, the per-stream
//! trailer budget, and emits the rejection metrics surfaced in
//! `doc/configure.md`. Owns the priority extraction path consumed by the H2
//! `Prioriser`.

use std::{borrow::Cow, io::Write, str::from_utf8};

use kawa::{
    Block, BodySize, Flags, Kind, Pair, ParsingPhase, StatusLine, Store, Version,
    h1::ParserCallbacks, repr::Slice,
};
use sozu_command::logging::ansi_palette;

use crate::metrics::names;
use crate::{
    pool::Checkout,
    protocol::{
        http::parser::compare_no_case,
        mux::{
            GenericHttpStream, StreamId,
            h2::Prioriser,
            parser::{H2Error, PriorityPart},
        },
    },
};

/// Module-level prefix used on every log line emitted from the pkawa H2
/// converter. Pkawa operates on raw HPACK blocks without direct session
/// context, so a single `MUX-PKAWA` label is used, colored bold bright-white
/// (uniform across every protocol) when the logger supports ANSI.
macro_rules! log_module_context {
    () => {{
        let (open, reset, _, _, _) = ansi_palette();
        format!("{open}MUX-PKAWA{reset}\t >>>", open = open, reset = reset)
    }};
}

/// QW7 helper: dispatch a request pseudo-header (`:method`, `:scheme`,
/// `:path`, `:authority`) through `store_pseudo_header`, recording the
/// per-reason rejection metric and flipping `invalid_headers` on
/// failure. The four call sites in `handle_header` differ only by the
/// destination identifier; the macro keeps the dispatch shape uniform
/// so a future fifth pseudo-header inherits both the reject metric and
/// the invalid-flag plumbing automatically.
macro_rules! store_or_reject {
    ($field:expr, $regular:expr, $kawa:expr, $value:expr, $invalid:expr) => {
        match store_pseudo_header(&$field, $regular, $kawa, &$value) {
            Ok(s) => $field = s,
            Err(reason) => {
                metric_reject(reason);
                *$invalid = true;
            }
        }
    };
}

/// Per-trailer-block byte cap (trailer carve-out). HEADERS and trailers
/// run independent budget counters against
/// `SETTINGS_MAX_HEADER_LIST_SIZE`, so without a tighter trailer-only
/// ceiling the effective per-stream cap doubles. Real-world gRPC trailer
/// blocks observed in production are 1–4 KB; 8 KiB leaves comfortable
/// headroom while denying a peer the chance to spend a second
/// `MAX_HEADER_LIST_SIZE` worth of bytes after the request HEADERS were
/// already accepted. True cumulative-per-stream tracking is a follow-up
/// (it requires adding a `Stream::cumulative_header_bytes` field plumbed
/// through every HEADERS / CONTINUATION / trailer entry point).
pub const MAX_TRAILER_BYTES: usize = 8 * 1024;

/// Returns true if the header name contains any uppercase ASCII letter (A-Z).
/// RFC 9113 section 8.2 requires all header field names to be lowercase in HTTP/2.
#[cfg(test)]
fn has_uppercase_ascii(name: &[u8]) -> bool {
    name.iter().any(|b| b.is_ascii_uppercase())
}

/// Returns true if the byte is a valid HTTP token character (tchar per RFC 9110 §5.6.2).
/// ```text
/// tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." /
///         DIGIT / "^" / "_" / "`" / ALPHA / "|" / "~"
/// ```
fn is_tchar(b: u8) -> bool {
    matches!(
        b,
        b'!' | b'#'
            | b'$'
            | b'%'
            | b'&'
            | b'\''
            | b'*'
            | b'+'
            | b'-'
            | b'.'
            | b'0'..=b'9'
            | b'A'..=b'Z'
            | b'^'
            | b'_'
            | b'`'
            | b'a'..=b'z'
            | b'|'
            | b'~'
    )
}

/// Returns true if the header name contains any byte that is not a valid
/// lowercase HTTP token character. In HTTP/2, field names must be lowercase
/// tokens (RFC 9113 §8.2, RFC 9110 §5.6.2). Non-token bytes — CTLs (`\r\n`),
/// space, and separators like `:` — flow verbatim through H1 serialization
/// and enable request smuggling (CWE-93, CWE-444).
fn has_invalid_name_byte(name: &[u8]) -> bool {
    name.iter().any(|&b| b.is_ascii_uppercase() || !is_tchar(b))
}

/// Returns true if the header name is a connection-specific header field
/// that MUST NOT appear in HTTP/2 (RFC 9113 section 8.2.2).
pub(super) fn is_connection_specific_header(name: &[u8]) -> bool {
    match name.first() {
        Some(b'c' | b'C') => compare_no_case(name, b"connection"),
        Some(b'p' | b'P') => compare_no_case(name, b"proxy-connection"),
        Some(b't' | b'T') => compare_no_case(name, b"transfer-encoding"),
        Some(b'u' | b'U') => compare_no_case(name, b"upgrade"),
        Some(b'k' | b'K') => compare_no_case(name, b"keep-alive"),
        _ => false,
    }
}

/// Returns true if the TE header has a value other than "trailers".
/// RFC 9113 section 8.2.2: the only acceptable value for TE in HTTP/2 is "trailers".
fn is_invalid_te_value(value: &[u8]) -> bool {
    !compare_no_case(value, b"trailers")
}

/// Strip the ``:port`` suffix (if any) from an ``authority``/``host`` value.
///
/// This does not validate that the remaining segment is a legal host — it is only
/// used for the RFC 9113 §8.3.1 equivalence check between a literal ``host``
/// header and the ``:authority`` pseudo-header when both are present.
fn strip_port(value: &[u8]) -> &[u8] {
    let in_len = value.len();
    // Do not strip port from IPv6 literals (e.g., [::1]:8080)
    if value.contains(&b'[') {
        // Bracketed IPv6: look for "]:port"
        let stripped = match value.iter().rposition(|&b| b == b']') {
            Some(bracket) => {
                if value.get(bracket + 1) == Some(&b':')
                    && bracket + 2 < value.len()
                    && value[bracket + 2..].iter().all(|b| b.is_ascii_digit())
                {
                    &value[..bracket + 1]
                } else {
                    value
                }
            }
            None => value,
        };
        // Stripping only ever removes a trailing `:port` suffix — the result
        // is a prefix of the input and never longer than what we started with.
        debug_assert!(
            stripped.len() <= in_len,
            "strip_port must not grow its input (IPv6 path)"
        );
        debug_assert!(
            stripped.as_ptr() == value.as_ptr(),
            "strip_port returns a prefix of value (shares its start)"
        );
        return stripped;
    }
    let stripped = match value.iter().rposition(|&b| b == b':') {
        Some(i) if i + 1 < value.len() && value[i + 1..].iter().all(|b| b.is_ascii_digit()) => {
            &value[..i]
        }
        _ => value,
    };
    // A stripped value is strictly shorter (we dropped at least `:` + 1 digit);
    // an unstripped value is byte-identical. Either way it is a prefix.
    debug_assert!(
        stripped.len() <= in_len,
        "strip_port must not grow its input"
    );
    debug_assert!(
        stripped.len() == in_len || stripped.len() + 2 <= in_len,
        "a real port strip removes at least a colon and one digit"
    );
    stripped
}

/// Case-insensitively compare a literal ``host`` header value to an
/// ``:authority`` pseudo-header value, respecting port semantics.
///
/// RFC 9113 §8.3.1: when both are present they must identify the same origin.
/// Per RFC 6454 §5, different explicit ports mean different origins.
/// When only one side carries a port (implicit default), compare hostnames only.
fn host_matches_authority(host: &[u8], authority: &[u8]) -> bool {
    // Fast path: exact case-insensitive match (covers identical port or both absent)
    if compare_no_case(host, authority) {
        return true;
    }
    // If both have explicit ports but differ, the origins differ.
    let host_stripped = strip_port(host);
    let auth_stripped = strip_port(authority);
    // strip_port only ever drops a trailing `:port` suffix, so the stripped
    // forms are no longer than their inputs; len inequality is the port flag.
    debug_assert!(
        host_stripped.len() <= host.len(),
        "stripped host cannot grow"
    );
    debug_assert!(
        auth_stripped.len() <= authority.len(),
        "stripped authority cannot grow"
    );
    let host_has_port = host_stripped.len() != host.len();
    let auth_has_port = auth_stripped.len() != authority.len();
    if host_has_port && auth_has_port {
        // Both have explicit ports but the full values differ → different origins.
        return false;
    }
    // One side has a port, the other doesn't (implicit default) → compare hostnames.
    compare_no_case(host_stripped, auth_stripped)
}

/// Like `has_invalid_value_byte` but also rejects HTAB (0x09), which is
/// allowed in regular header values (RFC 9110 §5.5) but not in pseudo-header
/// values that end up in the H1 request-line (RFC 9112 §3).
fn has_invalid_pseudo_value_byte(value: &[u8]) -> bool {
    value.iter().any(|&b| matches!(b, 0x00..=0x1F | 0x7F))
}

/// Returns true if the value contains any byte forbidden in HTTP field values
/// (RFC 9110 §5.5 + RFC 9113 §8.2.1): NUL, CR, LF, DEL, and other C0 controls.
/// HTAB (0x09) and visible ASCII (0x20..=0x7E) plus obs-text (0x80..=0xFF) are allowed.
///
/// Without this check, HPACK-decoded bytes containing `\r\n` flow verbatim through
/// kawa's H1 serializer and reach backends as injected headers — request smuggling
/// (CWE-93, CWE-444) on H2→H1 traffic.
#[cfg(test)]
fn has_invalid_value_byte(value: &[u8]) -> bool {
    value
        .iter()
        .any(|&b| matches!(b, 0x00..=0x08 | 0x0A..=0x1F | 0x7F))
}

/// Bounded enumeration of reasons a single HPACK header may be rejected by the
/// H2 → H1 converter. Each variant maps 1:1 to a metric label suffix exposed
/// as `h2.headers.rejected.<reason>` so SOC dashboards can break down rejection
/// pressure by root cause without unbounded cardinality.
///
/// New variants must update the corresponding row in `doc/configure.md`
/// (HTTP/2 header validation subsection).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum RejectReason {
    /// Header name contains an invalid byte (uppercase, CTL, separator, space).
    /// CWE-93 — turns into request smuggling once the H1 serializer emits the
    /// raw bytes on the wire.
    InvalidNameByte,
    /// Connection-specific header that MUST NOT appear in HTTP/2
    /// (RFC 9113 §8.2.2): `connection`, `proxy-connection`, `transfer-encoding`,
    /// `upgrade`, `keep-alive`.
    ConnectionSpecificHeader,
    /// `te` header with any value other than `trailers` (RFC 9113 §8.2.2).
    TeNotTrailers,
    /// CR or LF byte in a field value — request-smuggling vector
    /// (CWE-444). NUL is reported separately via `NulInValue`.
    CrlfInValue,
    /// NUL byte (0x00) in a field value. Distinct from CR/LF for triage:
    /// many smuggling toolchains pad with NULs first.
    NulInValue,
    /// Pseudo-header value contains a CTL or DEL byte that would corrupt the
    /// H1 request line (RFC 9112 §3 — pseudo values are stricter than regular
    /// field values: HTAB is also forbidden).
    OversizedPseudoValue,
    /// `:method` value contains a non-token byte (RFC 9110 §9 method = token).
    /// Distinct from name-byte rejection because the byte is in the *value*,
    /// not the name.
    InvalidMethod,
    /// `:scheme` value is not exactly `http` or `https` (RFC 9113 §8.3.1).
    InvalidScheme,
    /// `:path` value contains a `#` (fragment identifier — RFC 9112 §3.2 forbids
    /// fragments in request-targets).
    InvalidPath,
    /// `:status` value is not exactly three ASCII digits (RFC 9113 §8.3.2).
    InvalidStatus,
    /// Two `content-length` headers with disagreeing values, or a
    /// `transfer-encoding`/`content-length` conflict surfaced via the same
    /// validation hook.
    ClTeConflict,
    /// `content-length` value is missing, empty, or contains non-digit bytes —
    /// already disagrees with itself before any second header arrives.
    DuplicateCl,
    /// A pseudo-header arrived twice (`:method` after `:method`, etc. —
    /// RFC 9113 §8.3 requires uniqueness).
    DuplicatePseudo,
    /// A pseudo-header arrived AFTER a regular header (RFC 9113 §8.3 requires
    /// pseudos to precede all regular fields).
    PseudoAfterRegular,
    /// A `:`-prefixed name that is not one of the known request/response
    /// pseudo-headers (RFC 9113 §8.3 — no extension pseudos accepted here).
    UnknownPseudo,
    /// A pseudo-header arrived with a zero-length value (RFC 9113 §8.3.1
    /// forbids empty `:path`/`:method`/`:authority`/`:scheme`/`:status`).
    EmptyPseudo,
    /// The HPACK block's accounted size (name + value + the RFC 9113 §6.5.2
    /// 32-octet/field overhead) exceeded `SETTINGS_MAX_HEADER_LIST_SIZE` — the
    /// indexed-reference "header bomb" byte budget. Stream-level
    /// `RST_STREAM(ENHANCE_YOUR_CALM)`.
    HeaderListOverBudget,
    /// The block's materialized header-field count (cookie crumbs counted
    /// individually, RFC 9113 §8.2.3) exceeded `h2_max_header_fields` — the
    /// per-block field-count cap. Stream-level `RST_STREAM(ENHANCE_YOUR_CALM)`.
    TooManyHeaderFields,
}

/// Compile-time mapping from `(prefix, RejectReason)` to a static metric key.
///
/// Same `concat!`-based pattern as `h2_error_metric_key!` in `mux/h2.rs`:
/// the literal is materialised at compile time so the statsd drain can store
/// it as `&'static str` without a per-rejection allocation. Adding a new
/// `RejectReason` variant fails the build inside this match — the metric
/// breakdown stays in lock-step with the bounded enum (and with
/// `doc/configure.md`'s HTTP/2 header validation table).
macro_rules! reject_metric_key {
    ($prefix:literal, $reason:expr) => {
        match $reason {
            RejectReason::InvalidNameByte => concat!($prefix, ".invalid_name_byte"),
            RejectReason::ConnectionSpecificHeader => {
                concat!($prefix, ".connection_specific_header")
            }
            RejectReason::TeNotTrailers => concat!($prefix, ".te_not_trailers"),
            RejectReason::CrlfInValue => concat!($prefix, ".crlf_in_value"),
            RejectReason::NulInValue => concat!($prefix, ".nul_in_value"),
            RejectReason::OversizedPseudoValue => concat!($prefix, ".oversized_pseudo_value"),
            RejectReason::InvalidMethod => concat!($prefix, ".invalid_method"),
            RejectReason::InvalidScheme => concat!($prefix, ".invalid_scheme"),
            RejectReason::InvalidPath => concat!($prefix, ".invalid_path"),
            RejectReason::InvalidStatus => concat!($prefix, ".invalid_status"),
            RejectReason::ClTeConflict => concat!($prefix, ".cl_te_conflict"),
            RejectReason::DuplicateCl => concat!($prefix, ".duplicate_cl"),
            RejectReason::DuplicatePseudo => concat!($prefix, ".duplicate_pseudo"),
            RejectReason::PseudoAfterRegular => concat!($prefix, ".pseudo_after_regular"),
            RejectReason::UnknownPseudo => concat!($prefix, ".unknown_pseudo"),
            RejectReason::EmptyPseudo => concat!($prefix, ".empty_pseudo"),
            RejectReason::HeaderListOverBudget => concat!($prefix, ".header_list_size"),
            RejectReason::TooManyHeaderFields => concat!($prefix, ".header_fields"),
        }
    };
}

/// Increment the per-reason counter `h2.headers.rejected.<reason>` and the
/// per-rejection-event counter `h2.headers.rejected.total`. The total is the
/// coarse roll-up dashboards alert on; the per-reason counter is the breakdown
/// SOC uses to triage. Emitting both per call (rather than total once per
/// request) keeps the totals in lockstep with the breakdown — easier to
/// reconcile when a single request piles up several rejections.
fn metric_reject(reason: RejectReason) {
    incr!(names::h2::HEADERS_REJECTED_TOTAL);
    incr!(reject_metric_key!("h2.headers.rejected", reason));
}

/// Classify a header rejected by `is_invalid_h2_header`. Splits the original
/// boolean check into the bounded `RejectReason` enum so the caller can emit
/// the exact per-reason counter. Order matches `is_invalid_h2_header` so the
/// observable validation policy is unchanged.
fn classify_invalid_h2_header(name: &[u8], value: &[u8]) -> Option<RejectReason> {
    if name.is_empty() {
        // An empty name has no further byte to point at — bucket under
        // `invalid_name_byte`; the original check treated it as a name issue.
        return Some(RejectReason::InvalidNameByte);
    }
    if name[0] != b':' && has_invalid_name_byte(name) {
        return Some(RejectReason::InvalidNameByte);
    }
    if is_connection_specific_header(name) {
        return Some(RejectReason::ConnectionSpecificHeader);
    }
    if compare_no_case(name, b"te") && is_invalid_te_value(value) {
        return Some(RejectReason::TeNotTrailers);
    }
    if let Some(reason) = classify_invalid_value_byte(value) {
        return Some(reason);
    }
    None
}

/// Sub-classify which forbidden value byte caused a rejection. Distinguishes
/// NUL from CR/LF/other-CTL because the two have different threat profiles
/// (NUL → C string truncation, CR/LF → smuggling).
fn classify_invalid_value_byte(value: &[u8]) -> Option<RejectReason> {
    let mut saw_crlf = false;
    let mut saw_nul = false;
    for &b in value {
        match b {
            0x00 => saw_nul = true,
            0x0A | 0x0D => saw_crlf = true,
            0x01..=0x08 | 0x0B | 0x0C | 0x0E..=0x1F | 0x7F => {
                return Some(RejectReason::CrlfInValue);
            }
            _ => {}
        }
    }
    // CR/LF takes precedence over NUL when both are present (more dangerous
    // smuggling vector), but the result is non-None iff at least one forbidden
    // byte was seen — never the other way around.
    let result = if saw_crlf {
        Some(RejectReason::CrlfInValue)
    } else if saw_nul {
        Some(RejectReason::NulInValue)
    } else {
        None
    };
    debug_assert!(
        result.is_some() == (saw_crlf || saw_nul),
        "classify must reject iff a CR/LF or NUL byte was observed"
    );
    debug_assert!(
        !(saw_crlf && result != Some(RejectReason::CrlfInValue)),
        "CR/LF must classify as CrlfInValue even when NUL is also present"
    );
    result
}

/// Thin wrapper kept for tests and any code path that just needs the boolean.
/// New code should call `classify_invalid_h2_header` to surface the exact
/// rejection reason for the per-reason counter.
#[cfg(test)]
fn is_invalid_h2_header(name: &[u8], value: &[u8]) -> bool {
    classify_invalid_h2_header(name, value).is_some()
}

/// Validate and set Content-Length, returning false if it conflicts with a prior value
/// (RFC 9110 §8.6: multiple disagreeing Content-Length values are malformed).
fn set_content_length(body_size: &mut BodySize, length: usize) -> bool {
    let before = *body_size;
    let accepted = match *body_size {
        BodySize::Length(existing) if existing != length => false,
        _ => {
            *body_size = BodySize::Length(length);
            true
        }
    };
    // On rejection the prior framing must be untouched; on acceptance the body
    // size must now equal the value we were asked to record (RFC 9110 §8.6
    // forbids a second, disagreeing Content-Length).
    debug_assert!(
        accepted || *body_size == before,
        "rejected content-length must leave body_size unchanged"
    );
    debug_assert!(
        !accepted || *body_size == BodySize::Length(length),
        "accepted content-length must set body_size to exactly Length(length)"
    );
    accepted
}

/// Store a pseudo-header value into kawa storage.
///
/// Returns `Ok(Store::Slice)` on success, or `Err(RejectReason)` describing
/// which validity rule the pseudo violated. Callers should set
/// `invalid_headers = true` and increment the per-reason counter on `Err`.
///
/// Reasons:
/// - `DuplicatePseudo` — `dest` is already populated (RFC 9113 §8.3 uniqueness)
/// - `PseudoAfterRegular` — a regular header arrived first (RFC 9113 §8.3 ordering)
/// - `EmptyPseudo` — zero-length value (RFC 9113 §8.3.1 forbids empty pseudos)
/// - `OversizedPseudoValue` — CTL/DEL byte that would corrupt the H1 request
///   line. Empty values are rejected before storing because
///   `Store::Slice { len: 0 }` is NOT `Store::is_empty()`, so the presence
///   checks after the decode loop would silently accept a zero-length pseudo.
fn store_pseudo_header(
    dest: &Store,
    regular_headers: bool,
    kawa: &mut GenericHttpStream,
    value: &[u8],
) -> Result<Store, RejectReason> {
    if !dest.is_empty() {
        return Err(RejectReason::DuplicatePseudo);
    }
    if regular_headers {
        return Err(RejectReason::PseudoAfterRegular);
    }
    if value.is_empty() {
        return Err(RejectReason::EmptyPseudo);
    }
    if has_invalid_pseudo_value_byte(value) {
        return Err(RejectReason::OversizedPseudoValue);
    }
    let start = kawa.storage.end as u32;
    let end_before = kawa.storage.end;
    if kawa.storage.write_all(value).is_err() {
        // Storage exhaustion: report as `oversized_pseudo_value` since a
        // pseudo whose bytes don't fit is functionally an oversized payload
        // for the configured buffer pool. Keeps the counter cardinality
        // bounded without inventing a transport-failure reason.
        return Err(RejectReason::OversizedPseudoValue);
    }
    // A successful write_all is all-or-nothing: storage advanced by exactly the
    // value length, so the slice we are about to mint lies fully inside the
    // written region (start..end). Reaching here also means the value is
    // non-empty (the guard above rejected `value.is_empty()`).
    debug_assert_eq!(
        kawa.storage.end,
        end_before + value.len(),
        "pseudo store must advance storage.end by exactly value.len()"
    );
    debug_assert!(
        start as usize + value.len() <= kawa.storage.end,
        "pseudo slice must stay within the written storage region"
    );
    debug_assert!(
        !value.is_empty(),
        "empty pseudo value must already be rejected"
    );
    Ok(Store::Slice(Slice {
        start,
        len: value.len() as u32,
    }))
}

/// Write a regular (non-pseudo) header into kawa storage and push a `Block::Header`.
///
/// Also handles `content-length` validation: if the header is `content-length`, its
/// value is parsed and checked for consistency with any previously seen value.
///
/// Returns `Ok(())` on success, or `Err(RejectReason)` describing which validity
/// rule failed (caller should set `invalid_headers = true` and emit the
/// matching counter):
///
/// - `DuplicateCl` — `content-length` empty / non-digit / parse failure
/// - `ClTeConflict` — second `content-length` disagrees with the first one
/// - `OversizedPseudoValue` — kawa storage write failed (buffer exhausted)
fn write_regular_header(
    kawa: &mut GenericHttpStream,
    key: &[u8],
    value: &[u8],
) -> Result<(), RejectReason> {
    let len_key = key.len() as u32;
    let len_val = value.len() as u32;
    let start = kawa.storage.end as u32;
    let end_before_val = kawa.storage.end;
    if kawa.storage.write_all(value).is_err() {
        return Err(RejectReason::OversizedPseudoValue);
    }
    // All-or-nothing write_all: storage.end advanced by exactly the value length.
    debug_assert_eq!(
        kawa.storage.end,
        end_before_val + value.len(),
        "regular header value write must advance storage.end by value.len()"
    );
    let val = Store::Slice(Slice {
        start,
        len: len_val,
    });
    if compare_no_case(key, b"content-length") {
        // RFC 9110 §8.6: Content-Length is 1*DIGIT. `usize::from_str` would
        // accept leading whitespace, a leading `+`, or trailing garbage — all
        // of which create a parser-divergence vector against backends. Require
        // every byte to be an ASCII digit before parsing.
        if value.is_empty() || !value.iter().all(|b| b.is_ascii_digit()) {
            return Err(RejectReason::DuplicateCl);
        }
        if let Some(length) = from_utf8(value).ok().and_then(|v| v.parse::<usize>().ok()) {
            if !set_content_length(&mut kawa.body_size, length) {
                return Err(RejectReason::ClTeConflict);
            }
        } else {
            return Err(RejectReason::DuplicateCl);
        }
    }
    let end_before_key = kawa.storage.end;
    if kawa.storage.write_all(key).is_err() {
        return Err(RejectReason::OversizedPseudoValue);
    }
    // The key was appended immediately after the value, so it starts at
    // `start + len_val` and the two slices tile [start, end) contiguously
    // with no gap and no overlap.
    debug_assert_eq!(
        kawa.storage.end,
        end_before_key + key.len(),
        "regular header key write must advance storage.end by key.len()"
    );
    debug_assert_eq!(
        end_before_key as u32,
        start + len_val,
        "key must begin exactly where the value ended (contiguous, no gap)"
    );
    let key = Store::Slice(Slice {
        start: start + len_val,
        len: len_key,
    });
    debug_assert!(
        (start + len_val + len_key) as usize <= kawa.storage.end,
        "key+val slices must stay within the written storage region"
    );
    kawa.push_block(Block::Header(Pair { key, val }));
    Ok(())
}

/// Trims leading and trailing OWS (SP / HTAB per RFC 9110 §5.6.3) from a byte slice.
fn trim_ows(input: &[u8]) -> &[u8] {
    let start = input
        .iter()
        .position(|&b| b != b' ' && b != b'\t')
        .unwrap_or(input.len());
    let end = input
        .iter()
        .rposition(|&b| b != b' ' && b != b'\t')
        .map_or(start, |p| p + 1);
    &input[start..end]
}

/// Parse an RFC 9218 `priority` header value into (urgency, incremental).
///
/// The structured field format is: `u=N, i` or `u=N` or just `i`.
/// - `u=N`: urgency, integer 0-7 (default 3 per RFC 9218 section 4)
/// - `i`: incremental flag (default false)
///
/// Values outside the valid range are clamped (urgency to 0-7).
/// Malformed tokens are silently ignored, falling back to defaults.
///
/// Re-used by the RFC 9218 §7.1 PRIORITY_UPDATE frame handler
/// (`h2::ConnectionH2::handle_priority_update_frame`) to decode the
/// priority field value payload — same wire format as the request header.
pub(super) fn parse_rfc9218_priority(value: &[u8]) -> (u8, bool) {
    let mut urgency: u8 = 3; // RFC 9218 §4: default urgency
    let mut incremental = false;

    for token in value.split(|&b| b == b',') {
        let token = trim_ows(token);
        if token.is_empty() {
            continue;
        }
        if token.len() >= 3 && token[0] == b'u' && token[1] == b'=' {
            // Parse `u=N` where N may be a multi-digit value (clamped to 0-7)
            if let Ok(s) = std::str::from_utf8(&token[2..]) {
                if let Ok(n) = s.parse::<u8>() {
                    urgency = n.min(7);
                    // The `.min(7)` clamp is the only writer of `urgency` after
                    // the default; it can never leave the RFC 9218 §4 range.
                    debug_assert!(urgency <= 7, "clamped urgency must stay within 0..=7");
                }
            }
        } else if token == b"i" || token == b"i=?1" {
            incremental = true;
        } else if token == b"i=?0" {
            incremental = false;
        }
    }

    // RFC 9218 §4: urgency is a 3-bit field (0..=7). The default (3) and the
    // clamped parse path are the only writers, so this always holds — the
    // Prioriser downstream relies on it for its urgency-bucket array indexing.
    debug_assert!(
        urgency <= 7,
        "parse_rfc9218_priority must yield an urgency within the RFC 9218 range"
    );
    (urgency, incremental)
}

/// Run the HPACK decoder while tracking the cumulative decoded header-list size
/// against `max_decoded_bytes` (RFC 9113 §6.5.2 SETTINGS_MAX_HEADER_LIST_SIZE).
///
/// `per_header` is invoked for every successfully decoded `(name, value)` pair
/// that fits within the budget; it may set its `&mut bool` argument to mark the
/// stream as carrying invalid headers, in which case subsequent pairs are still
/// decoded (to keep HPACK dynamic-table state in sync) but skipped.
///
/// Returns the final value of the `invalid_headers` flag so the caller can
/// combine it with kind-specific validity checks (e.g. mandatory pseudo-headers).
fn decode_headers_with_budget<F>(
    decoder: &mut loona_hpack::Decoder<'static>,
    input: &[u8],
    max_decoded_bytes: usize,
    max_header_fields: u32,
    mut per_header: F,
) -> Result<bool, (H2Error, bool)>
where
    F: FnMut(Cow<[u8]>, Cow<[u8]>, &mut bool, &mut usize),
{
    let max_header_fields = max_header_fields as usize;
    let mut invalid_headers = false;
    let mut budget_exceeded = false;
    let mut field_limit_exceeded = false;
    let mut field_count: usize = 0;
    let mut decoded_bytes: usize = 0;
    let decode_status = decoder.decode_with_cb(input, |k, v| {
        if invalid_headers || budget_exceeded || field_limit_exceeded {
            return;
        }
        let bytes_before = decoded_bytes;
        // RFC 9113 §6.5.2: the size accounted against SETTINGS_MAX_HEADER_LIST_SIZE
        // is the name + value octets PLUS a 32-octet per-field overhead. The
        // overhead is what bounds the field count under a fixed byte budget;
        // omitting it lets an HPACK indexed-reference bomb (thousands of 1-byte
        // indexed references) materialize ~33× more fields than the limit intends.
        decoded_bytes = decoded_bytes
            .saturating_add(k.len())
            .saturating_add(v.len())
            .saturating_add(crate::protocol::mux::h2::HEADER_FIELD_SIZE_OVERHEAD);
        // The running header-list size only ever grows as pairs are admitted;
        // it must never shrink between callbacks (RFC 9113 §6.5.2 accounting).
        debug_assert!(
            decoded_bytes >= bytes_before,
            "decoded header-list size must be monotonic non-decreasing"
        );
        if decoded_bytes > max_decoded_bytes {
            budget_exceeded = true;
            return;
        }
        // We only reach per_header for pairs that fit the budget; the running
        // total stays at or below the negotiated MAX_HEADER_LIST_SIZE here.
        debug_assert!(
            decoded_bytes <= max_decoded_bytes,
            "admitted pairs must keep the running size within the budget"
        );
        // Cap the COUNT of materialized header fields (cf. nginx `max_headers`,
        // Apache `LimitRequestFields`): the bomb's real cost is one `Pair` of
        // per-entry bookkeeping per field, not the decoded byte size.
        field_count += 1;
        if field_count > max_header_fields {
            field_limit_exceeded = true;
            return;
        }
        if let Some(reason) = classify_invalid_h2_header(&k, &v) {
            metric_reject(reason);
            invalid_headers = true;
            return;
        }
        per_header(k, v, &mut invalid_headers, &mut field_count);
        // The cookie branch (RFC 9113 §8.2.3) expands one HPACK field into many
        // jar crumbs and bumps `field_count` for each crumb beyond the first
        // (the first crumb is already counted by the `field_count += 1` above,
        // so a cookie costs exactly N); re-check after the call so a crumb-packed
        // cookie header cannot blow past the cap.
        if field_count > max_header_fields {
            field_limit_exceeded = true;
        }
    });
    if let Err(error) = decode_status {
        error!("{} INVALID FRAGMENT: {:?}", log_module_context!(), error);
        return Err((H2Error::CompressionError, true));
    }
    // budget_exceeded is set exactly when the running total crossed the cap; if
    // it stayed clear the whole decode fit inside MAX_HEADER_LIST_SIZE.
    debug_assert!(
        budget_exceeded || decoded_bytes <= max_decoded_bytes,
        "a non-overflowing decode must end at or below the budget"
    );
    if budget_exceeded {
        metric_reject(RejectReason::HeaderListOverBudget);
        error!(
            "{} HPACK decoded header size {} exceeds MAX_HEADER_LIST_SIZE {}",
            log_module_context!(),
            decoded_bytes,
            max_decoded_bytes
        );
        return Err((H2Error::EnhanceYourCalm, false));
    }
    if field_limit_exceeded {
        metric_reject(RejectReason::TooManyHeaderFields);
        error!(
            "{} HPACK header field count {} exceeds max_header_fields {}",
            log_module_context!(),
            field_count,
            max_header_fields
        );
        return Err((H2Error::EnhanceYourCalm, false));
    }
    // Reaching the Ok branch means we neither errored nor overflowed the budget,
    // so the final accounted size is within the negotiated cap.
    debug_assert!(
        decoded_bytes <= max_decoded_bytes,
        "successful decode must report a header-list size within the budget"
    );
    Ok(invalid_headers)
}

#[allow(clippy::too_many_arguments)]
pub fn handle_header<C>(
    decoder: &mut loona_hpack::Decoder<'static>,
    prioriser: &mut Prioriser,
    stream_id: StreamId,
    kawa: &mut GenericHttpStream,
    input: &[u8],
    end_stream: bool,
    callbacks: &mut C,
    max_header_list_size: u32,
    max_header_fields: u32,
    elide_x_real_ip: bool,
) -> Result<(), (H2Error, bool)>
where
    C: ParserCallbacks<Checkout>,
{
    if !kawa.is_initial() {
        return handle_trailer(
            kawa,
            input,
            end_stream,
            decoder,
            max_header_list_size,
            max_header_fields,
            elide_x_real_ip,
        );
    }
    kawa.push_block(Block::StatusLine);
    let max_decoded_bytes = max_header_list_size as usize;
    kawa.detached.status_line = match kawa.kind {
        Kind::Request => {
            let mut method = Store::Empty;
            let mut authority = Store::Empty;
            let mut path = Store::Empty;
            let mut scheme = Store::Empty;
            let mut regular_headers = false;
            let mut cookies_added = false;
            // RFC 9113 §8.3.1: a literal ``host`` header may appear, but if it
            // does it MUST identify the same origin as ``:authority``. We defer
            // the comparison to after the decode loop (authority may arrive in
            // any order) and drop the literal header so the H1 serializer emits
            // exactly one ``Host:`` line from the authority pseudo-header.
            let mut host_value: Option<Vec<u8>> = None;
            let mut host_conflict = false;
            let invalid_headers = decode_headers_with_budget(
                decoder,
                input,
                max_decoded_bytes,
                max_header_fields,
                |k, v, invalid_headers, field_count| {
                    if compare_no_case(&k, b":method") {
                        // RFC 9110 §9: method = token. Validate every byte is
                        // a tchar — spaces, delimiters, and CTLs in the method
                        // reach the H1 request line and can smuggle extra path
                        // segments or headers to backends.
                        if !v.iter().all(|&b| is_tchar(b)) {
                            metric_reject(RejectReason::InvalidMethod);
                            *invalid_headers = true;
                            return;
                        }
                        store_or_reject!(method, regular_headers, kawa, v, invalid_headers);
                    } else if compare_no_case(&k, b":scheme") {
                        // RFC 9113 §8.3.1: the HPACK lowercase rule means a
                        // valid :scheme arrives exactly as "http" or "https".
                        // Anything else is a smuggling / SSRF vector.
                        if v.as_ref() != b"http" && v.as_ref() != b"https" {
                            metric_reject(RejectReason::InvalidScheme);
                            *invalid_headers = true;
                            return;
                        }
                        store_or_reject!(scheme, regular_headers, kawa, v, invalid_headers);
                    } else if compare_no_case(&k, b":path") {
                        // RFC 9112 §3.2: fragment identifiers (`#`) are
                        // prohibited in request-targets.
                        if v.contains(&b'#') {
                            metric_reject(RejectReason::InvalidPath);
                            *invalid_headers = true;
                            return;
                        }
                        store_or_reject!(path, regular_headers, kawa, v, invalid_headers);
                    } else if compare_no_case(&k, b":authority") {
                        store_or_reject!(authority, regular_headers, kawa, v, invalid_headers);
                    } else if k.starts_with(b":") {
                        metric_reject(RejectReason::UnknownPseudo);
                        *invalid_headers = true;
                    } else if compare_no_case(&k, b"cookie") {
                        regular_headers = true;
                        // RFC 9113 §8.2.3: When converting H2 to H1, multiple cookie
                        // header fields MUST be concatenated into a single octet string
                        // using "; " as separator. We store each cookie-pair in the
                        // detached jar (same as the H1 parser) so that:
                        //  1. H1BlockConverter emits a single "Cookie: k1=v1; k2=v2" header
                        //  2. H2BlockConverter re-encodes each as a separate HPACK header
                        //  3. HttpContext::on_request_headers can find sticky session cookies
                        let mut first_crumb = true;
                        for cookie_pair in v.split(|&b| b == b';') {
                            let trimmed = trim_ows(cookie_pair);
                            if trimmed.is_empty() {
                                continue;
                            }
                            // Split on first '=' to separate cookie name and value
                            let (cookie_key, cookie_val) =
                                match trimmed.iter().position(|&b| b == b'=') {
                                    Some(eq_pos) => (&trimmed[..eq_pos], &trimmed[eq_pos + 1..]),
                                    None => (trimmed, &b""[..]),
                                };
                            // RFC 6265 §4.2.1 + RFC 9110 §5.5: cookie-name and
                            // cookie-value must not contain CTLs. Without this
                            // check, a crafted cookie can smuggle headers
                            // through kawa's H1 serializer. Validate BEFORE the
                            // field-count gate so a malformed crumb is still
                            // rejected as CrlfInValue/NulInValue rather than
                            // masked by the count cap.
                            if let Some(reason) = classify_invalid_value_byte(cookie_key)
                                .or_else(|| classify_invalid_value_byte(cookie_val))
                            {
                                metric_reject(reason);
                                *invalid_headers = true;
                                return;
                            }
                            // RFC 9113 §8.2.3 lets one HPACK cookie field expand
                            // into many crumbs, each materialized as a jar Pair.
                            // Count every crumb against the field cap and bail the
                            // moment it is crossed — BEFORE materializing the
                            // over-cap crumb (storage + jar Pair), so a crumb-packed
                            // cookie cannot amplify allocation (cf. Apache
                            // CVE-2026-49975 counting crumbs against
                            // LimitRequestFields). The outer `field_count += 1` in
                            // `decode_headers_with_budget` already counted the first
                            // crumb of this cookie HPACK field, so only crumbs 2..N
                            // add here — a cookie costs exactly N, not N+1.
                            if first_crumb {
                                first_crumb = false;
                            } else {
                                *field_count += 1;
                                if *field_count > max_header_fields as usize {
                                    return;
                                }
                            }
                            let key_start = kawa.storage.end as u32;
                            if kawa.storage.write_all(cookie_key).is_err() {
                                metric_reject(RejectReason::OversizedPseudoValue);
                                *invalid_headers = true;
                                return;
                            }
                            let key_len = cookie_key.len() as u32;
                            let val_start = kawa.storage.end as u32;
                            if kawa.storage.write_all(cookie_val).is_err() {
                                metric_reject(RejectReason::OversizedPseudoValue);
                                *invalid_headers = true;
                                return;
                            }
                            let val_len = cookie_val.len() as u32;
                            if !cookies_added {
                                kawa.push_block(Block::Cookies);
                                cookies_added = true;
                            }
                            kawa.detached.jar.push_back(Pair {
                                key: Store::Slice(Slice {
                                    start: key_start,
                                    len: key_len,
                                }),
                                val: Store::Slice(Slice {
                                    start: val_start,
                                    len: val_len,
                                }),
                            });
                        }
                    } else if compare_no_case(&k, b"host") {
                        // RFC 9113 §8.3.1: a literal ``host`` header is tolerated
                        // but only if it matches ``:authority``. We buffer the
                        // value here and reconcile after the decode loop — at
                        // which point authority is known regardless of order.
                        regular_headers = true;
                        if let Some(reason) = classify_invalid_value_byte(&v) {
                            metric_reject(reason);
                            *invalid_headers = true;
                            return;
                        }
                        match host_value {
                            Some(ref existing) if existing.as_slice() != v.as_ref() => {
                                // Multiple disagreeing `host` headers are
                                // malformed (RFC 9110 §7.2 / §5.3.1) — reject.
                                host_conflict = true;
                            }
                            Some(_) => {
                                // Duplicate identical `host:` headers are
                                // also malformed per RFC 9110 §7.2 ("a
                                // server MUST respond with a 400
                                // (Bad Request) status code to any HTTP/1.1
                                // request message that lacks a Host header
                                // field and to any request message that
                                // contains more than one Host header field
                                // value or has any Host header field value
                                // that is not a valid URI authority"). The
                                // identical-value short-circuit was lenient
                                // because two equal `host` values produce
                                // the same wire shape after normalisation,
                                // but the spec is strict on COUNT not on
                                // VALUE. Reject so request smuggling that
                                // relies on duplicate headers cannot hide
                                // behind value equality.
                                host_conflict = true;
                            }
                            None => host_value = Some(v.to_vec()),
                        }
                    } else {
                        regular_headers = true;
                        if let Err(reason) = write_regular_header(kawa, &k, &v) {
                            metric_reject(reason);
                            *invalid_headers = true;
                            return;
                        }
                        if compare_no_case(&k, b"priority") {
                            let (urgency, incremental) = parse_rfc9218_priority(&v);
                            prioriser.push_priority(
                                stream_id,
                                PriorityPart::Rfc9218 {
                                    urgency,
                                    incremental,
                                },
                            );
                        }
                    }
                },
            )?;
            // Post-decode :path form validation (deferred because :method may
            // arrive after :path in HPACK — RFC 9113 does not mandate ordering).
            // RFC 9112 §3.2 / RFC 9113 §8.3.1: for http/https URIs we accept
            // origin-form (starts with `/`) and — only when the method is
            // OPTIONS — asterisk-form (`*`).
            if let Some(path_data) = path.data_opt(kawa.storage.buffer()) {
                let is_asterisk = path_data == b"*";
                let starts_with_slash = path_data.first() == Some(&b'/');
                let method_is_options = method
                    .data_opt(kawa.storage.buffer())
                    .is_some_and(|m| m == b"OPTIONS");
                if !(starts_with_slash || (is_asterisk && method_is_options)) {
                    return Err((H2Error::ProtocolError, false));
                }
            }
            // RFC 9113 §8.3.1 requires all four pseudo-headers to be present and non-empty.
            // Note: Store::is_empty() only matches Store::Empty — a pseudo-header stored
            // with an empty value yields Store::Slice { len: 0 } which is_empty() misses.
            // HPACK never produces zero-length pseudo-header values for valid requests, so
            // is_empty() is sufficient here; store_pseudo_header already rejects duplicates.
            // Note: CONNECT requests (RFC 9113 §8.5) only need :method + :authority,
            // but we don't advertise SETTINGS_ENABLE_CONNECT_PROTOCOL so CONNECT is
            // intentionally unsupported for now.
            if invalid_headers
                || method.is_empty()
                || authority.is_empty()
                || path.is_empty()
                || scheme.is_empty()
            {
                error!("{} INVALID HEADERS", log_module_context!());
                return Err((H2Error::ProtocolError, false));
            }
            // RFC 9113 §8.3.1: if a literal ``host`` header appears, it must
            // match ``:authority`` (modulo optional port) and be deduplicated
            // so the H1 serializer emits exactly one ``Host:`` line. Mismatches
            // are request-smuggling vectors and are rejected as PROTOCOL_ERROR.
            if host_conflict {
                error!(
                    "{} H2 host header: multiple disagreeing values",
                    log_module_context!()
                );
                return Err((H2Error::ProtocolError, false));
            }
            if let Some(ref host) = host_value {
                let authority_bytes = authority.data_opt(kawa.storage.buffer()).unwrap_or(&[]);
                if !host_matches_authority(host, authority_bytes) {
                    error!(
                        "{} H2 host header does not match :authority",
                        log_module_context!()
                    );
                    return Err((H2Error::ProtocolError, false));
                }
                // Match — drop it. kawa's H1 serializer emits Host: from
                // :authority on its own.
            }
            // All four mandatory request pseudo-headers passed the presence gate
            // above (RFC 9113 §8.3.1); none may be Store::Empty at this point.
            // `store_pseudo_header` already enforced uniqueness and the
            // pseudo-before-regular ordering, so a populated quartet here is the
            // proof the request line is well-formed before we mint it.
            debug_assert!(
                !method.is_empty()
                    && !authority.is_empty()
                    && !path.is_empty()
                    && !scheme.is_empty(),
                "all four request pseudo-headers must be present after validation"
            );
            StatusLine::Request {
                version: Version::V20,
                method,
                uri: path.clone(),
                authority,
                path,
            }
        }
        Kind::Response => {
            let mut code = 0;
            let mut status = Store::Empty;
            let mut regular_headers = false;
            let invalid_headers = decode_headers_with_budget(
                decoder,
                input,
                max_decoded_bytes,
                max_header_fields,
                |k, v, invalid_headers, _field_count| {
                    if compare_no_case(&k, b":status") {
                        // RFC 9113 §8.3.2 / RFC 9110 §15: :status is exactly
                        // three ASCII digits. `u16::from_str` would accept
                        // `+200`, ` 200`, `00200` etc., all of which diverge
                        // from the backend's H1 parser.
                        if v.len() != 3 || !v.iter().all(|b| b.is_ascii_digit()) {
                            metric_reject(RejectReason::InvalidStatus);
                            *invalid_headers = true;
                            return;
                        }
                        match store_pseudo_header(&status, regular_headers, kawa, &v) {
                            Ok(s) => {
                                status = s;
                                // The three-digit ASCII guard above proves each
                                // byte is in b'0'..=b'9', so this hand-rolled
                                // base-10 decode lands in 100..=999 with no
                                // overflow of the u16 accumulator.
                                debug_assert!(
                                    v.len() == 3 && v.iter().all(|b| b.is_ascii_digit()),
                                    ":status reaching the decode must be three ASCII digits"
                                );
                                code = (v[0] - b'0') as u16 * 100
                                    + (v[1] - b'0') as u16 * 10
                                    + (v[2] - b'0') as u16;
                                debug_assert!(
                                    (100..=999).contains(&code),
                                    "decoded :status code must be in 100..=999"
                                );
                            }
                            Err(reason) => {
                                metric_reject(reason);
                                *invalid_headers = true;
                            }
                        }
                    } else if k.starts_with(b":") {
                        metric_reject(RejectReason::UnknownPseudo);
                        *invalid_headers = true;
                    } else {
                        regular_headers = true;
                        if let Err(reason) = write_regular_header(kawa, &k, &v) {
                            metric_reject(reason);
                            *invalid_headers = true;
                        }
                    }
                },
            )?;
            if invalid_headers || status.is_empty() {
                error!("{} INVALID HEADERS", log_module_context!());
                return Err((H2Error::ProtocolError, false));
            }
            // Past the validity gate, :status was exactly three ASCII digits
            // (the in-loop guard rejected anything else), so the decimal `code`
            // is in 100..=999 and `status` is a stored, non-empty slice.
            debug_assert!(
                (100..=999).contains(&code),
                "response :status code must be a three-digit value in 100..=999"
            );
            debug_assert!(
                !status.is_empty(),
                "validated response must carry a non-empty :status pseudo"
            );
            StatusLine::Response {
                version: Version::V20,
                code,
                status,
                reason: Store::Static(b"FromH2"),
            }
        }
    };

    // everything has been parsed
    kawa.storage.head = kawa.storage.end;
    debug!(
        "{} index: {}/{}/{}",
        log_module_context!(),
        kawa.storage.start,
        kawa.storage.head,
        kawa.storage.end
    );

    callbacks.on_headers(kawa);

    if end_stream {
        // RFC 9113 §8.1.1: when END_STREAM is set on HEADERS, no DATA frames
        // follow, so the payload length is 0. A non-zero Content-Length is a
        // stream error (PROTOCOL_ERROR). Body-exempt responses (1xx, 204, 304)
        // are excluded — they may carry Content-Length per RFC 9110 §8.6.
        if let BodySize::Length(n) = kawa.body_size {
            let body_exempt = matches!(kawa.kind, Kind::Response)
                && matches!(
                    kawa.detached.status_line,
                    StatusLine::Response { code, .. } if (100..200).contains(&code) || code == 204 || code == 304
                );
            if n > 0 && !body_exempt {
                error!(
                    "{} END_STREAM with non-zero Content-Length: {} (RFC 9113 §8.1.1)",
                    log_module_context!(),
                    n
                );
                return Err((H2Error::ProtocolError, false));
            }
        }
        if let BodySize::Empty = kawa.body_size {
            // RFC 9110 §8.6: Do not inject Content-Length: 0 for responses where
            // message body is forbidden (1xx, 204, 304). Only inject for requests
            // and other response codes.
            let skip_content_length = matches!(kawa.kind, Kind::Response)
                && matches!(
                    kawa.detached.status_line,
                    StatusLine::Response { code, .. } if (100..200).contains(&code) || code == 204 || code == 304
                );
            if !skip_content_length {
                kawa.body_size = BodySize::Length(0);
                kawa.push_block(Block::Header(Pair {
                    key: Store::Static(b"Content-Length"),
                    val: Store::Static(b"0"),
                }));
            }
        }
    }

    // If body will follow (!end_stream) and no Content-Length was declared,
    // inject Transfer-Encoding: chunked so the H1 backend can frame the body.
    // The H2 converter filters this header (connection-specific per RFC 9113 §8.2.2).
    //
    // Note on H2→H1 trailers (RFC 9110 §6.5): when the H2 peer declares a
    // Content-Length (`body_size == BodySize::Length(_)`) and later sends a
    // trailer HEADERS frame, the H1 backend cannot receive those trailers —
    // HTTP/1.1 only carries trailers with chunked transfer-coding. In that
    // case the trailers are silently dropped by `handle_trailer`'s caller
    // (no Transfer-Encoding can be retro-fitted once the request line and
    // headers have already gone out on the wire). Peers that require
    // trailer delivery should omit Content-Length; the branch below then
    // upgrades the framing to chunked and H2BlockConverter on the back side
    // passes the trailer block through intact.
    if !end_stream && kawa.body_size == BodySize::Empty {
        kawa.body_size = BodySize::Chunked;
        kawa.push_block(Block::Header(Pair {
            key: Store::Static(b"Transfer-Encoding"),
            val: Store::Static(b"chunked"),
        }));
    }

    kawa.push_block(Block::Flags(Flags {
        end_body: end_stream,
        end_chunk: false,
        end_header: true,
        end_stream,
    }));

    if kawa.parsing_phase == ParsingPhase::Terminated {
        return Ok(());
    }

    // A stream that still expects a body (`!end_stream`) must have had its
    // framing resolved to a concrete length or chunked encoding above — the
    // `BodySize::Empty` upgrade-to-chunked branch guarantees we never enter the
    // phase mapping with an unframed body when more bytes are coming.
    debug_assert!(
        end_stream || kawa.body_size != BodySize::Empty,
        "a continuing stream must have a resolved body framing before phasing"
    );
    kawa.parsing_phase = match kawa.body_size {
        BodySize::Chunked => ParsingPhase::Chunks { first: true },
        BodySize::Length(0) => ParsingPhase::Terminated,
        BodySize::Length(_) => ParsingPhase::Body,
        BodySize::Empty => ParsingPhase::Chunks { first: true },
    };
    // The phase we just selected must be consistent with the framing: a
    // length-framed body lands in Body/Terminated, never mid-chunk.
    debug_assert!(
        !matches!(kawa.body_size, BodySize::Length(n) if n > 0)
            || kawa.parsing_phase == ParsingPhase::Body,
        "a non-empty Content-Length body must transition to ParsingPhase::Body"
    );
    Ok(())
}

/// Decode an H2 trailer HEADERS frame and append the validated trailer
/// pairs to `kawa.blocks`.
///
/// The shared `HttpContext::on_request_headers` callback that handles
/// elision on **initial** HEADERS frames is **not** invoked here, so any
/// listener-scoped header rewrites must be plumbed in explicitly.
///
/// ── Spoof-vector elision per RFC 9110 §6.5 ──
///
/// RFC 9110 §6.5 forbids trailers from carrying fields that affect
/// "message framing, message routing, or response semantics." sōzu
/// rewrites four client-attribution headers on the initial HEADERS pass
/// (`HttpContext::on_request_headers` in
/// `lib/src/protocol/kawa_h1/editor.rs`):
///   * `X-Real-IP` is replaced by the post-PROXY-v2 peer IP when
///     `send_x_real_ip = true` and stripped client-side when
///     `elide_x_real_ip = true`.
///   * `X-Forwarded-For` has the peer IP appended.
///   * `Forwarded` (RFC 7239) has a `proto=…;for=…;by=…` clause appended.
///   * `X-Request-Id` is preserved verbatim (de-facto correlation
///     header used by Envoy/HAProxy/most LBs).
///
/// A naive H2 client could otherwise smuggle any of those by sending
/// them as a trailer block: an H2 backend that merges trailers into
/// its header view (gRPC-style, or anything that uses
/// `headers::extend(trailers.iter())`) would observe an attacker-
/// controlled value. The four elisions below run **unconditionally** —
/// the spec already prohibits them, the operator gains no observability
/// or routing signal from a trailer-side copy, and forwarding them is
/// strictly a spoof vector.
///
/// `elide_x_real_ip` is kept as an explicit parameter for symmetry
/// with the initial-HEADERS path's listener flag, but the trailer-side
/// elision of `x-real-ip` no longer depends on it — the listener flag
/// only governs whether sōzu *injects* an `X-Real-IP` header on the
/// forward, never whether it filters one off the wire.
pub fn handle_trailer(
    kawa: &mut GenericHttpStream,
    input: &[u8],
    end_stream: bool,
    decoder: &mut loona_hpack::Decoder<'static>,
    max_header_list_size: u32,
    max_header_fields: u32,
    elide_x_real_ip: bool,
) -> Result<(), (H2Error, bool)> {
    // Acknowledge the parameter; dropping it would force a callsite
    // change. The elision below covers x-real-ip unconditionally so
    // the listener flag is no longer a gate for trailer-side defence.
    let _ = elide_x_real_ip;
    if !end_stream {
        return Err((H2Error::ProtocolError, false));
    }
    let max_header_fields = max_header_fields as usize;
    let mut invalid_trailers = false;
    let mut budget_exceeded = false;
    let mut field_limit_exceeded = false;
    let mut field_count: usize = 0;
    let mut decoded_bytes: usize = 0;
    // HEADERS and trailers each tracked an independent `decoded_bytes`
    // counter against `max_header_list_size`, so the
    // effective per-stream budget was `2 × MAX_HEADER_LIST_SIZE`
    // (~128 KiB at the default). True per-stream cumulative tracking
    // would require plumbing a shared counter through the `Stream`
    // struct; in the interim, cap trailer-only budget at `MAX_TRAILER_BYTES`
    // — well above legitimate gRPC trailer sizes (1-4 KB observed in the
    // wild, RFC 9110 §6.5 imposes no minimum) and an order of magnitude
    // tighter than the HEADERS cap.
    let max_decoded = (max_header_list_size as usize).min(MAX_TRAILER_BYTES);
    // The trailer carve-out can only tighten the budget, never relax it below
    // the negotiated MAX_HEADER_LIST_SIZE.
    debug_assert!(
        max_decoded <= max_header_list_size as usize && max_decoded <= MAX_TRAILER_BYTES,
        "trailer budget is the min of MAX_HEADER_LIST_SIZE and the carve-out cap"
    );
    let decode_status = decoder.decode_with_cb(input, |k, v| {
        if invalid_trailers || budget_exceeded || field_limit_exceeded {
            return;
        }
        let bytes_before = decoded_bytes;
        // RFC 9113 §6.5.2: count name + value octets plus the 32-octet
        // per-field overhead, matching the HEADERS path.
        decoded_bytes = decoded_bytes
            .saturating_add(k.len())
            .saturating_add(v.len())
            .saturating_add(crate::protocol::mux::h2::HEADER_FIELD_SIZE_OVERHEAD);
        debug_assert!(
            decoded_bytes >= bytes_before,
            "decoded trailer size must be monotonic non-decreasing"
        );
        if decoded_bytes > max_decoded {
            budget_exceeded = true;
            return;
        }
        // Admitted trailers keep the running total within the carve-out cap.
        debug_assert!(
            decoded_bytes <= max_decoded,
            "admitted trailers must stay within the trailer budget"
        );
        field_count += 1;
        if field_count > max_header_fields {
            field_limit_exceeded = true;
            return;
        }
        // RFC 9113 §8.1: Trailers MUST NOT contain pseudo-header fields.
        if k.starts_with(b":") {
            metric_reject(RejectReason::UnknownPseudo);
            invalid_trailers = true;
            return;
        }
        // Reuse the same validation policy as the main header path: reject
        // invalid name bytes (CTLs, separators, uppercase), connection-specific
        // fields (RFC 9113 §8.2.2), invalid TE values, and forbidden value
        // bytes (RFC 9110 §5.5). Without this, crafted trailer names can
        // smuggle H1 lines through kawa's serializer.
        if let Some(reason) = classify_invalid_h2_header(&k, &v) {
            metric_reject(reason);
            invalid_trailers = true;
            return;
        }
        // ── Spoof-vector elision per RFC 9110 §6.5 ──
        //
        // RFC 9110 §6.5 forbids trailers from carrying message-routing
        // semantics. The four client-attribution headers below are
        // rewritten by sōzu on the initial-HEADERS pass; admitting them
        // as trailers would let a naive H2 client smuggle a spoofed
        // value to a backend that merges trailers into its header view.
        // Drop them unconditionally — keys are already lower-case here
        // (`classify_invalid_h2_header` rejects any uppercase byte per
        // RFC 9113 §8.2.2), so a byte-equality check is sufficient.
        // `incr!` records the rejection so dashboards observe the
        // attempted smuggle without spamming logs.
        if matches!(
            k.as_ref(),
            b"x-real-ip" | b"x-forwarded-for" | b"forwarded" | b"x-request-id"
        ) {
            incr!(names::h2::TRAILER_SPOOF_VECTOR_ELIDED);
            return;
        }
        let start = kawa.storage.end as u32;
        let end_before = kawa.storage.end;
        if kawa.storage.write_all(&k).is_err() || kawa.storage.write_all(&v).is_err() {
            metric_reject(RejectReason::OversizedPseudoValue);
            invalid_trailers = true;
            return;
        }
        // Both writes succeeded, so storage.end advanced by exactly key+value
        // and the two slices tile [start, end) contiguously (key first, then
        // value at `start + len_key`).
        debug_assert_eq!(
            kawa.storage.end,
            end_before + k.len() + v.len(),
            "trailer write must advance storage.end by key.len() + value.len()"
        );
        let len_key = k.len() as u32;
        let len_val = v.len() as u32;
        debug_assert!(
            (start + len_key + len_val) as usize <= kawa.storage.end,
            "trailer key+val slices must stay within the written storage region"
        );
        let key = Store::Slice(Slice {
            start,
            len: len_key,
        });
        let val = Store::Slice(Slice {
            start: start + len_key,
            len: len_val,
        });
        kawa.push_block(Block::Header(Pair { key, val }));
    });

    if let Err(error) = decode_status {
        error!("{} INVALID FRAGMENT: {:?}", log_module_context!(), error);
        return Err((H2Error::CompressionError, true));
    }
    if budget_exceeded {
        metric_reject(RejectReason::HeaderListOverBudget);
        error!(
            "{} HPACK decoded trailer size {} exceeds MAX_HEADER_LIST_SIZE {}",
            log_module_context!(),
            decoded_bytes,
            max_decoded
        );
        return Err((H2Error::EnhanceYourCalm, false));
    }
    if field_limit_exceeded {
        metric_reject(RejectReason::TooManyHeaderFields);
        error!(
            "{} HPACK trailer field count {} exceeds max_header_fields {}",
            log_module_context!(),
            field_count,
            max_header_fields
        );
        return Err((H2Error::EnhanceYourCalm, false));
    }
    if invalid_trailers {
        error!("{} INVALID TRAILERS", log_module_context!());
        return Err((H2Error::ProtocolError, false));
    }
    // Reaching here means the trailer block decoded cleanly, never overflowed
    // the carve-out budget, and carried no invalid field — the three rejection
    // gates above already returned on the negative space.
    debug_assert!(
        !budget_exceeded && !invalid_trailers && decoded_bytes <= max_decoded,
        "an accepted trailer block must fit the budget and pass validation"
    );

    // RFC 9110 §6.5: if the request/response was framed with a
    // fixed Content-Length (not chunked), the H1-side serializer cannot emit
    // trailers — HTTP/1.1 only carries trailers with chunked transfer-coding.
    // The trailer block stays in kawa but the downstream writer will never
    // reach it. Emit a visible signal so operators chasing "vanished gRPC
    // trailers" have something to grep, without changing the drop behaviour
    // (changing it would retroactively need to rewrite the framing, which
    // is not possible once headers are on the wire).
    if matches!(kawa.body_size, BodySize::Length(_)) {
        warn!(
            "{} H2 trailers arrived on a Content-Length-framed stream; \
             trailers will be silently dropped by the H1 serializer \
             (RFC 9110 §6.5). Peer should omit Content-Length for trailer \
             delivery to upgrade framing to chunked.",
            log_module_context!()
        );
        incr!(names::h2::TRAILERS_DROPPED_CONTENT_LENGTH);
    }

    kawa.push_block(Block::Flags(Flags {
        end_body: false,
        end_chunk: false,
        end_header: true,
        end_stream: true,
    }));
    kawa.parsing_phase = ParsingPhase::Terminated;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    // ── parse_rfc9218_priority ────────────────────────────────────────────

    #[test]
    fn test_parse_rfc9218_priority_defaults() {
        // Empty value -> RFC 9218 §4 defaults: urgency 3, incremental false
        let (u, i) = parse_rfc9218_priority(b"");
        assert_eq!(u, 3);
        assert!(!i);
    }

    #[test]
    fn test_parse_rfc9218_priority_urgency_only() {
        assert_eq!(parse_rfc9218_priority(b"u=0"), (0, false));
        assert_eq!(parse_rfc9218_priority(b"u=3"), (3, false));
        assert_eq!(parse_rfc9218_priority(b"u=7"), (7, false));
    }

    #[test]
    fn test_parse_rfc9218_priority_urgency_clamped() {
        // Values > 7 are clamped to 7
        assert_eq!(parse_rfc9218_priority(b"u=9"), (7, false));
        assert_eq!(parse_rfc9218_priority(b"u=255"), (7, false));
    }

    #[test]
    fn test_parse_rfc9218_priority_incremental_only() {
        // Just "i" -> default urgency 3, incremental true
        assert_eq!(parse_rfc9218_priority(b"i"), (3, true));
    }

    #[test]
    fn test_parse_rfc9218_priority_incremental_boolean_form() {
        assert_eq!(parse_rfc9218_priority(b"i=?1"), (3, true));
        assert_eq!(parse_rfc9218_priority(b"i=?0"), (3, false));
    }

    #[test]
    fn test_parse_rfc9218_priority_combined() {
        assert_eq!(parse_rfc9218_priority(b"u=3, i"), (3, true));
        assert_eq!(parse_rfc9218_priority(b"u=0, i"), (0, true));
        assert_eq!(parse_rfc9218_priority(b"u=7, i=?1"), (7, true));
        assert_eq!(parse_rfc9218_priority(b"u=5, i=?0"), (5, false));
    }

    #[test]
    fn test_parse_rfc9218_priority_whitespace_tolerance() {
        // OWS around tokens should be trimmed
        assert_eq!(parse_rfc9218_priority(b"u=3,  i"), (3, true));
        assert_eq!(parse_rfc9218_priority(b" u=3 , i "), (3, true));
        assert_eq!(parse_rfc9218_priority(b"\tu=2\t,\ti\t"), (2, true));
    }

    #[test]
    fn test_parse_rfc9218_priority_malformed_ignored() {
        // Unknown tokens are silently ignored
        assert_eq!(parse_rfc9218_priority(b"x=5"), (3, false));
        assert_eq!(parse_rfc9218_priority(b"u=3, x=5"), (3, false));
        // "u=" with non-numeric value: parse fails, urgency stays default
        assert_eq!(parse_rfc9218_priority(b"u=abc"), (3, false));
    }

    #[test]
    fn test_parse_rfc9218_priority_order_independent() {
        // "i" before "u=N" should work
        assert_eq!(parse_rfc9218_priority(b"i, u=1"), (1, true));
    }

    // ── is_connection_specific_header ─────────────────────────────────────

    #[test]
    fn test_is_connection_specific_header_positive() {
        assert!(is_connection_specific_header(b"connection"));
        assert!(is_connection_specific_header(b"Connection"));
        assert!(is_connection_specific_header(b"proxy-connection"));
        assert!(is_connection_specific_header(b"Proxy-Connection"));
        assert!(is_connection_specific_header(b"transfer-encoding"));
        assert!(is_connection_specific_header(b"Transfer-Encoding"));
        assert!(is_connection_specific_header(b"upgrade"));
        assert!(is_connection_specific_header(b"Upgrade"));
        assert!(is_connection_specific_header(b"keep-alive"));
        assert!(is_connection_specific_header(b"Keep-Alive"));
    }

    #[test]
    fn test_is_connection_specific_header_negative() {
        assert!(!is_connection_specific_header(b"content-type"));
        assert!(!is_connection_specific_header(b"accept"));
        assert!(!is_connection_specific_header(b"host"));
        assert!(!is_connection_specific_header(b"te"));
        assert!(!is_connection_specific_header(b"cookie"));
        assert!(!is_connection_specific_header(b""));
    }

    // ── is_invalid_h2_header ─────────────────────────────────────────────

    #[test]
    fn test_is_invalid_h2_header_uppercase_name() {
        assert!(is_invalid_h2_header(b"Content-Type", b"text/html"));
        assert!(is_invalid_h2_header(b"X-Custom", b"value"));
    }

    #[test]
    fn test_is_invalid_h2_header_connection_specific() {
        assert!(is_invalid_h2_header(b"connection", b"close"));
        assert!(is_invalid_h2_header(b"transfer-encoding", b"chunked"));
        assert!(is_invalid_h2_header(b"upgrade", b"h2c"));
        assert!(is_invalid_h2_header(b"keep-alive", b"timeout=5"));
        assert!(is_invalid_h2_header(b"proxy-connection", b"keep-alive"));
    }

    #[test]
    fn test_is_invalid_h2_header_te_trailers_ok() {
        // TE: trailers is the only valid TE value in HTTP/2
        assert!(!is_invalid_h2_header(b"te", b"trailers"));
        assert!(!is_invalid_h2_header(b"te", b"Trailers")); // case insensitive
    }

    #[test]
    fn test_is_invalid_h2_header_te_other_invalid() {
        assert!(is_invalid_h2_header(b"te", b"gzip"));
        assert!(is_invalid_h2_header(b"te", b"deflate"));
        assert!(is_invalid_h2_header(b"te", b"chunked"));
    }

    #[test]
    fn test_is_invalid_h2_header_valid() {
        assert!(!is_invalid_h2_header(b"content-type", b"text/html"));
        assert!(!is_invalid_h2_header(b"accept", b"*/*"));
        assert!(!is_invalid_h2_header(b"x-custom", b"value"));
    }

    // ── has_uppercase_ascii ──────────────────────────────────────────────

    #[test]
    fn test_has_uppercase_ascii() {
        assert!(has_uppercase_ascii(b"Content-Type"));
        assert!(has_uppercase_ascii(b"X"));
        assert!(!has_uppercase_ascii(b"content-type"));
        assert!(!has_uppercase_ascii(b""));
        assert!(!has_uppercase_ascii(b"123-header"));
    }

    // ── trim_ows ─────────────────────────────────────────────────────────

    #[test]
    fn test_trim_ows() {
        assert_eq!(trim_ows(b"  hello  "), b"hello");
        assert_eq!(trim_ows(b"\thello\t"), b"hello");
        assert_eq!(trim_ows(b" \t hello \t "), b"hello");
        assert_eq!(trim_ows(b"hello"), b"hello");
        assert_eq!(trim_ows(b""), b"" as &[u8]);
        assert_eq!(trim_ows(b"   "), b"" as &[u8]);
    }

    // ── store_pseudo_header ──────────────────────────────────────────────

    /// Create a `GenericHttpStream` backed by a pool `Checkout` for testing.
    fn make_generic_kawa(pool: &mut crate::pool::Pool, kind: Kind) -> GenericHttpStream {
        let checkout = pool.checkout().expect("pool checkout should succeed");
        kawa::Kawa::new(kind, kawa::Buffer::new(checkout))
    }

    #[test]
    fn test_store_pseudo_header_rejects_duplicate() {
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let mut kawa = make_generic_kawa(&mut pool, Kind::Request);

        // First store succeeds
        let dest = Store::Empty;
        let result = store_pseudo_header(&dest, false, &mut kawa, b"GET");
        assert!(result.is_ok());

        // Second store with non-empty dest fails (duplicate pseudo-header)
        let dest = result.unwrap();
        let result = store_pseudo_header(&dest, false, &mut kawa, b"POST");
        assert!(result.is_err());
    }

    #[test]
    fn test_store_pseudo_header_rejects_after_regular_headers() {
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let mut kawa = make_generic_kawa(&mut pool, Kind::Request);

        let dest = Store::Empty;
        // regular_headers = true means regular headers have already appeared
        let result = store_pseudo_header(&dest, true, &mut kawa, b"GET");
        assert!(result.is_err());
    }

    // ── is_connection_specific_header (additional case sensitivity) ────

    #[test]
    fn test_is_connection_specific_header_mixed_case() {
        // Verify case-insensitive matching for various mixed-case forms
        assert!(is_connection_specific_header(b"CONNECTION"));
        assert!(is_connection_specific_header(b"CoNnEcTiOn"));
        assert!(is_connection_specific_header(b"PROXY-CONNECTION"));
        assert!(is_connection_specific_header(b"Proxy-connection"));
        assert!(is_connection_specific_header(b"TRANSFER-ENCODING"));
        assert!(is_connection_specific_header(b"transfer-Encoding"));
        assert!(is_connection_specific_header(b"UPGRADE"));
        assert!(is_connection_specific_header(b"KEEP-ALIVE"));
        assert!(is_connection_specific_header(b"Keep-alive"));
    }

    #[test]
    fn test_is_connection_specific_header_partial_match() {
        // Substrings or superstrings must not match
        assert!(!is_connection_specific_header(b"connection-extra"));
        assert!(!is_connection_specific_header(b"my-connection"));
        assert!(!is_connection_specific_header(b"upgrade-insecure-requests"));
        assert!(!is_connection_specific_header(b"keep-alive-timeout"));
        assert!(!is_connection_specific_header(b"x-keep-alive"));
    }

    // ── is_invalid_te_value ─────────────────────────────────────────────

    #[test]
    fn test_is_invalid_te_value_trailers_ok() {
        assert!(!is_invalid_te_value(b"trailers"));
        assert!(!is_invalid_te_value(b"Trailers"));
        assert!(!is_invalid_te_value(b"TRAILERS"));
    }

    #[test]
    fn test_is_invalid_te_value_other_rejected() {
        assert!(is_invalid_te_value(b"gzip"));
        assert!(is_invalid_te_value(b"deflate"));
        assert!(is_invalid_te_value(b"chunked"));
        assert!(is_invalid_te_value(b"compress"));
        assert!(is_invalid_te_value(b""));
        assert!(is_invalid_te_value(b"trailers, gzip"));
    }

    // ── is_invalid_h2_header (additional edge cases) ──────────────────

    #[test]
    fn test_is_invalid_h2_header_empty_name() {
        // Empty header name is invalid per RFC 9113 §8.2.1 (field names MUST be non-empty)
        assert!(is_invalid_h2_header(b"", b""));
    }

    #[test]
    fn test_is_invalid_h2_header_single_uppercase() {
        // Even a single uppercase letter makes it invalid
        assert!(is_invalid_h2_header(b"X", b""));
        assert!(is_invalid_h2_header(b"hostA", b"value"));
    }

    // ── has_uppercase_ascii (additional) ───────────────────────────────

    #[test]
    fn test_has_uppercase_ascii_non_ascii_bytes() {
        // Non-ASCII bytes (128+) are not uppercase ASCII
        assert!(!has_uppercase_ascii(&[0x80, 0xFF, 0xC0]));
        assert!(!has_uppercase_ascii(b"\xc3\xa9")); // UTF-8 for 'e' with accent
    }

    #[test]
    fn test_has_uppercase_ascii_mixed_with_numbers() {
        assert!(!has_uppercase_ascii(b"content-type-2"));
        assert!(has_uppercase_ascii(b"content-Type-2"));
    }

    // ── trim_ows (additional) ─────────────────────────────────────────

    #[test]
    fn test_trim_ows_single_char() {
        assert_eq!(trim_ows(b"x"), b"x");
        assert_eq!(trim_ows(b" "), b"" as &[u8]);
        assert_eq!(trim_ows(b"\t"), b"" as &[u8]);
    }

    #[test]
    fn test_trim_ows_preserves_internal_whitespace() {
        assert_eq!(trim_ows(b"  hello world  "), b"hello world");
        assert_eq!(trim_ows(b"\ta\tb\t"), b"a\tb");
    }

    // ── handle_header: cookie jar population ─────────────────────────────

    /// Helper: HPACK-encode a set of headers and call `handle_header`, returning the kawa stream.
    fn decode_request_headers(
        pool: &mut crate::pool::Pool,
        headers: &[(&[u8], &[u8])],
        end_stream: bool,
    ) -> GenericHttpStream {
        let mut encoder = loona_hpack::Encoder::new();
        let mut encoded = Vec::new();
        for &(name, value) in headers {
            encoder
                .encode_header_into((name, value), &mut encoded)
                .unwrap();
        }

        let mut decoder = loona_hpack::Decoder::new();
        let mut prioriser = Prioriser::default();
        let mut kawa = make_generic_kawa(pool, Kind::Request);

        struct NoOpCallbacks;
        impl kawa::h1::ParserCallbacks<crate::pool::Checkout> for NoOpCallbacks {
            fn on_headers(&mut self, _kawa: &mut GenericHttpStream) {}
        }
        let mut callbacks = NoOpCallbacks;

        let result = handle_header(
            &mut decoder,
            &mut prioriser,
            1,
            &mut kawa,
            &encoded,
            end_stream,
            &mut callbacks,
            crate::protocol::mux::h2::MAX_HEADER_LIST_SIZE as u32,
            u32::MAX,
            false,
        );
        assert!(result.is_ok(), "handle_header failed: {:?}", result.err());
        kawa
    }

    // ── handle_header: HPACK "bomb" budget caps ──────────────────────────

    fn base_request_pseudo() -> Vec<(Vec<u8>, Vec<u8>)> {
        vec![
            (b":method".to_vec(), b"GET".to_vec()),
            (b":scheme".to_vec(), b"https".to_vec()),
            (b":path".to_vec(), b"/".to_vec()),
            (b":authority".to_vec(), b"example.com".to_vec()),
        ]
    }

    /// HPACK-encode owned headers and run `handle_header` with explicit budget
    /// caps, returning the raw result so limit enforcement can be asserted.
    fn try_decode_request_capped(
        pool: &mut crate::pool::Pool,
        headers: &[(Vec<u8>, Vec<u8>)],
        max_header_list_size: u32,
        max_header_fields: u32,
    ) -> Result<GenericHttpStream, (H2Error, bool)> {
        let mut encoder = loona_hpack::Encoder::new();
        let mut encoded = Vec::new();
        for (name, value) in headers {
            encoder
                .encode_header_into((name.as_slice(), value.as_slice()), &mut encoded)
                .unwrap();
        }
        let mut decoder = loona_hpack::Decoder::new();
        let mut prioriser = Prioriser::default();
        let mut kawa = make_generic_kawa(pool, Kind::Request);
        struct NoOpCallbacks;
        impl kawa::h1::ParserCallbacks<crate::pool::Checkout> for NoOpCallbacks {
            fn on_headers(&mut self, _kawa: &mut GenericHttpStream) {}
        }
        let mut callbacks = NoOpCallbacks;
        handle_header(
            &mut decoder,
            &mut prioriser,
            1,
            &mut kawa,
            &encoded,
            true,
            &mut callbacks,
            max_header_list_size,
            max_header_fields,
            false,
        )
        .map(|()| kawa)
    }

    #[test]
    fn test_h2_header_field_count_cap_rejects_bomb() {
        // HPACK indexed-reference bomb: thousands of 1-byte indexed references
        // each materialize one Pair of per-entry bookkeeping. Cap the COUNT of
        // header fields (nginx `max_headers` / Apache `LimitRequestFields`
        // equivalent), independent of decoded byte size.
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 1 << 20);
        let mut headers = base_request_pseudo();
        for _ in 0..200 {
            headers.push((b"x-bomb".to_vec(), b"".to_vec()));
        }
        let result = try_decode_request_capped(&mut pool, &headers, u32::MAX, 128);
        assert!(
            matches!(result, Err((H2Error::EnhanceYourCalm, _))),
            "expected EnhanceYourCalm for >128 header fields, got {:?}",
            result.map(|_| ())
        );
    }

    #[test]
    fn test_h2_header_list_size_includes_32_octet_overhead() {
        // RFC 9113 §6.5.2: SETTINGS_MAX_HEADER_LIST_SIZE counts name + value
        // octets PLUS a 32-octet overhead per field. These headers' raw bytes
        // are far under the limit, but the per-field overhead pushes the
        // accounted size over it — without the +32 the bomb slips through.
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 1 << 20);
        let mut headers = base_request_pseudo();
        for _ in 0..120 {
            headers.push((b"a".to_vec(), b"".to_vec())); // 1 raw octet, 33 with overhead
        }
        let result = try_decode_request_capped(&mut pool, &headers, 4096, u32::MAX);
        assert!(
            matches!(result, Err((H2Error::EnhanceYourCalm, _))),
            "expected EnhanceYourCalm once 32-octet/field overhead is counted, got {:?}",
            result.map(|_| ())
        );
    }

    #[test]
    fn test_h2_cookie_crumb_count_cap_rejects_bomb() {
        // RFC 9113 §8.2.3 cookie-crumb vector: one HPACK cookie field expands
        // into many jar Pairs. Crumbs must count against the field cap
        // (cf. Apache CVE-2026-49975 counting crumbs against LimitRequestFields).
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 1 << 20);
        let mut headers = base_request_pseudo();
        let mut cookie = Vec::new();
        for i in 0..200 {
            if i > 0 {
                cookie.extend_from_slice(b"; ");
            }
            cookie.extend_from_slice(b"a=1");
        }
        headers.push((b"cookie".to_vec(), cookie));
        let result = try_decode_request_capped(&mut pool, &headers, u32::MAX, 128);
        assert!(
            matches!(result, Err((H2Error::EnhanceYourCalm, _))),
            "expected EnhanceYourCalm for >128 cookie crumbs, got {:?}",
            result.map(|_| ())
        );
    }

    #[test]
    fn test_h2_cookie_crumb_count_exact_n_boundary() {
        // L2 exact-N semantics: a cookie HPACK field costs exactly N (its crumb
        // count), NOT N+1. With 4 pseudo-headers + a cap of 4 + 128 = 132, a lone
        // cookie of 128 crumbs costs exactly 128 → total 132 → ACCEPTED; 129
        // crumbs → total 133 → REJECTED. Under the old N+1 count the 128-crumb
        // cookie would have cost 129 (total 133) and been wrongly rejected — so
        // this pins the exact-N boundary and guards against a silent regression
        // back to N+1 (or to an under-count below the materialized Pair count).
        let cap: u32 = 4 + 128;

        let build = |crumbs: usize| -> Vec<(Vec<u8>, Vec<u8>)> {
            let mut headers = base_request_pseudo();
            let mut cookie = Vec::new();
            for i in 0..crumbs {
                if i > 0 {
                    cookie.extend_from_slice(b"; ");
                }
                cookie.extend_from_slice(b"a=1");
            }
            headers.push((b"cookie".to_vec(), cookie));
            headers
        };

        // Exactly at the cap: 128 crumbs (total field count 132) → accepted.
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 1 << 20);
        let at_cap = build(128);
        let result = try_decode_request_capped(&mut pool, &at_cap, u32::MAX, cap);
        assert!(
            result.is_ok(),
            "128-crumb cookie must pass under exact-N (cap {cap}), got {:?}",
            result.err()
        );

        // One past the cap: 129 crumbs (total field count 133) → rejected.
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 1 << 20);
        let over_cap = build(129);
        let result = try_decode_request_capped(&mut pool, &over_cap, u32::MAX, cap);
        assert!(
            matches!(result, Err((H2Error::EnhanceYourCalm, _))),
            "129-crumb cookie must reject under exact-N (cap {cap}), got {:?}",
            result.map(|_| ())
        );
    }

    #[test]
    fn test_h2_legit_request_within_caps_accepted() {
        // A normal request with a handful of headers and a 3-crumb cookie must
        // pass cleanly under the default caps.
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let mut headers = base_request_pseudo();
        headers.push((b"user-agent".to_vec(), b"curl/8".to_vec()));
        headers.push((b"accept".to_vec(), b"*/*".to_vec()));
        headers.push((b"cookie".to_vec(), b"a=1; b=2; c=3".to_vec()));
        let kawa = try_decode_request_capped(
            &mut pool,
            &headers,
            crate::protocol::mux::h2::MAX_HEADER_LIST_SIZE as u32,
            128,
        )
        .expect("legit request must be accepted");
        assert_eq!(kawa.detached.jar.len(), 3);
    }

    #[test]
    fn test_h2_cookies_stored_in_jar() {
        // RFC 9113 §8.2.3: H2 cookies should be stored in detached.jar
        // so H1 converter concatenates them into a single Cookie header.
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let kawa = decode_request_headers(
            &mut pool,
            &[
                (b":method", b"GET"),
                (b":scheme", b"https"),
                (b":path", b"/"),
                (b":authority", b"example.com"),
                (b"cookie", b"a=1; b=2; c=3"),
            ],
            true,
        );

        // All three cookies should be in the jar
        assert_eq!(kawa.detached.jar.len(), 3);
        let buf = kawa.storage.buffer();
        assert_eq!(kawa.detached.jar[0].key.data(buf), b"a");
        assert_eq!(kawa.detached.jar[0].val.data(buf), b"1");
        assert_eq!(kawa.detached.jar[1].key.data(buf), b"b");
        assert_eq!(kawa.detached.jar[1].val.data(buf), b"2");
        assert_eq!(kawa.detached.jar[2].key.data(buf), b"c");
        assert_eq!(kawa.detached.jar[2].val.data(buf), b"3");

        // Should have exactly one Block::Cookies in the blocks
        let cookie_blocks: Vec<_> = kawa
            .blocks
            .iter()
            .filter(|b| matches!(b, Block::Cookies))
            .collect();
        assert_eq!(cookie_blocks.len(), 1);
    }

    #[test]
    fn test_h2_multiple_cookie_headers_merged_in_jar() {
        // Multiple separate cookie HPACK headers should all go to the same jar
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let kawa = decode_request_headers(
            &mut pool,
            &[
                (b":method", b"GET"),
                (b":scheme", b"https"),
                (b":path", b"/"),
                (b":authority", b"example.com"),
                (b"cookie", b"a=1"),
                (b"cookie", b"b=2"),
                (b"cookie", b"c=3"),
            ],
            true,
        );

        assert_eq!(kawa.detached.jar.len(), 3);
        let buf = kawa.storage.buffer();
        assert_eq!(kawa.detached.jar[0].key.data(buf), b"a");
        assert_eq!(kawa.detached.jar[0].val.data(buf), b"1");
        assert_eq!(kawa.detached.jar[1].key.data(buf), b"b");
        assert_eq!(kawa.detached.jar[1].val.data(buf), b"2");
        assert_eq!(kawa.detached.jar[2].key.data(buf), b"c");
        assert_eq!(kawa.detached.jar[2].val.data(buf), b"3");

        // Still only one Block::Cookies marker
        let cookie_blocks: Vec<_> = kawa
            .blocks
            .iter()
            .filter(|b| matches!(b, Block::Cookies))
            .collect();
        assert_eq!(cookie_blocks.len(), 1);
    }

    #[test]
    fn test_h2_cookie_empty_value() {
        // Cookie with empty value after '=' (e.g., intercom-session=)
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let kawa = decode_request_headers(
            &mut pool,
            &[
                (b":method", b"GET"),
                (b":scheme", b"https"),
                (b":path", b"/"),
                (b":authority", b"example.com"),
                (b"cookie", b"session=; PHPSESSID=abc123"),
            ],
            true,
        );

        assert_eq!(kawa.detached.jar.len(), 2);
        let buf = kawa.storage.buffer();
        assert_eq!(kawa.detached.jar[0].key.data(buf), b"session");
        assert_eq!(kawa.detached.jar[0].val.data(buf), b"");
        assert_eq!(kawa.detached.jar[1].key.data(buf), b"PHPSESSID");
        assert_eq!(kawa.detached.jar[1].val.data(buf), b"abc123");
    }

    #[test]
    fn test_h2_cookie_without_equals() {
        // Cookie without '=' (bare name, no value)
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let kawa = decode_request_headers(
            &mut pool,
            &[
                (b":method", b"GET"),
                (b":scheme", b"https"),
                (b":path", b"/"),
                (b":authority", b"example.com"),
                (b"cookie", b"bare_name"),
            ],
            true,
        );

        assert_eq!(kawa.detached.jar.len(), 1);
        let buf = kawa.storage.buffer();
        assert_eq!(kawa.detached.jar[0].key.data(buf), b"bare_name");
        assert_eq!(kawa.detached.jar[0].val.data(buf), b"");
    }

    // ── has_invalid_value_byte / CTL rejection ───────────────────────────

    #[test]
    fn test_has_invalid_value_byte_ctl_and_del() {
        // RFC 9110 §5.5 / RFC 9113 §8.2.1: CR, LF, NUL, other C0 CTLs, DEL
        // are forbidden in field values.
        assert!(has_invalid_value_byte(b"a\rb"));
        assert!(has_invalid_value_byte(b"a\nb"));
        assert!(has_invalid_value_byte(b"a\r\nb"));
        assert!(has_invalid_value_byte(b"a\x00b"));
        assert!(has_invalid_value_byte(b"a\x01b"));
        assert!(has_invalid_value_byte(b"a\x7fb"));
        assert!(has_invalid_value_byte(b"a\x1fb"));
    }

    #[test]
    fn test_has_invalid_value_byte_permits_tab_sp_vchar() {
        // HTAB and visible ASCII (SP..=~) are permitted.
        assert!(!has_invalid_value_byte(b"a\tb"));
        assert!(!has_invalid_value_byte(b"a b"));
        assert!(!has_invalid_value_byte(b"normal-value"));
        // obs-text (0x80..=0xFF) is permitted by the value ABNF
        assert!(!has_invalid_value_byte(&[0x80, 0xFF]));
        // Empty slice is allowed by this helper (empty-check is done elsewhere)
        assert!(!has_invalid_value_byte(b""));
    }

    #[test]
    fn test_is_invalid_h2_header_rejects_ctl_in_value() {
        assert!(is_invalid_h2_header(b"x-evil", b"a\r\nb"));
        assert!(is_invalid_h2_header(b"x-evil", b"a\nb"));
        assert!(is_invalid_h2_header(b"x-evil", b"a\rb"));
        assert!(is_invalid_h2_header(b"x-evil", b"a\x00b"));
        assert!(is_invalid_h2_header(b"x-evil", b"a\x7fb"));
        assert!(is_invalid_h2_header(b"x-evil", b"a\x01b"));
        assert!(!is_invalid_h2_header(b"x-evil", b"a\tb"));
        assert!(!is_invalid_h2_header(b"x-evil", b"a b"));
    }

    // ── store_pseudo_header: empty & CTL rejection ────────────────────────

    #[test]
    fn test_store_pseudo_header_rejects_empty_value() {
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let mut kawa = make_generic_kawa(&mut pool, Kind::Request);
        // RFC 9113 §8.3.1: pseudo-header values MUST NOT be empty.
        let result = store_pseudo_header(&Store::Empty, false, &mut kawa, b"");
        assert!(result.is_err());
    }

    #[test]
    fn test_store_pseudo_header_rejects_ctl_in_value() {
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let mut kawa = make_generic_kawa(&mut pool, Kind::Request);
        let result = store_pseudo_header(&Store::Empty, false, &mut kawa, b"/foo\r\n");
        assert!(result.is_err());
        let result = store_pseudo_header(&Store::Empty, false, &mut kawa, b"a\x00b");
        assert!(result.is_err());
    }

    // ── handle_header: request pseudo-header & CTL/smuggling rejection ────

    /// HPACK-encode a header list and call `handle_header`, returning the
    /// resulting `Result` so callers can assert on rejections.
    fn try_decode_request_headers(
        pool: &mut crate::pool::Pool,
        headers: &[(&[u8], &[u8])],
        end_stream: bool,
    ) -> Result<(), (H2Error, bool)> {
        let mut encoder = loona_hpack::Encoder::new();
        let mut encoded = Vec::new();
        for &(name, value) in headers {
            encoder
                .encode_header_into((name, value), &mut encoded)
                .unwrap();
        }
        let mut decoder = loona_hpack::Decoder::new();
        let mut prioriser = Prioriser::default();
        let mut kawa = make_generic_kawa(pool, Kind::Request);
        struct NoOpCallbacks;
        impl kawa::h1::ParserCallbacks<crate::pool::Checkout> for NoOpCallbacks {
            fn on_headers(&mut self, _kawa: &mut GenericHttpStream) {}
        }
        let mut callbacks = NoOpCallbacks;
        handle_header(
            &mut decoder,
            &mut prioriser,
            1,
            &mut kawa,
            &encoded,
            end_stream,
            &mut callbacks,
            crate::protocol::mux::h2::MAX_HEADER_LIST_SIZE as u32,
            u32::MAX,
            false,
        )
    }

    fn try_decode_response_headers(
        pool: &mut crate::pool::Pool,
        headers: &[(&[u8], &[u8])],
        end_stream: bool,
    ) -> Result<(), (H2Error, bool)> {
        let mut encoder = loona_hpack::Encoder::new();
        let mut encoded = Vec::new();
        for &(name, value) in headers {
            encoder
                .encode_header_into((name, value), &mut encoded)
                .unwrap();
        }
        let mut decoder = loona_hpack::Decoder::new();
        let mut prioriser = Prioriser::default();
        let mut kawa = make_generic_kawa(pool, Kind::Response);
        struct NoOpCallbacks;
        impl kawa::h1::ParserCallbacks<crate::pool::Checkout> for NoOpCallbacks {
            fn on_headers(&mut self, _kawa: &mut GenericHttpStream) {}
        }
        let mut callbacks = NoOpCallbacks;
        handle_header(
            &mut decoder,
            &mut prioriser,
            1,
            &mut kawa,
            &encoded,
            end_stream,
            &mut callbacks,
            crate::protocol::mux::h2::MAX_HEADER_LIST_SIZE as u32,
            u32::MAX,
            false,
        )
    }

    #[test]
    fn test_handle_header_rejects_crlf_in_regular_header_value() {
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let err = try_decode_request_headers(
            &mut pool,
            &[
                (b":method", b"GET"),
                (b":scheme", b"https"),
                (b":path", b"/"),
                (b":authority", b"example.com"),
                (b"x-evil", b"normal\r\nX-Smuggled: yes"),
            ],
            true,
        );
        assert!(err.is_err(), "CRLF-laden header value must be rejected");
    }

    #[test]
    fn test_handle_header_rejects_empty_path() {
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let err = try_decode_request_headers(
            &mut pool,
            &[
                (b":method", b"GET"),
                (b":scheme", b"https"),
                (b":path", b""),
                (b":authority", b"example.com"),
            ],
            true,
        );
        assert!(err.is_err(), "empty :path must be rejected");
    }

    #[test]
    fn test_handle_header_rejects_non_origin_form_path() {
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        // absolute-form path (no leading `/`) must be rejected for non-OPTIONS
        let err = try_decode_request_headers(
            &mut pool,
            &[
                (b":method", b"GET"),
                (b":scheme", b"https"),
                (b":path", b"http://attacker/"),
                (b":authority", b"example.com"),
            ],
            true,
        );
        assert!(err.is_err());

        // bare `*` is only valid for OPTIONS
        let err = try_decode_request_headers(
            &mut pool,
            &[
                (b":method", b"GET"),
                (b":scheme", b"https"),
                (b":path", b"*"),
                (b":authority", b"example.com"),
            ],
            true,
        );
        assert!(err.is_err());
    }

    #[test]
    fn test_handle_header_accepts_options_asterisk() {
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let ok = try_decode_request_headers(
            &mut pool,
            &[
                (b":method", b"OPTIONS"),
                (b":scheme", b"https"),
                (b":path", b"*"),
                (b":authority", b"example.com"),
            ],
            true,
        );
        assert!(ok.is_ok(), "OPTIONS * must be accepted, got {ok:?}");
    }

    #[test]
    fn test_handle_header_rejects_bad_scheme() {
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let err = try_decode_request_headers(
            &mut pool,
            &[
                (b":method", b"GET"),
                (b":scheme", b"javascript"),
                (b":path", b"/"),
                (b":authority", b"example.com"),
            ],
            true,
        );
        assert!(err.is_err());

        let err = try_decode_request_headers(
            &mut pool,
            &[
                (b":method", b"GET"),
                (b":scheme", b"file"),
                (b":path", b"/"),
                (b":authority", b"example.com"),
            ],
            true,
        );
        assert!(err.is_err());
    }

    #[test]
    fn test_handle_header_rejects_crlf_in_path_and_authority() {
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let err = try_decode_request_headers(
            &mut pool,
            &[
                (b":method", b"GET"),
                (b":scheme", b"https"),
                (b":path", b"/foo\r\nHost: attacker"),
                (b":authority", b"example.com"),
            ],
            true,
        );
        assert!(err.is_err(), "CRLF in :path must be rejected");

        let err = try_decode_request_headers(
            &mut pool,
            &[
                (b":method", b"GET"),
                (b":scheme", b"https"),
                (b":path", b"/"),
                (b":authority", b"example.com\r\nX: y"),
            ],
            true,
        );
        assert!(err.is_err(), "CRLF in :authority must be rejected");
    }

    #[test]
    fn test_handle_header_rejects_bad_status() {
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        for bad in [&b"20"[..], b"abc", b"+200", b" 200", b"00200", b"2000"] {
            let err = try_decode_response_headers(
                &mut pool,
                &[(b":status", bad), (b"content-type", b"text/html")],
                true,
            );
            assert!(err.is_err(), ":status {bad:?} must be rejected");
        }
    }

    #[test]
    fn test_handle_header_rejects_empty_status() {
        // Response pseudo-header emptiness could slip through
        // if the three-digit guard were removed. Locks in `v.len() != 3` as
        // the rejection gate for an empty :status (HPACK allows zero-length
        // field values, so this must be enforced explicitly). A server
        // emitting :status = "" would otherwise produce a malformed H1
        // response ("HTTP/1.1  FromH2") on the backend side.
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let err = try_decode_response_headers(
            &mut pool,
            &[(b":status", b""), (b"content-type", b"text/html")],
            true,
        );
        assert!(err.is_err(), "empty :status must be rejected");
    }

    #[test]
    fn test_handle_header_rejects_missing_status() {
        // RFC 9113 §8.3.2: response HEADERS MUST contain :status. If no
        // :status pseudo-header is present at all, the post-loop
        // `status.is_empty()` check (line 851 of the production path) is the
        // backstop that converts the absence into a stream-level
        // PROTOCOL_ERROR. Without this test, silently-downgraded-to-H1
        // responses with no status line could slip through.
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let err = try_decode_response_headers(&mut pool, &[(b"content-type", b"text/html")], true);
        assert!(err.is_err(), "response without :status must be rejected");
    }

    #[test]
    fn test_handle_header_rejects_ctl_in_cookie_value() {
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let err = try_decode_request_headers(
            &mut pool,
            &[
                (b":method", b"GET"),
                (b":scheme", b"https"),
                (b":path", b"/"),
                (b":authority", b"example.com"),
                (b"cookie", b"a=1\r\nX-Smuggled: yes"),
            ],
            true,
        );
        assert!(err.is_err(), "CRLF in cookie value must be rejected");
    }

    #[test]
    fn test_handle_header_rejects_ctl_in_cookie_key() {
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let err = try_decode_request_headers(
            &mut pool,
            &[
                (b":method", b"GET"),
                (b":scheme", b"https"),
                (b":path", b"/"),
                (b":authority", b"example.com"),
                (b"cookie", b"a\rb=1"),
            ],
            true,
        );
        assert!(err.is_err(), "CR in cookie key must be rejected");
    }

    // ── write_regular_header: Content-Length digit-only parse ─────────────

    #[test]
    fn test_write_regular_header_content_length_digit_only() {
        // RFC 9113 §8.1.1: Content-Length value MUST be a non-empty sequence
        // of ASCII digits. write_regular_header must reject every non-digit
        // variant before calling usize::from_str so no parser-divergence path
        // reaches the backend.
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);

        let reject_cases: &[(&[u8], &str)] = &[
            (b"", "empty"),
            (b" 42", "leading whitespace"),
            (b"42 ", "trailing whitespace"),
            (b"+42", "unary plus"),
            (b"-42", "negative sign"),
            (b"4\xFF2", "non-ASCII byte"),
            (b"0x10", "non-digit hex chars"),
        ];
        for (val, label) in reject_cases {
            let mut kawa = make_generic_kawa(&mut pool, Kind::Request);
            let result = write_regular_header(&mut kawa, b"content-length", val);
            assert!(
                matches!(result, Err(RejectReason::DuplicateCl)),
                "content-length {label:?} ({val:?}) must yield DuplicateCl, got {result:?}",
            );
        }

        // Valid: a plain digit string must be accepted and set BodySize::Length.
        let mut kawa = make_generic_kawa(&mut pool, Kind::Request);
        let result = write_regular_header(&mut kawa, b"content-length", b"42");
        assert!(
            result.is_ok(),
            "valid content-length '42' was rejected: {result:?}"
        );
        assert_eq!(
            kawa.body_size,
            kawa::BodySize::Length(42),
            "body_size must be Length(42) after parsing '42'",
        );
    }

    #[test]
    fn test_handle_header_rejects_bad_content_length() {
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        // RFC 9110 §8.6 / RFC 9113 §8.1.1: Content-Length is 1*DIGIT.
        // Whitespace, sign, trailing garbage, and non-ASCII must be rejected
        // to avoid parser-divergence against backends.
        for bad in [
            &b" 42"[..], // leading whitespace
            b"+42",      // unary plus
            b"42 ",      // trailing whitespace
            b"-1",       // negative sign
            b"",         // empty
            b"0x10",     // non-digit chars
            b"4\xFF2",   // non-ASCII byte (RFC 9113 §8.1.1: must be digits only)
        ] {
            let err = try_decode_request_headers(
                &mut pool,
                &[
                    (b":method", b"POST"),
                    (b":scheme", b"https"),
                    (b":path", b"/"),
                    (b":authority", b"example.com"),
                    (b"content-length", bad),
                ],
                true,
            );
            assert!(err.is_err(), "content-length {bad:?} must be rejected");
        }

        // Sanity: a clean digit string is accepted.
        let ok = try_decode_request_headers(
            &mut pool,
            &[
                (b":method", b"POST"),
                (b":scheme", b"https"),
                (b":path", b"/"),
                (b":authority", b"example.com"),
                (b"content-length", b"42"),
            ],
            false,
        );
        assert!(ok.is_ok(), "valid content-length must be accepted: {ok:?}");
    }

    // ── handle_trailer: CTL rejection ─────────────────────────────────────

    #[test]
    fn test_handle_trailer_rejects_ctl_in_value() {
        use kawa::Buffer;
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let checkout = pool.checkout().expect("checkout");
        let mut kawa: GenericHttpStream = kawa::Kawa::new(Kind::Request, Buffer::new(checkout));
        // Fake: move out of the initial phase so handle_header routes to
        // handle_trailer. Easiest: push a StatusLine and move the head.
        kawa.push_block(Block::StatusLine);
        kawa.detached.status_line = StatusLine::Request {
            version: Version::V20,
            method: Store::Static(b"GET"),
            uri: Store::Static(b"/"),
            authority: Store::Static(b"example.com"),
            path: Store::Static(b"/"),
        };
        // HPACK-encode a trailer with LF in the value.
        let mut encoder = loona_hpack::Encoder::new();
        let mut encoded = Vec::new();
        encoder
            .encode_header_into((&b"x-trailer"[..], &b"val\nsmuggled"[..]), &mut encoded)
            .unwrap();
        let mut decoder = loona_hpack::Decoder::new();
        let err = handle_trailer(
            &mut kawa,
            &encoded,
            true,
            &mut decoder,
            crate::protocol::mux::h2::MAX_HEADER_LIST_SIZE as u32,
            u32::MAX,
            false,
        );
        assert!(err.is_err(), "LF in trailer value must be rejected");
    }

    #[test]
    fn test_h2_cookie_value_with_equals() {
        // Cookie value containing '=' (e.g., base64-encoded token)
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let kawa = decode_request_headers(
            &mut pool,
            &[
                (b":method", b"GET"),
                (b":scheme", b"https"),
                (b":path", b"/"),
                (b":authority", b"example.com"),
                (b"cookie", b"token=abc=def=="),
            ],
            true,
        );

        assert_eq!(kawa.detached.jar.len(), 1);
        let buf = kawa.storage.buffer();
        assert_eq!(kawa.detached.jar[0].key.data(buf), b"token");
        // Split on FIRST '=' only, so value includes trailing '='
        assert_eq!(kawa.detached.jar[0].val.data(buf), b"abc=def==");
    }

    // ── host vs :authority reconciliation (RFC 9113 §8.3.1) ───────────

    #[test]
    fn test_strip_port_and_host_authority_match() {
        assert_eq!(strip_port(b"example.com"), b"example.com");
        assert_eq!(strip_port(b"example.com:8443"), b"example.com");
        assert_eq!(strip_port(b"example.com:abc"), b"example.com:abc");
        // IPv6 bracketed literals
        assert_eq!(strip_port(b"[::1]:8443"), b"[::1]");
        assert_eq!(strip_port(b"[::1]"), b"[::1]");
        assert_eq!(strip_port(b"[::1]:"), b"[::1]:");
        // Trailing colon with empty port must NOT strip (not a valid port)
        assert_eq!(strip_port(b"example.com:"), b"example.com:");

        // Both without port
        assert!(host_matches_authority(b"example.com", b"example.com"));
        // Case insensitive, same port
        assert!(host_matches_authority(b"Example.COM:80", b"example.com:80"));
        // Case insensitive, no port
        assert!(host_matches_authority(b"Example.com", b"example.com"));
        // Same explicit port
        assert!(host_matches_authority(b"example.com:80", b"example.com:80"));
        // One has port, one implicit
        assert!(host_matches_authority(b"example.com:80", b"example.com"));
        assert!(host_matches_authority(b"example.com", b"example.com:443"));
        // Different explicit ports → different origins (RFC 6454 §5)
        assert!(!host_matches_authority(
            b"example.com:80",
            b"example.com:443"
        ));
        assert!(!host_matches_authority(b"evil.com", b"example.com"));
        assert!(!host_matches_authority(b"example.com.evil", b"example.com"));
    }

    #[test]
    fn test_handle_header_host_matches_authority_is_deduplicated() {
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let kawa = decode_request_headers(
            &mut pool,
            &[
                (b":method", b"GET"),
                (b":scheme", b"https"),
                (b":path", b"/"),
                (b":authority", b"example.com"),
                (b"host", b"Example.com"),
            ],
            true,
        );
        // Literal ``host`` must not be emitted as a regular Header block —
        // kawa's H1 converter serialises Host: from :authority on its own.
        let buf = kawa.storage.buffer();
        for block in kawa.blocks.iter() {
            if let Block::Header(pair) = block {
                assert!(
                    !compare_no_case(pair.key.data(buf), b"host"),
                    "literal host header must be dropped when it matches :authority"
                );
            }
        }
    }

    #[test]
    fn test_handle_header_host_mismatch_rejected() {
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let err = try_decode_request_headers(
            &mut pool,
            &[
                (b":method", b"GET"),
                (b":scheme", b"https"),
                (b":path", b"/"),
                (b":authority", b"example.com"),
                (b"host", b"evil.com"),
            ],
            true,
        );
        assert!(
            matches!(err, Err((H2Error::ProtocolError, _))),
            "host != :authority must yield PROTOCOL_ERROR, got {err:?}"
        );
    }

    #[test]
    fn test_handle_header_multiple_disagreeing_host_rejected() {
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let err = try_decode_request_headers(
            &mut pool,
            &[
                (b":method", b"GET"),
                (b":scheme", b"https"),
                (b":path", b"/"),
                (b":authority", b"example.com"),
                (b"host", b"example.com"),
                (b"host", b"evil.com"),
            ],
            true,
        );
        assert!(
            matches!(err, Err((H2Error::ProtocolError, _))),
            "disagreeing host headers must yield PROTOCOL_ERROR, got {err:?}"
        );
    }

    #[test]
    fn test_handle_header_host_with_port_matches_authority() {
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let kawa = decode_request_headers(
            &mut pool,
            &[
                (b":method", b"GET"),
                (b":scheme", b"https"),
                (b":path", b"/"),
                (b":authority", b"example.com"),
                (b"host", b"example.com:8443"),
            ],
            true,
        );
        let buf = kawa.storage.buffer();
        for block in kawa.blocks.iter() {
            if let Block::Header(pair) = block {
                assert!(
                    !compare_no_case(pair.key.data(buf), b"host"),
                    "literal host header must be dropped (port-stripped match)"
                );
            }
        }
    }

    #[test]
    fn test_handle_header_host_crlf_rejected() {
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let err = try_decode_request_headers(
            &mut pool,
            &[
                (b":method", b"GET"),
                (b":scheme", b"https"),
                (b":path", b"/"),
                (b":authority", b"example.com"),
                (b"host", b"example.com\r\nX-Smuggled: yes"),
            ],
            true,
        );
        assert!(err.is_err(), "CRLF in host header must be rejected");
    }

    // ── H2→H1 trailer / Transfer-Encoding invariants ──────────────────────

    /// H2 request without END_STREAM and without Content-Length MUST gain
    /// `Transfer-Encoding: chunked` so the H1 backend can frame the body
    /// and any subsequent trailer HEADERS frame.
    #[test]
    fn test_h2_to_h1_body_without_content_length_forces_chunked() {
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let kawa = decode_request_headers(
            &mut pool,
            &[
                (b":method", b"POST"),
                (b":scheme", b"https"),
                (b":path", b"/upload"),
                (b":authority", b"example.com"),
            ],
            false, // body follows
        );
        assert_eq!(kawa.body_size, BodySize::Chunked);
        let buf = kawa.storage.buffer();
        let has_te_chunked = kawa.blocks.iter().any(|b| {
            matches!(b, Block::Header(Pair { key, val })
                if key.data(buf).eq_ignore_ascii_case(b"Transfer-Encoding")
                    && val.data(buf).eq_ignore_ascii_case(b"chunked"))
        });
        assert!(
            has_te_chunked,
            "H2→H1 chunked body must emit Transfer-Encoding: chunked for trailer support"
        );
    }
    // ── handle_trailer: spoof-vector elision per RFC 9110 §6.5 ───────────

    /// Helper: HPACK-encode a set of trailer pairs and run them through
    /// `handle_trailer`. Returns the kawa stream so the caller can
    /// inspect which trailer headers landed in `kawa.blocks`.
    fn decode_trailer(
        pool: &mut crate::pool::Pool,
        trailers: &[(&[u8], &[u8])],
    ) -> GenericHttpStream {
        let mut encoder = loona_hpack::Encoder::new();
        let mut encoded = Vec::new();
        for &(name, value) in trailers {
            encoder
                .encode_header_into((name, value), &mut encoded)
                .unwrap();
        }

        let mut decoder = loona_hpack::Decoder::new();
        let mut kawa = make_generic_kawa(pool, Kind::Request);

        let result = handle_trailer(
            &mut kawa,
            &encoded,
            true, // end_stream
            &mut decoder,
            crate::protocol::mux::h2::MAX_HEADER_LIST_SIZE as u32,
            u32::MAX,
            false, // elide_x_real_ip — listener flag, not the trailer-side gate
        );
        assert!(result.is_ok(), "handle_trailer failed: {:?}", result.err());
        kawa
    }

    /// Returns the lowercased trailer keys that survived the elision filter.
    fn surviving_trailer_keys(kawa: &GenericHttpStream) -> Vec<Vec<u8>> {
        let buf = kawa.storage.buffer();
        kawa.blocks
            .iter()
            .filter_map(|b| match b {
                Block::Header(Pair { key, .. }) => Some(key.data(buf).to_vec()),
                _ => None,
            })
            .collect()
    }

    /// RFC 9110 §6.5 forbids trailers from carrying message-routing
    /// fields. The initial-HEADERS path rewrites four client-attribution
    /// headers (`X-Real-IP`, `X-Forwarded-For`, `Forwarded`,
    /// `X-Request-Id`). An H2 client must not be able to smuggle a
    /// spoofed copy as a trailer, since H2 backends that merge trailers
    /// into their header view would observe the attacker-controlled
    /// value. Drop them unconditionally.
    #[test]
    fn handle_trailer_elides_spoof_vector_headers() {
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let kawa = decode_trailer(
            &mut pool,
            &[
                (b"x-real-ip", b"1.2.3.4"),
                (b"x-forwarded-for", b"5.6.7.8"),
                (b"forwarded", b"for=9.10.11.12"),
                (b"x-request-id", b"attacker-correlation-id"),
                (b"x-trailer-keep", b"please-keep-me"),
            ],
        );
        let surviving = surviving_trailer_keys(&kawa);
        assert_eq!(
            surviving,
            vec![b"x-trailer-keep".to_vec()],
            "only non-spoof trailers must survive the RFC 9110 §6.5 elision"
        );
    }

    /// Each of the four spoof-vector headers must be dropped on its own,
    /// so a single-trailer attempt cannot bypass the filter just because
    /// the others are absent.
    #[test]
    fn handle_trailer_drops_each_spoof_header_individually() {
        for &name in &[
            b"x-real-ip" as &[u8],
            b"x-forwarded-for",
            b"forwarded",
            b"x-request-id",
        ] {
            let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
            let kawa = decode_trailer(&mut pool, &[(name, b"v")]);
            let surviving = surviving_trailer_keys(&kawa);
            assert!(
                surviving.is_empty(),
                "trailer with only {} should leave no surviving block",
                std::str::from_utf8(name).unwrap()
            );
        }
    }

    /// Sanity: an unrelated trailer (e.g. `grpc-status`) is still kept.
    /// Without this we'd be silently breaking gRPC semantics.
    #[test]
    fn handle_trailer_keeps_grpc_status() {
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let kawa = decode_trailer(&mut pool, &[(b"grpc-status", b"0")]);
        let surviving = surviving_trailer_keys(&kawa);
        assert_eq!(surviving, vec![b"grpc-status".to_vec()]);
    }

    /// H2 request declaring Content-Length keeps the Length framing: the
    /// H1 backend cannot receive trailers in this case (RFC 9110 §6.5 —
    /// trailers require chunked transfer-coding), and we document that
    /// the caller must drop trailers rather than retro-fit Transfer-Encoding
    /// once the request headers have already gone out on the wire.
    #[test]
    fn test_h2_to_h1_body_with_content_length_keeps_length_framing() {
        let mut pool = crate::pool::Pool::with_capacity(1, 1, 4096);
        let kawa = decode_request_headers(
            &mut pool,
            &[
                (b":method", b"POST"),
                (b":scheme", b"https"),
                (b":path", b"/upload"),
                (b":authority", b"example.com"),
                (b"content-length", b"42"),
            ],
            false,
        );
        assert_eq!(kawa.body_size, BodySize::Length(42));
        let buf = kawa.storage.buffer();
        let has_te = kawa.blocks.iter().any(|b| {
            matches!(b, Block::Header(Pair { key, .. })
                if key.data(buf).eq_ignore_ascii_case(b"Transfer-Encoding"))
        });
        assert!(
            !has_te,
            "Transfer-Encoding must not be retro-fitted when Content-Length was declared"
        );
    }
}