eggress-protocol-http 1.0.3

HTTP/1.1 CONNECT protocol for eggress proxy
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
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};

use crate::error::HttpError;
use eggress_core::{BoxStream, TargetAddr, TargetHost};

/// Limits for body copying.
pub struct BodyCopyLimits {
    pub max_chunk_size_line: usize,
    pub max_chunk_size: u64,
    pub max_decoded_body: u64,
    pub max_trailer_line: usize,
    pub max_trailer_bytes: usize,
}

impl Default for BodyCopyLimits {
    fn default() -> Self {
        Self {
            max_chunk_size_line: 1024,
            max_chunk_size: 64 * 1024 * 1024,
            max_decoded_body: 64 * 1024 * 1024,
            max_trailer_line: 8192,
            max_trailer_bytes: 32 * 1024,
        }
    }
}

/// Report from body copying.
#[derive(Debug, Default)]
pub struct BodyCopyReport {
    pub wire_bytes: u64,
    pub decoded_bytes: u64,
}

/// Report from forwarding a response.
#[derive(Debug, Default)]
pub struct ForwardResponseReport {
    pub bytes_forwarded: u64,
}

/// Copy a request body from reader to writer.
///
/// For Content-Length bodies, copies exactly `len` bytes.
/// For chunked bodies, parses and forwards chunks with proper bounds.
/// Returns byte counts for accounting.
pub async fn copy_request_body<R, W>(
    reader: &mut R,
    writer: &mut W,
    kind: RequestBodyKind,
    limits: &BodyCopyLimits,
) -> Result<BodyCopyReport, HttpError>
where
    R: AsyncRead + Unpin,
    W: AsyncWrite + Unpin,
{
    match kind {
        RequestBodyKind::None => Ok(BodyCopyReport::default()),
        RequestBodyKind::ContentLength(len) => {
            if len > limits.max_decoded_body {
                return Err(HttpError::MalformedRequest("decoded body too large".into()));
            }
            copy_content_length_body(reader, writer, len).await
        }
        RequestBodyKind::Chunked => copy_chunked_body(reader, writer, limits).await,
    }
}

async fn copy_content_length_body<R, W>(
    reader: &mut R,
    writer: &mut W,
    len: u64,
) -> Result<BodyCopyReport, HttpError>
where
    R: AsyncRead + Unpin,
    W: AsyncWrite + Unpin,
{
    let mut remaining = len;
    let mut buf = [0u8; 8192];
    while remaining > 0 {
        let to_read = (remaining as usize).min(buf.len());
        let n = reader.read(&mut buf[..to_read]).await?;
        if n == 0 {
            return Err(HttpError::MalformedRequest("unexpected EOF in body".into()));
        }
        writer.write_all(&buf[..n]).await?;
        remaining -= n as u64;
    }
    Ok(BodyCopyReport {
        wire_bytes: len,
        decoded_bytes: len,
    })
}

async fn copy_chunked_body<R, W>(
    reader: &mut R,
    writer: &mut W,
    limits: &BodyCopyLimits,
) -> Result<BodyCopyReport, HttpError>
where
    R: AsyncRead + Unpin,
    W: AsyncWrite + Unpin,
{
    let mut wire_bytes: u64 = 0;
    let mut decoded_bytes: u64 = 0;

    loop {
        // Read chunk size line
        let size_line = read_bounded_line(reader, limits.max_chunk_size_line).await?;
        wire_bytes += size_line.len() as u64;

        // Parse chunk size (ignore extensions after ';')
        let chunk_size = parse_chunk_size(&size_line)?;

        // Forward the size line
        writer.write_all(&size_line).await?;

        if chunk_size == 0 {
            // Read and forward trailers
            let mut trailer_bytes: u64 = 0;
            loop {
                let trailer = read_bounded_line(reader, limits.max_trailer_line).await?;
                wire_bytes += trailer.len() as u64;
                trailer_bytes += trailer.len() as u64;

                if trailer_bytes > limits.max_trailer_bytes as u64 {
                    return Err(HttpError::MalformedRequest("trailers too large".into()));
                }

                writer.write_all(&trailer).await?;

                if trailer == b"\r\n" {
                    break;
                }
            }
            break;
        }

        // Validate chunk size against limit
        if chunk_size > limits.max_chunk_size {
            return Err(HttpError::MalformedRequest("chunk too large".into()));
        }

        // Validate decoded body limit
        decoded_bytes = decoded_bytes
            .checked_add(chunk_size)
            .ok_or_else(|| HttpError::MalformedRequest("decoded body too large".into()))?;
        if decoded_bytes > limits.max_decoded_body {
            return Err(HttpError::MalformedRequest("decoded body too large".into()));
        }

        // Read exactly chunk_size data bytes
        let mut remaining = chunk_size;
        let mut buf = [0u8; 8192];
        while remaining > 0 {
            let to_read = (remaining as usize).min(buf.len());
            let n = reader.read(&mut buf[..to_read]).await?;
            if n == 0 {
                return Err(HttpError::MalformedRequest(
                    "unexpected EOF in chunk data".into(),
                ));
            }
            writer.write_all(&buf[..n]).await?;
            remaining -= n as u64;
            wire_bytes += n as u64;
        }

        // Read and verify CRLF after chunk data
        let mut crlf = [0u8; 2];
        reader.read_exact(&mut crlf).await?;
        wire_bytes += 2;
        if crlf != *b"\r\n" {
            return Err(HttpError::MalformedRequest(
                "missing CRLF after chunk data".into(),
            ));
        }
        writer.write_all(&crlf).await?;
    }

    Ok(BodyCopyReport {
        wire_bytes,
        decoded_bytes,
    })
}

/// Read a bounded line terminated by \r\n.
async fn read_bounded_line<R: AsyncRead + Unpin>(
    reader: &mut R,
    max_len: usize,
) -> Result<Vec<u8>, HttpError> {
    let mut line = Vec::new();
    let mut temp = [0u8; 1];
    loop {
        if line.len() >= max_len {
            return Err(HttpError::MalformedRequest("line too long".into()));
        }
        let n = reader.read(&mut temp).await?;
        if n == 0 {
            if line.is_empty() {
                return Err(HttpError::MalformedRequest("unexpected EOF".into()));
            }
            return Err(HttpError::MalformedRequest("incomplete line".into()));
        }
        line.push(temp[0]);
        if line.len() >= 2 && &line[line.len() - 2..] == b"\r\n" {
            break;
        }
    }
    Ok(line)
}

async fn read_bounded_line_into<R: AsyncRead + Unpin>(
    reader: &mut R,
    line: &mut Vec<u8>,
    max_len: usize,
) -> Result<(), HttpError> {
    let mut temp = [0u8; 1];
    loop {
        if line.len() >= max_len {
            return Err(HttpError::MalformedResponse("line too long".into()));
        }
        let n = reader.read(&mut temp).await?;
        if n == 0 {
            if line.is_empty() {
                return Err(HttpError::MalformedResponse("unexpected EOF".into()));
            }
            return Err(HttpError::MalformedResponse("incomplete line".into()));
        }
        line.push(temp[0]);
        if line.len() >= 2 && &line[line.len() - 2..] == b"\r\n" {
            break;
        }
    }
    Ok(())
}

/// Parse a chunk size from a line (without trailing CRLF).
/// Supports hex with optional extensions (after ';').
fn parse_chunk_size(line_without_crlf: &[u8]) -> Result<u64, HttpError> {
    let size_field = line_without_crlf
        .split(|b| *b == b';')
        .next()
        .ok_or_else(|| HttpError::MalformedRequest("empty chunk size".into()))?;

    if size_field.is_empty() {
        return Err(HttpError::MalformedRequest("empty chunk size".into()));
    }

    let size_str = std::str::from_utf8(size_field)
        .map_err(|_| HttpError::MalformedRequest("invalid chunk size encoding".into()))?;
    let size_str = size_str.trim();

    u64::from_str_radix(size_str, 16)
        .map_err(|_| HttpError::MalformedRequest("invalid chunk size".into()))
}

/// Describes how the request body is framed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RequestBodyKind {
    None,
    ContentLength(u64),
    Chunked,
}

/// Determine the request body framing from parsed headers.
///
/// Validates:
/// - Content-Length values (reject conflicting, accept equal duplicates)
/// - Transfer-Encoding (reject TE + CL, require chunked to be final)
/// - Only "chunked" transfer coding is supported in Phase 1
pub fn determine_request_body_kind(
    headers: &[(String, String)],
) -> Result<RequestBodyKind, HttpError> {
    let mut content_lengths: Vec<u64> = Vec::new();
    let mut transfer_encodings: Vec<String> = Vec::new();

    for (name, value) in headers {
        if name.eq_ignore_ascii_case("Content-Length") {
            // Parse each Content-Length value
            let len = value
                .trim()
                .parse::<u64>()
                .map_err(|_| HttpError::InvalidContentLength)?;
            content_lengths.push(len);
        } else if name.eq_ignore_ascii_case("Transfer-Encoding") {
            // Split comma-separated transfer codings
            for coding in value.split(',') {
                let coding = coding.trim().to_string();
                if !coding.is_empty() {
                    transfer_encodings.push(coding);
                }
            }
        }
    }

    // Validate Content-Length
    if !content_lengths.is_empty() {
        // All values must be identical
        let first = content_lengths[0];
        if content_lengths.iter().any(|&cl| cl != first) {
            return Err(HttpError::ConflictingContentLength);
        }
    }

    // Validate Transfer-Encoding
    if !transfer_encodings.is_empty() {
        // TE + CL is rejected in Phase 1
        if !content_lengths.is_empty() {
            return Err(HttpError::TransferEncodingWithContentLength);
        }

        // Check if chunked is present but not the final coding
        let has_chunked = transfer_encodings
            .iter()
            .any(|c| c.eq_ignore_ascii_case("chunked"));
        if has_chunked {
            let last = transfer_encodings.last().unwrap();
            if !last.eq_ignore_ascii_case("chunked") {
                return Err(HttpError::ChunkedNotFinal);
            }
        }

        // Only "chunked" is supported in Phase 1
        for coding in &transfer_encodings {
            if !coding.eq_ignore_ascii_case("chunked") {
                return Err(HttpError::UnsupportedTransferEncoding(coding.clone()));
            }
        }

        return Ok(RequestBodyKind::Chunked);
    }

    if let Some(len) = content_lengths.first() {
        Ok(RequestBodyKind::ContentLength(*len))
    } else {
        Ok(RequestBodyKind::None)
    }
}

/// Maximum size for the HTTP request head (request line + headers).
const MAX_HEAD_SIZE: usize = 32 * 1024;

/// Maximum size for the HTTP response head.
const MAX_RESPONSE_HEAD_SIZE: usize = 32 * 1024;

/// Bound informational responses so an upstream cannot keep the proxy in a
/// response-head loop indefinitely.
const MAX_INFORMATIONAL_RESPONSES: usize = 8;

/// Maximum number of header lines.
const MAX_HEADER_LINES: usize = 128;

/// Bound a response chunk before converting it to a platform `usize`.
const MAX_RESPONSE_CHUNK_SIZE: u64 = 64 * 1024 * 1024;

/// Total byte budget for chunked-response trailers after the terminating
/// zero chunk, so an upstream cannot stream them indefinitely.
const MAX_TRAILER_BYTES: usize = 64 * 1024;

/// Headers that must not be forwarded across a proxy (RFC 2616 §13.5.1).
///
/// `Transfer-Encoding: chunked` is preserved because the chunked body is
/// forwarded unchanged.
fn is_hop_by_hop_header(name: &str, value: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    match lower.as_str() {
        "transfer-encoding" => !value.eq_ignore_ascii_case("chunked"),
        _ => matches!(
            lower.as_str(),
            "connection"
                | "keep-alive"
                | "proxy-authenticate"
                | "proxy-authorization"
                | "te"
                | "trailers"
                | "upgrade"
                | "proxy-connection"
        ),
    }
}

/// Extract tokens from the `Connection` header value.
///
/// Per RFC 7230 §6.1, each token names a header that must be removed before
/// forwarding.
fn connection_tokens(headers: &[(String, String)]) -> std::collections::HashSet<String> {
    headers
        .iter()
        .filter(|(name, _)| name.eq_ignore_ascii_case("connection"))
        .flat_map(|(_, value)| value.split(','))
        .map(|token| token.trim().to_ascii_lowercase())
        .filter(|token| !token.is_empty())
        .collect()
}

/// Filter hop-by-hop headers from a header list, returning only end-to-end headers.
///
/// Removes standard hop-by-hop headers plus any headers nominated by
/// `Connection` tokens.  Preserves `Transfer-Encoding: chunked`.
pub fn filter_hop_by_hop(headers: &[(String, String)]) -> Vec<(String, String)> {
    let nominated = connection_tokens(headers);
    headers
        .iter()
        .filter(|(name, value)| {
            let lower = name.to_ascii_lowercase();
            !is_hop_by_hop_header(&lower, value) && !nominated.contains(&lower)
        })
        .cloned()
        .collect()
}

/// Return whether the request contains an expectation this forwarder cannot
/// negotiate. Expectation values are collected case-insensitively and comma-
/// separated values are treated independently.
pub fn has_unsupported_expectation(headers: &[(String, String)]) -> bool {
    headers.iter().any(|(name, value)| {
        name.eq_ignore_ascii_case("Expect")
            && value
                .split(',')
                .any(|expectation| !expectation.trim().is_empty())
    })
}

/// Build an origin-form HTTP request to send to the upstream server.
///
/// Converts the parsed absolute-form request into origin-form by:
/// - Using only the path component as the request target
/// - Filtering out hop-by-hop headers
/// - Adding `Connection: close` to avoid keep-alive complications
pub fn build_origin_request(request: &ForwardRequest) -> String {
    let filtered = filter_hop_by_hop(&request.headers);

    let mut req = format!(
        "{} {} {}\r\n",
        request.method, request.path, request.version
    );

    for (name, value) in &filtered {
        req.push_str(&format!("{}: {}\r\n", name, value));
    }

    // Ensure Connection: close for Phase 1 (no persistent forwarding)
    if !filtered
        .iter()
        .any(|(n, _)| n.eq_ignore_ascii_case("Connection"))
    {
        req.push_str("Connection: close\r\n");
    }

    req.push_str("\r\n");
    req
}

/// Parsed HTTP response from an upstream server.
#[derive(Debug)]
pub struct ForwardResponse {
    pub version: String,
    pub status: u16,
    pub reason: String,
    pub headers: Vec<(String, String)>,
    pub content_length: Option<u64>,
    pub is_chunked: bool,
    /// True if the upstream sent `Connection: close`.
    pub connection_close: bool,
}

/// Read and parse an HTTP response head from the upstream.
///
/// `stream` is typically a `BufReader<&mut BoxStream>` so per-byte header
/// scans are served from the 8 KiB buffer rather than issuing a syscall per
/// header byte (B-01).
async fn read_response_head<R: AsyncRead + Unpin>(
    stream: &mut R,
) -> Result<ForwardResponse, HttpError> {
    let mut head_buf = Vec::with_capacity(1024);
    let mut temp = [0u8; 1];
    // Track `\r\n` occurrences during the read so that a flood of empty
    // header lines cannot slip under MAX_RESPONSE_HEAD_SIZE while still
    // exceeding the per-line limit.
    let mut crlf_count: usize = 0;

    loop {
        if head_buf.len() >= MAX_RESPONSE_HEAD_SIZE {
            return Err(HttpError::HeaderTooLarge);
        }

        let n = stream.read(&mut temp).await?;
        if n == 0 {
            return Err(HttpError::MalformedResponse(
                "unexpected EOF reading response".into(),
            ));
        }

        head_buf.push(temp[0]);

        if head_buf.len() >= 2 {
            let len = head_buf.len();
            if &head_buf[len - 2..] == b"\r\n" {
                crlf_count += 1;
                // The status line and the terminating empty line also have
                // CRLFs, but are not header lines.
                if crlf_count > MAX_HEADER_LINES + 2 {
                    return Err(HttpError::TooManyHeaders);
                }
            }
        }

        if head_buf.len() >= 4 {
            let len = head_buf.len();
            if &head_buf[len - 4..] == b"\r\n\r\n" {
                break;
            }
        }
    }

    let head_str = String::from_utf8_lossy(&head_buf);
    let mut lines = head_str.split("\r\n");

    // Parse status line
    let status_line = lines
        .next()
        .ok_or_else(|| HttpError::MalformedResponse("empty response".into()))?;

    let parts: Vec<&str> = status_line.split_whitespace().collect();
    if parts.len() < 2 {
        return Err(HttpError::MalformedResponse(format!(
            "invalid status line: {}",
            status_line
        )));
    }

    let version = parts[0].to_string();
    let status: u16 = parts[1]
        .parse()
        .map_err(|e| HttpError::MalformedResponse(format!("invalid status code: {}", e)))?;
    let reason = parts.get(2).unwrap_or(&"").to_string();

    // Parse response headers
    let mut headers = Vec::new();
    let mut content_length = None;
    let mut is_chunked = false;
    let mut connection_close = false;

    let mut header_count = 0;
    for line in lines {
        if line.is_empty() {
            break;
        }
        header_count += 1;
        if header_count > MAX_HEADER_LINES {
            return Err(HttpError::TooManyHeaders);
        }
        if let Some((name, value)) = parse_header_line(line) {
            if name.eq_ignore_ascii_case("Content-Length") {
                let parsed = value
                    .parse::<u64>()
                    .map_err(|_| HttpError::InvalidContentLength)?;
                if content_length.is_some_and(|previous| previous != parsed) {
                    return Err(HttpError::ConflictingContentLength);
                }
                content_length = Some(parsed);
            } else if name.eq_ignore_ascii_case("Transfer-Encoding") {
                for coding in value.split(',') {
                    let coding_name = coding.trim().split(';').next().unwrap_or("").trim();
                    if coding_name.eq_ignore_ascii_case("chunked") {
                        is_chunked = true;
                    }
                }
            } else if name.eq_ignore_ascii_case("Connection") {
                // Check for "close" token (case-insensitive)
                connection_close = value
                    .split(',')
                    .any(|t| t.trim().eq_ignore_ascii_case("close"));
            }
            headers.push((name, value));
        }
    }

    // Per RFC 7230 §3.3.3, when both Content-Length and Transfer-Encoding
    // are present, Transfer-Encoding takes precedence. A proxy MUST ignore
    // Content-Length if Transfer-Encoding is present.
    if is_chunked {
        content_length = None;
    }

    Ok(ForwardResponse {
        version,
        status,
        reason,
        headers,
        content_length,
        is_chunked,
        connection_close,
    })
}

fn format_response_head(
    response: &ForwardResponse,
    force_close: bool,
) -> Result<String, HttpError> {
    let filtered = filter_hop_by_hop(&response.headers);
    if !response
        .reason
        .bytes()
        .all(|byte| (0x20..=0x7e).contains(&byte))
    {
        return Err(HttpError::MalformedResponse(
            "response reason contains non-printable bytes".into(),
        ));
    }
    let mut head = format!("HTTP/1.1 {} {}\r\n", response.status, response.reason);

    for (name, value) in &filtered {
        if name.contains(['\r', '\n']) || value.contains(['\r', '\n']) {
            return Err(HttpError::MalformedResponse(
                "response header contains a line break".into(),
            ));
        }
        head.push_str(&format!("{}: {}\r\n", name, value));
    }

    if force_close
        && !filtered
            .iter()
            .any(|(n, _)| n.eq_ignore_ascii_case("Connection"))
    {
        head.push_str("Connection: close\r\n");
    }

    head.push_str("\r\n");
    Ok(head)
}

/// Result of forwarding a response, including upstream connection state.
pub struct ForwardResult {
    pub report: ForwardResponseReport,
    /// HTTP status code of the forwarded response.
    pub status: u16,
    /// True if the upstream connection is still usable (no `Connection: close`).
    pub upstream_alive: bool,
    /// True if the response status indicates the client should not retry.
    pub client_should_close: bool,
}

/// Forward the upstream response back to the client stream.
///
/// Writes the response status line and filtered headers to the client,
/// then relays the body (if any) using content-length or chunked framing.
pub async fn forward_response(
    upstream: &mut BoxStream,
    client: &mut BoxStream,
) -> Result<ForwardResult, HttpError> {
    // Buffer upstream reads so single-byte header scans do not issue a
    // syscall per header byte (B-01/O-01). The BufReader preserves any
    // bytes read ahead of the body for the subsequent relay loops.
    let mut upstream_buf = tokio::io::BufReader::new(&mut *upstream);
    let mut informational_responses = 0;
    let mut bytes_forwarded: u64 = 0;
    let response = loop {
        let response = read_response_head(&mut upstream_buf).await?;
        if response.status == 101 {
            return Err(HttpError::UpgradeUnsupported);
        }
        if (100..200).contains(&response.status) {
            informational_responses += 1;
            if informational_responses > MAX_INFORMATIONAL_RESPONSES {
                return Err(HttpError::TooManyInformationalResponses);
            }
            let head = format_response_head(&response, false)?;
            client.write_all(head.as_bytes()).await?;
            bytes_forwarded += head.len() as u64;
            continue;
        }
        break response;
    };
    let head = format_response_head(&response, true)?;
    client.write_all(head.as_bytes()).await?;
    bytes_forwarded += head.len() as u64;

    // Relay body based on framing
    let mut eof_framing = false;
    match (response.content_length, response.is_chunked) {
        (Some(len), _) => {
            let mut remaining = len;
            let mut buf = [0u8; 8192];
            while remaining > 0 {
                let to_read = (remaining as usize).min(buf.len());
                let n = upstream_buf.read(&mut buf[..to_read]).await?;
                if n == 0 {
                    return Err(HttpError::MalformedResponse(
                        "unexpected EOF in response body".into(),
                    ));
                }
                client.write_all(&buf[..n]).await?;
                bytes_forwarded += n as u64;
                remaining -= n as u64;
            }
        }
        (None, true) => {
            let mut size_line_buf = Vec::new();
            loop {
                size_line_buf.clear();
                read_bounded_line_into(&mut upstream_buf, &mut size_line_buf, 1024).await?;

                let size_str = String::from_utf8_lossy(&size_line_buf);
                let size_str = size_str.trim_end_matches("\r\n");
                let size_str = size_str.split(';').next().unwrap_or("").trim();
                let chunk_size = u64::from_str_radix(size_str, 16).map_err(|e| {
                    HttpError::MalformedResponse(format!("invalid chunk size: {}", e))
                })?;
                if chunk_size > MAX_RESPONSE_CHUNK_SIZE {
                    return Err(HttpError::MalformedResponse(
                        "response chunk too large".into(),
                    ));
                }

                client.write_all(&size_line_buf).await?;
                bytes_forwarded += size_line_buf.len() as u64;

                if chunk_size == 0 {
                    let mut trailer_total = 0usize;
                    loop {
                        let mut trailer = Vec::new();
                        read_bounded_line_into(&mut upstream_buf, &mut trailer, 8192).await?;
                        trailer_total += trailer.len();
                        if trailer_total > MAX_TRAILER_BYTES {
                            return Err(HttpError::MalformedResponse(
                                "response trailers exceed maximum total size".into(),
                            ));
                        }
                        client.write_all(&trailer).await?;
                        bytes_forwarded += trailer.len() as u64;
                        if trailer == b"\r\n" {
                            break;
                        }
                        if !trailer.ends_with(b"\r\n") {
                            break;
                        }
                    }
                    break;
                }

                let mut remaining =
                    usize::try_from(chunk_size.checked_add(2).ok_or_else(|| {
                        HttpError::MalformedResponse("response chunk size overflow".into())
                    })?)
                    .map_err(|_| HttpError::MalformedResponse("response chunk too large".into()))?;
                let mut buf = [0u8; 8192];
                while remaining > 0 {
                    let to_read = remaining.min(buf.len());
                    let n = upstream_buf.read(&mut buf[..to_read]).await?;
                    if n == 0 {
                        return Ok(ForwardResult {
                            report: ForwardResponseReport { bytes_forwarded },
                            status: response.status,
                            upstream_alive: false,
                            client_should_close: true,
                        });
                    }
                    client.write_all(&buf[..n]).await?;
                    bytes_forwarded += n as u64;
                    remaining -= n;
                }
            }
        }
        (None, false) => {
            // No Content-Length and no Transfer-Encoding: the response body
            // ends at connection close, so the upstream is fully drained.
            eof_framing = true;
            let mut buf = [0u8; 8192];
            loop {
                let n = upstream_buf.read(&mut buf).await?;
                if n == 0 {
                    break;
                }
                client.write_all(&buf[..n]).await?;
                bytes_forwarded += n as u64;
            }
        }
    }

    // Determine upstream alive: HTTP/1.1 default is keep-alive, HTTP/1.0 default is close
    let mut upstream_alive = if response.connection_close {
        false
    } else if response.version.contains("1.1") {
        true
    } else {
        // HTTP/1.0: alive only if explicitly requested via Keep-Alive
        response
            .headers
            .iter()
            .any(|(n, v)| n.eq_ignore_ascii_case("Keep-Alive") && !v.is_empty())
    };
    if eof_framing {
        // A connection closed by EOF framing can never be reused.
        upstream_alive = false;
    }

    // Client should close if the upstream said close
    let client_should_close = response.connection_close;

    Ok(ForwardResult {
        report: ForwardResponseReport { bytes_forwarded },
        status: response.status,
        upstream_alive,
        client_should_close,
    })
}

/// A parsed HTTP request ready for forwarding.
#[derive(Debug, Clone)]
pub struct ForwardRequest {
    pub method: String,
    pub path: String,
    pub version: String,
    pub headers: Vec<(String, String)>,
    pub target: TargetAddr,
    pub has_body: bool,
    pub content_length: Option<u64>,
    pub is_chunked: bool,
    /// True if the client sent `Connection: close`.
    pub connection_close: bool,
}

impl ForwardRequest {
    /// Compute the request body kind from parsed fields.
    pub fn body_kind(&self) -> RequestBodyKind {
        if self.is_chunked {
            RequestBodyKind::Chunked
        } else if let Some(len) = self.content_length {
            RequestBodyKind::ContentLength(len)
        } else {
            RequestBodyKind::None
        }
    }
}

/// Forward an HTTP request from a client to the target server.
///
/// Parses the absolute-form request, converts to origin-form, forwards
/// the request, and returns the response.
///
/// # Arguments
/// * `stream` - The client stream
///
/// # Returns
/// The parsed forward request and the target address to connect to.
pub async fn forward_request(stream: BoxStream) -> Result<(ForwardRequest, BoxStream), HttpError> {
    // Buffer reads so the incremental head parse does not issue one
    // syscall per byte; unconsumed prefetch stays available to later
    // reads on the returned stream (including keep-alive re-parses).
    let mut stream: BoxStream = Box::new(tokio::io::BufReader::new(stream));
    let request = read_forward_request(&mut stream).await?;
    Ok((request, stream))
}

/// Read and parse an HTTP forward request from an existing stream.
///
/// Unlike [`forward_request`], this borrows the stream rather than
/// consuming it, enabling persistent-session loops.
pub async fn forward_request_stream(stream: &mut BoxStream) -> Result<ForwardRequest, HttpError> {
    read_forward_request(stream).await
}

/// Read and parse an HTTP forward request with absolute-form target.
async fn read_forward_request(stream: &mut BoxStream) -> Result<ForwardRequest, HttpError> {
    let mut head_buf = Vec::with_capacity(1024);
    let mut temp = [0u8; 1];
    let mut header_count = 0;
    let mut saw_request_line = false;

    loop {
        if head_buf.len() >= MAX_HEAD_SIZE {
            return Err(HttpError::HeaderTooLarge);
        }

        let n = stream.read(&mut temp).await?;
        if n == 0 {
            return Err(HttpError::MalformedRequest(
                "unexpected EOF reading request".into(),
            ));
        }

        head_buf.push(temp[0]);

        // Check for end of headers
        if head_buf.len() >= 4 {
            let len = head_buf.len();
            if &head_buf[len - 4..] == b"\r\n\r\n" {
                break;
            }
            if head_buf.len() >= 2 && &head_buf[len - 2..] == b"\r\n" {
                // The first CRLF terminates the request line and is not a
                // header. The final empty line is handled by the terminator
                // check above, so only actual header lines are counted.
                if saw_request_line {
                    header_count += 1;
                } else {
                    saw_request_line = true;
                }
                if header_count > MAX_HEADER_LINES {
                    return Err(HttpError::TooManyHeaders);
                }
            }
        }
    }

    let head_str = String::from_utf8_lossy(&head_buf);
    let mut lines = head_str.split("\r\n");

    // Parse request line
    let request_line = lines
        .next()
        .ok_or_else(|| HttpError::MalformedRequest("empty request".into()))?;

    let parts: Vec<&str> = request_line.split_whitespace().collect();
    if parts.len() != 3 {
        return Err(HttpError::MalformedRequest(format!(
            "expected 3 parts in request line, got {}",
            parts.len()
        )));
    }

    let method = parts[0].to_string();
    let raw_target = parts[1].to_string();
    let version = parts[2].to_string();
    if version != "HTTP/1.0" && version != "HTTP/1.1" {
        return Err(HttpError::MalformedRequest(format!(
            "unsupported HTTP version: {version}"
        )));
    }

    // Parse absolute-form target: http://host:port/path
    let (target, path) = parse_absolute_uri(&raw_target)?;

    // Parse headers
    let mut headers = Vec::new();

    for line in lines {
        if line.is_empty() {
            break;
        }
        if let Some((name, value)) = parse_header_line(line) {
            // Skip Proxy-Authorization header (don't forward it)
            if name.eq_ignore_ascii_case("Proxy-Authorization") {
                continue;
            }

            headers.push((name, value));
        }
    }

    // Determine body framing from headers
    let body_kind = determine_request_body_kind(&headers)?;
    let (has_body, content_length, is_chunked) = match body_kind {
        RequestBodyKind::None => (false, None, false),
        RequestBodyKind::ContentLength(len) => (len > 0, Some(len), false),
        RequestBodyKind::Chunked => (true, None, true),
    };

    // Determine Connection: close
    let connection_close = headers.iter().any(|(n, v)| {
        n.eq_ignore_ascii_case("Connection")
            && v.split(',').any(|t| t.trim().eq_ignore_ascii_case("close"))
    });

    Ok(ForwardRequest {
        method,
        path,
        version,
        headers,
        target,
        has_body,
        content_length,
        is_chunked,
        connection_close,
    })
}

/// Parse an absolute-form URI into target and path.
///
/// Supports: http://host:port/path, http://host/path
fn parse_absolute_uri(uri: &str) -> Result<(TargetAddr, String), HttpError> {
    // Remove scheme and determine default port
    let (rest, default_port) = if let Some(stripped) = uri.strip_prefix("http://") {
        (stripped, 80)
    } else if let Some(stripped) = uri.strip_prefix("https://") {
        // For HTTPS, we'd need TLS, but for now treat as HTTP
        (stripped, 443)
    } else {
        return Err(HttpError::MalformedRequest(format!(
            "absolute URI required, got: {}",
            uri
        )));
    };

    // Find path separator
    let path_start = rest.find('/').unwrap_or(rest.len());
    let authority = &rest[..path_start];
    let path = if path_start < rest.len() {
        &rest[path_start..]
    } else {
        "/"
    };

    // Parse authority with default port
    let target = parse_authority_with_default(authority, default_port)?;

    Ok((target, path.to_string()))
}

/// Parse an authority (host:port) into a TargetAddr with a default port.
fn parse_authority_with_default(
    authority: &str,
    default_port: u16,
) -> Result<TargetAddr, HttpError> {
    // Handle IPv6 bracketed addresses
    if authority.starts_with('[') {
        let bracket_end = authority.find(']').ok_or_else(|| {
            HttpError::TargetParseError("unclosed bracket in IPv6 address".into())
        })?;

        let ip_str = &authority[1..bracket_end];
        let ip: std::net::IpAddr = ip_str
            .parse()
            .map_err(|e| HttpError::TargetParseError(format!("invalid IPv6 address: {}", e)))?;

        // Check for port after bracket
        let port = if authority
            .as_bytes()
            .get(bracket_end + 1)
            .is_some_and(|&b| b == b':')
        {
            let port_str = authority.get(bracket_end + 2..).ok_or_else(|| {
                HttpError::TargetParseError("missing port after IPv6 address".into())
            })?;
            port_str
                .parse()
                .map_err(|e| HttpError::TargetParseError(format!("invalid port: {}", e)))?
        } else {
            default_port
        };

        return Ok(TargetAddr {
            host: TargetHost::Ip(ip),
            port,
        });
    }

    // Find the last ':' to split host and port
    let colon_pos = authority.rfind(':');

    let (host_str, port) = if let Some(colon_pos) = colon_pos {
        let host_str = &authority[..colon_pos];
        let port_str = &authority[colon_pos + 1..];
        let port: u16 = port_str
            .parse()
            .map_err(|e| HttpError::TargetParseError(format!("invalid port: {}", e)))?;
        (host_str, port)
    } else {
        (authority, default_port)
    };

    // Try to parse as IP first
    if let Ok(ip) = host_str.parse::<std::net::IpAddr>() {
        return Ok(TargetAddr {
            host: TargetHost::Ip(ip),
            port,
        });
    }

    // Otherwise treat as domain
    if host_str.is_empty() {
        return Err(HttpError::TargetParseError("empty host".into()));
    }

    Ok(TargetAddr {
        host: TargetHost::Domain(host_str.to_string()),
        port,
    })
}

/// Parse a header line into (name, value).
///
/// Rejects header names or values containing control characters (NUL, CR, LF)
/// per RFC 7230 §3.2.4.
fn parse_header_line(line: &str) -> Option<(String, String)> {
    let colon_pos = line.find(':')?;
    let name = line[..colon_pos].trim().to_string();
    let value = line[colon_pos + 1..].trim().to_string();

    if name.is_empty() {
        return None;
    }
    if name.bytes().any(|b| b == b'\0' || b == b'\r' || b == b'\n') {
        return None;
    }
    if value
        .bytes()
        .any(|b| b == b'\0' || b == b'\r' || b == b'\n')
    {
        return None;
    }

    Some((name, value))
}

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

    #[test]
    fn test_parse_absolute_uri() {
        let (target, path) = parse_absolute_uri("http://example.com:8080/path").unwrap();
        assert_eq!(
            target,
            TargetAddr {
                host: TargetHost::Domain("example.com".to_string()),
                port: 8080,
            }
        );
        assert_eq!(path, "/path");
    }

    #[test]
    fn test_parse_absolute_uri_no_path() {
        let (target, path) = parse_absolute_uri("http://example.com:80").unwrap();
        assert_eq!(
            target,
            TargetAddr {
                host: TargetHost::Domain("example.com".to_string()),
                port: 80,
            }
        );
        assert_eq!(path, "/");
    }

    #[test]
    fn test_parse_absolute_uri_ipv4() {
        let (target, path) = parse_absolute_uri("http://192.168.1.1:3000/api").unwrap();
        assert_eq!(
            target,
            TargetAddr {
                host: TargetHost::Ip("192.168.1.1".parse().unwrap()),
                port: 3000,
            }
        );
        assert_eq!(path, "/api");
    }

    #[test]
    fn test_parse_absolute_uri_no_scheme() {
        assert!(parse_absolute_uri("example.com/path").is_err());
    }

    #[test]
    fn test_parse_header_line() {
        let (name, value) = parse_header_line("Content-Type: text/html").unwrap();
        assert_eq!(name, "Content-Type");
        assert_eq!(value, "text/html");
    }

    #[test]
    fn test_parse_header_line_no_colon() {
        assert!(parse_header_line("NoColon").is_none());
    }

    #[test]
    fn test_filter_hop_by_hop_connection_nominated() {
        let headers = vec![
            ("Connection".into(), "X-Custom, Keep-Alive".into()),
            ("X-Custom".into(), "value".into()),
            ("Keep-Alive".into(), "timeout=5".into()),
            ("Content-Type".into(), "text/html".into()),
        ];
        let filtered = filter_hop_by_hop(&headers);
        // X-Custom and Keep-Alive should be removed (nominated by Connection),
        // plus connection itself is always removed.
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].0, "Content-Type");
    }

    #[test]
    fn test_filter_hop_by_hop_preserves_transfer_encoding_chunked() {
        let headers = vec![
            ("Transfer-Encoding".into(), "chunked".into()),
            ("Content-Type".into(), "application/json".into()),
        ];
        let filtered = filter_hop_by_hop(&headers);
        assert_eq!(filtered.len(), 2);
        assert!(filtered.iter().any(|(n, _)| n == "Transfer-Encoding"));
    }

    #[test]
    fn test_filter_hop_by_hop_removes_transfer_encoding_non_chunked() {
        let headers = vec![
            ("Transfer-Encoding".into(), "gzip".into()),
            ("Content-Type".into(), "text/html".into()),
        ];
        let filtered = filter_hop_by_hop(&headers);
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].0, "Content-Type");
    }

    #[test]
    fn test_filter_connection_tokens_empty() {
        let headers = vec![("Content-Type".into(), "text/html".into())];
        let tokens = connection_tokens(&headers);
        assert!(tokens.is_empty());
    }

    #[test]
    fn test_filter_connection_tokens_multiple() {
        let headers = vec![("Connection".into(), "close, Upgrade".into())];
        let tokens = connection_tokens(&headers);
        assert!(tokens.contains("close"));
        assert!(tokens.contains("upgrade"));
    }

    #[test]
    fn test_determine_body_none() {
        let headers = vec![("Host".into(), "example.com".into())];
        assert_eq!(
            determine_request_body_kind(&headers).unwrap(),
            RequestBodyKind::None
        );
    }

    #[test]
    fn test_determine_body_content_length() {
        let headers = vec![("Content-Length".into(), "42".into())];
        assert_eq!(
            determine_request_body_kind(&headers).unwrap(),
            RequestBodyKind::ContentLength(42)
        );
    }

    #[test]
    fn test_determine_body_duplicate_equal_cl() {
        let headers = vec![
            ("Content-Length".into(), "42".into()),
            ("Content-Length".into(), "42".into()),
        ];
        assert_eq!(
            determine_request_body_kind(&headers).unwrap(),
            RequestBodyKind::ContentLength(42)
        );
    }

    #[test]
    fn test_determine_body_conflicting_cl() {
        let headers = vec![
            ("Content-Length".into(), "42".into()),
            ("Content-Length".into(), "100".into()),
        ];
        assert!(matches!(
            determine_request_body_kind(&headers),
            Err(HttpError::ConflictingContentLength)
        ));
    }

    #[test]
    fn test_determine_body_invalid_cl() {
        let headers = vec![("Content-Length".into(), "abc".into())];
        assert!(matches!(
            determine_request_body_kind(&headers),
            Err(HttpError::InvalidContentLength)
        ));
    }

    #[test]
    fn test_determine_body_chunked() {
        let headers = vec![("Transfer-Encoding".into(), "chunked".into())];
        assert_eq!(
            determine_request_body_kind(&headers).unwrap(),
            RequestBodyKind::Chunked
        );
    }

    #[test]
    fn test_determine_body_te_plus_cl() {
        let headers = vec![
            ("Transfer-Encoding".into(), "chunked".into()),
            ("Content-Length".into(), "42".into()),
        ];
        assert!(matches!(
            determine_request_body_kind(&headers),
            Err(HttpError::TransferEncodingWithContentLength)
        ));
    }

    #[test]
    fn test_determine_body_unsupported_te() {
        let headers = vec![("Transfer-Encoding".into(), "gzip".into())];
        assert!(matches!(
            determine_request_body_kind(&headers),
            Err(HttpError::UnsupportedTransferEncoding(_))
        ));
    }

    #[test]
    fn test_determine_body_chunked_not_final() {
        let headers = vec![("Transfer-Encoding".into(), "chunked, gzip".into())];
        assert!(matches!(
            determine_request_body_kind(&headers),
            Err(HttpError::ChunkedNotFinal)
        ));
    }

    #[test]
    fn test_determine_body_mixed_header_casing() {
        let headers = vec![
            ("content-length".into(), "42".into()),
            ("CONTENT-LENGTH".into(), "42".into()),
        ];
        assert_eq!(
            determine_request_body_kind(&headers).unwrap(),
            RequestBodyKind::ContentLength(42)
        );
    }

    // ===== Body copy tests =====

    #[tokio::test]
    async fn test_copy_chunked_body_simple() {
        let input = b"5\r\nhello\r\n0\r\n\r\n";
        let mut reader = &input[..];
        let mut writer = Vec::new();
        let limits = BodyCopyLimits::default();

        let report = copy_request_body(&mut reader, &mut writer, RequestBodyKind::Chunked, &limits)
            .await
            .unwrap();
        assert_eq!(report.decoded_bytes, 5);
        assert_eq!(writer, input);
    }

    #[tokio::test]
    async fn test_copy_chunked_body_multiple_chunks() {
        let input = b"5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n";
        let mut reader = &input[..];
        let mut writer = Vec::new();
        let limits = BodyCopyLimits::default();

        let report = copy_request_body(&mut reader, &mut writer, RequestBodyKind::Chunked, &limits)
            .await
            .unwrap();
        assert_eq!(report.decoded_bytes, 11);
        assert_eq!(writer, input);
    }

    #[tokio::test]
    async fn test_copy_chunked_body_uppercase_hex() {
        let input = b"5\r\nhello\r\n0\r\n\r\n";
        let mut reader = &input[..];
        let mut writer = Vec::new();
        let limits = BodyCopyLimits::default();

        let report = copy_request_body(&mut reader, &mut writer, RequestBodyKind::Chunked, &limits)
            .await
            .unwrap();
        assert_eq!(report.decoded_bytes, 5);
    }

    #[tokio::test]
    async fn test_copy_chunked_body_with_extension() {
        let input = b"5;ext=value\r\nhello\r\n0\r\n\r\n";
        let mut reader = &input[..];
        let mut writer = Vec::new();
        let limits = BodyCopyLimits::default();

        let report = copy_request_body(&mut reader, &mut writer, RequestBodyKind::Chunked, &limits)
            .await
            .unwrap();
        assert_eq!(report.decoded_bytes, 5);
    }

    #[tokio::test]
    async fn test_copy_chunked_body_with_trailer() {
        let input = b"5\r\nhello\r\n0\r\nTrailer: value\r\n\r\n";
        let mut reader = &input[..];
        let mut writer = Vec::new();
        let limits = BodyCopyLimits::default();

        let report = copy_request_body(&mut reader, &mut writer, RequestBodyKind::Chunked, &limits)
            .await
            .unwrap();
        assert_eq!(report.decoded_bytes, 5);
    }

    #[tokio::test]
    async fn test_copy_chunked_body_malformed_hex() {
        let input = b"ZZ\r\nhello\r\n0\r\n\r\n";
        let mut reader = &input[..];
        let mut writer = Vec::new();
        let limits = BodyCopyLimits::default();

        let result =
            copy_request_body(&mut reader, &mut writer, RequestBodyKind::Chunked, &limits).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_copy_chunked_body_empty_size() {
        let input = b"\r\nhello\r\n0\r\n\r\n";
        let mut reader = &input[..];
        let mut writer = Vec::new();
        let limits = BodyCopyLimits::default();

        let result =
            copy_request_body(&mut reader, &mut writer, RequestBodyKind::Chunked, &limits).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_copy_chunked_body_missing_crlf() {
        let input = b"5\r\nhelloX\r\n0\r\n\r\n";
        let mut reader = &input[..];
        let mut writer = Vec::new();
        let limits = BodyCopyLimits::default();

        let result =
            copy_request_body(&mut reader, &mut writer, RequestBodyKind::Chunked, &limits).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_copy_chunked_body_oversized_chunk() {
        let input = b"FFFFFFFFFFFFFFFF\r\nhello\r\n0\r\n\r\n";
        let mut reader = &input[..];
        let mut writer = Vec::new();
        let limits = BodyCopyLimits {
            max_chunk_size: 1024,
            ..Default::default()
        };

        let result =
            copy_request_body(&mut reader, &mut writer, RequestBodyKind::Chunked, &limits).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_copy_content_length_body() {
        let input = b"hello world";
        let mut reader = &input[..];
        let mut writer = Vec::new();
        let limits = BodyCopyLimits::default();

        let report = copy_request_body(
            &mut reader,
            &mut writer,
            RequestBodyKind::ContentLength(11),
            &limits,
        )
        .await
        .unwrap();
        assert_eq!(report.wire_bytes, 11);
        assert_eq!(report.decoded_bytes, 11);
        assert_eq!(writer, input);
    }

    #[tokio::test]
    async fn test_copy_none_body() {
        let mut reader = &b""[..];
        let mut writer = Vec::new();
        let limits = BodyCopyLimits::default();

        let report = copy_request_body(&mut reader, &mut writer, RequestBodyKind::None, &limits)
            .await
            .unwrap();
        assert_eq!(report.wire_bytes, 0);
        assert_eq!(report.decoded_bytes, 0);
    }

    #[tokio::test]
    async fn test_copy_content_length_body_premature_eof() {
        let input = b"hel"; // only 3 bytes but Content-Length says 11
        let mut reader = &input[..];
        let mut writer = Vec::new();
        let limits = BodyCopyLimits::default();

        let result = copy_request_body(
            &mut reader,
            &mut writer,
            RequestBodyKind::ContentLength(11),
            &limits,
        )
        .await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        let msg = format!("{}", err);
        assert!(
            msg.contains("unexpected EOF"),
            "error should mention EOF: {}",
            msg
        );
    }

    #[tokio::test]
    async fn test_copy_content_length_body_zero_length() {
        let input = b"";
        let mut reader = &input[..];
        let mut writer = Vec::new();
        let limits = BodyCopyLimits::default();

        let report = copy_request_body(
            &mut reader,
            &mut writer,
            RequestBodyKind::ContentLength(0),
            &limits,
        )
        .await
        .unwrap();
        assert_eq!(report.wire_bytes, 0);
        assert_eq!(report.decoded_bytes, 0);
    }

    #[tokio::test]
    async fn test_copy_chunked_body_decoded_limit_exceeded() {
        // A single valid chunk of 100 bytes but max_decoded_body is 10
        let chunk_data = "x".repeat(100);
        let input = format!("64\r\n{}\r\n0\r\n\r\n", chunk_data);
        let mut reader = input.as_bytes();
        let mut writer = Vec::new();
        let limits = BodyCopyLimits {
            max_decoded_body: 10,
            ..Default::default()
        };

        let result =
            copy_request_body(&mut reader, &mut writer, RequestBodyKind::Chunked, &limits).await;
        assert!(result.is_err());
        let msg = format!("{}", result.unwrap_err());
        assert!(
            msg.contains("decoded body too large"),
            "error should mention decoded body limit: {}",
            msg
        );
    }

    // ===== Phase 2: HTTP framing and connection-state invariants =====

    #[test]
    fn test_te_plus_cl_rejected_not_forwarded() {
        let headers = vec![
            ("Transfer-Encoding".into(), "chunked".into()),
            ("Content-Length".into(), "0".into()),
        ];
        let result = determine_request_body_kind(&headers);
        assert!(
            matches!(result, Err(HttpError::TransferEncodingWithContentLength)),
            "TE+CL must be rejected to prevent ambiguous framing: {:?}",
            result
        );
    }

    #[test]
    fn test_conflicting_cl_values_rejected() {
        let headers = vec![
            ("Content-Length".into(), "10".into()),
            ("Content-Length".into(), "20".into()),
        ];
        let result = determine_request_body_kind(&headers);
        assert!(
            matches!(result, Err(HttpError::ConflictingContentLength)),
            "conflicting CL values must be rejected: {:?}",
            result
        );
    }

    #[test]
    fn test_equal_duplicate_cl_deterministic() {
        let headers = vec![
            ("Content-Length".into(), "42".into()),
            ("Content-Length".into(), "42".into()),
        ];
        let kind = determine_request_body_kind(&headers).unwrap();
        assert_eq!(kind, RequestBodyKind::ContentLength(42));
    }

    #[test]
    fn test_connection_nominated_headers_removed() {
        let headers = vec![
            ("Connection".into(), "X-Foo, X-Bar".into()),
            ("X-Foo".into(), "a".into()),
            ("X-Bar".into(), "b".into()),
            ("Content-Type".into(), "text/html".into()),
        ];
        let filtered = filter_hop_by_hop(&headers);
        let names: Vec<_> = filtered.iter().map(|(n, _)| n.as_str()).collect();
        assert_eq!(names, vec!["Content-Type"]);
    }

    #[test]
    fn test_ipv6_literal_authority_roundtrip() {
        let (target, path) = parse_absolute_uri("http://[::1]:8080/api").unwrap();
        assert_eq!(
            target,
            TargetAddr {
                host: TargetHost::Ip("::1".parse().unwrap()),
                port: 8080,
            }
        );
        assert_eq!(path, "/api");
    }

    #[test]
    fn test_ipv6_literal_no_port() {
        let (target, _path) = parse_absolute_uri("http://[::1]/path").unwrap();
        assert_eq!(target.port, 80);
        assert_eq!(target.host, TargetHost::Ip("::1".parse().unwrap()));
    }

    #[test]
    fn test_chunked_not_final_rejected() {
        // When chunked is not the final coding and a non-chunked coding is present,
        // the unsupported encoding is rejected first (since only chunked is supported).
        let headers = vec![("Transfer-Encoding".into(), "gzip, chunked".into())];
        let result = determine_request_body_kind(&headers);
        assert!(
            matches!(
                result,
                Err(HttpError::UnsupportedTransferEncoding(_)) | Err(HttpError::ChunkedNotFinal)
            ),
            "chunked not final with unsupported coding must be rejected: {:?}",
            result
        );
    }

    #[test]
    fn test_unsupported_transfer_encoding_rejected() {
        let headers = vec![("Transfer-Encoding".into(), "deflate".into())];
        let result = determine_request_body_kind(&headers);
        assert!(
            matches!(result, Err(HttpError::UnsupportedTransferEncoding(_))),
            "unsupported TE must be rejected: {:?}",
            result
        );
    }

    #[tokio::test]
    async fn test_upstream_connection_close_detected() {
        let response = b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\nConnection: close\r\n\r\nhello";
        // Upstream: server writes response into duplex, forward_response reads from the other end
        let (upstream_read, mut upstream_write) = tokio::io::duplex(4096);
        tokio::spawn(async move {
            upstream_write.write_all(response).await.unwrap();
            upstream_write.shutdown().await.ok();
        });
        // Client: forward_response writes to client_write, we read from client_read
        let (mut client_read, client_write) = tokio::io::duplex(4096);

        let mut upstream: BoxStream = Box::new(upstream_read);
        let mut client: BoxStream = Box::new(client_write);
        let result = forward_response(&mut upstream, &mut client).await;
        assert!(result.is_ok());
        let fwd = result.unwrap();
        assert!(
            !fwd.upstream_alive,
            "Connection: close should make upstream not alive"
        );
        assert!(
            fwd.client_should_close,
            "client should close when upstream says close"
        );
        // Verify the client received the forwarded response
        let mut buf = Vec::new();
        let _ = tokio::time::timeout(
            std::time::Duration::from_secs(1),
            client_read.read_to_end(&mut buf),
        )
        .await;
        let resp = String::from_utf8_lossy(&buf);
        assert!(
            resp.contains("200 OK"),
            "client should receive response: {resp}"
        );
        assert!(resp.contains("hello"), "client should receive body: {resp}");
    }

    #[tokio::test]
    async fn test_upstream_http11_keepalive_default() {
        let response = b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello";
        let (upstream_read, mut upstream_write) = tokio::io::duplex(4096);
        tokio::spawn(async move {
            upstream_write.write_all(response).await.unwrap();
            tokio::time::sleep(std::time::Duration::from_millis(200)).await;
        });
        let (mut client_read, client_write) = tokio::io::duplex(4096);

        let mut upstream: BoxStream = Box::new(upstream_read);
        let mut client: BoxStream = Box::new(client_write);
        let result = forward_response(&mut upstream, &mut client).await;
        assert!(result.is_ok());
        let fwd = result.unwrap();
        assert!(
            fwd.upstream_alive,
            "HTTP/1.1 without Connection: close should be alive"
        );
        assert!(!fwd.client_should_close);
        let mut buf = Vec::new();
        let _ = tokio::time::timeout(
            std::time::Duration::from_secs(1),
            client_read.read_to_end(&mut buf),
        )
        .await;
        let resp = String::from_utf8_lossy(&buf);
        assert!(
            resp.contains("200 OK"),
            "client should receive response: {resp}"
        );
    }

    #[test]
    fn test_filter_hop_by_hop_removes_upgrade() {
        let headers = vec![
            ("Upgrade".into(), "websocket".into()),
            ("Content-Type".into(), "text/html".into()),
        ];
        let filtered = filter_hop_by_hop(&headers);
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].0, "Content-Type");
    }

    #[test]
    fn test_filter_hop_by_hop_removes_proxy_connection() {
        let headers = vec![
            ("Proxy-Connection".into(), "keep-alive".into()),
            ("Content-Type".into(), "text/html".into()),
        ];
        let filtered = filter_hop_by_hop(&headers);
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].0, "Content-Type");
    }

    #[tokio::test]
    async fn test_request_body_kind_none_has_no_body() {
        let headers = vec![("Host".into(), "example.com".into())];
        let kind = determine_request_body_kind(&headers).unwrap();
        assert_eq!(kind, RequestBodyKind::None);
        assert!(!matches!(kind, RequestBodyKind::ContentLength(0)));
    }

    #[test]
    fn test_forward_request_body_kind_dispatches_correctly() {
        let req_none = ForwardRequest {
            method: "GET".into(),
            path: "/".into(),
            version: "HTTP/1.1".into(),
            headers: vec![],
            target: TargetAddr {
                host: TargetHost::Domain("example.com".into()),
                port: 80,
            },
            has_body: false,
            content_length: None,
            is_chunked: false,
            connection_close: false,
        };
        assert_eq!(req_none.body_kind(), RequestBodyKind::None);

        let req_cl = ForwardRequest {
            content_length: Some(100),
            has_body: true,
            ..req_none.clone()
        };
        assert_eq!(req_cl.body_kind(), RequestBodyKind::ContentLength(100));

        let req_chunked = ForwardRequest {
            is_chunked: true,
            has_body: true,
            ..req_none.clone()
        };
        assert_eq!(req_chunked.body_kind(), RequestBodyKind::Chunked);
    }

    // ===== Phase 2 gap coverage: invariants 6–9 =====

    #[tokio::test]
    async fn test_copy_request_body_premature_eof() {
        let input = b"short";
        let mut reader = &input[..];
        let mut writer = Vec::new();
        let limits = BodyCopyLimits::default();

        let result = copy_request_body(
            &mut reader,
            &mut writer,
            RequestBodyKind::ContentLength(100),
            &limits,
        )
        .await;
        assert!(
            result.is_err(),
            "Content-Length body with premature EOF must fail"
        );
        let msg = format!("{}", result.unwrap_err());
        assert!(
            msg.contains("unexpected EOF"),
            "error should mention unexpected EOF: {msg}"
        );
    }

    #[tokio::test]
    async fn test_forward_request_stream_after_failure() {
        use tokio::io::AsyncWriteExt;

        let (client_read, mut client_write) = tokio::io::duplex(4096);
        let mut stream: BoxStream = Box::new(client_read);

        let bad_request = b"INVALID\r\n\r\n";
        client_write.write_all(bad_request).await.unwrap();

        let result = forward_request_stream(&mut stream).await;
        assert!(result.is_err(), "malformed request must fail");

        let good_request = b"GET http://example.com/ HTTP/1.1\r\nHost: example.com\r\n\r\n";
        client_write.write_all(good_request).await.unwrap();

        let result2 = forward_request_stream(&mut stream).await;
        assert!(
            result2.is_ok(),
            "valid request after failure must succeed: {:?}",
            result2.err()
        );
        let req = result2.unwrap();
        assert_eq!(req.method, "GET");
        assert_eq!(req.path, "/");
    }

    #[tokio::test]
    async fn test_forward_request_rejects_unsupported_http_version() {
        let (client_read, mut client_write) = tokio::io::duplex(4096);
        let mut stream: BoxStream = Box::new(client_read);
        client_write
            .write_all(b"GET http://example.com/ HTTP/9.9\r\n\r\n")
            .await
            .unwrap();

        let error = forward_request_stream(&mut stream).await.unwrap_err();
        assert!(
            matches!(error, HttpError::MalformedRequest(message) if message.contains("HTTP/9.9"))
        );
    }

    #[tokio::test]
    async fn test_response_header_limit_allows_maximum_header_count() {
        let (client_read, mut client_write) = tokio::io::duplex(32 * 1024);
        let mut stream: BoxStream = Box::new(client_read);
        let mut response = String::from("HTTP/1.1 200 OK\r\n");
        for index in 0..MAX_HEADER_LINES {
            response.push_str(&format!("X-Test-{index}: value\r\n"));
        }
        response.push_str("\r\n");
        client_write.write_all(response.as_bytes()).await.unwrap();

        let parsed = read_response_head(&mut stream).await.unwrap();
        assert_eq!(parsed.headers.len(), MAX_HEADER_LINES);
    }

    #[test]
    fn test_build_origin_request_strips_upgrade() {
        let req = ForwardRequest {
            method: "GET".into(),
            path: "/".into(),
            version: "HTTP/1.1".into(),
            headers: vec![
                ("Host".into(), "example.com".into()),
                ("Upgrade".into(), "websocket".into()),
                ("Connection".into(), "Upgrade".into()),
            ],
            target: TargetAddr {
                host: TargetHost::Domain("example.com".into()),
                port: 80,
            },
            has_body: false,
            content_length: None,
            is_chunked: false,
            connection_close: false,
        };
        let origin = build_origin_request(&req);
        assert!(
            !origin.to_lowercase().contains("upgrade"),
            "Upgrade header must be stripped from forwarded request: {origin}"
        );
        assert!(
            !origin.to_lowercase().contains("connection: upgrade"),
            "Connection: Upgrade must be stripped: {origin}"
        );
        assert!(
            origin.contains("Connection: close"),
            "proxy must add Connection: close: {origin}"
        );
    }

    #[test]
    fn test_expectation_detection_is_case_insensitive_and_comma_aware() {
        assert!(has_unsupported_expectation(&[(
            "eXpEcT".into(),
            "foo, 100-continue".into()
        ),]));
        assert!(!has_unsupported_expectation(&[(
            "Expect".into(),
            "  ,  ".into()
        )]));
    }

    #[tokio::test]
    async fn test_forward_response_forwards_informational_responses_before_final() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};

        let response = b"HTTP/1.1 103 Early Hints\r\nLink: </style.css>\r\n\r\nHTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello";
        let (upstream_read, mut upstream_write) = tokio::io::duplex(4096);
        tokio::spawn(async move {
            upstream_write.write_all(response).await.unwrap();
        });
        let (mut client_read, client_write) = tokio::io::duplex(4096);

        let mut upstream: BoxStream = Box::new(upstream_read);
        let mut client: BoxStream = Box::new(client_write);

        let result = forward_response(&mut upstream, &mut client).await.unwrap();
        assert_eq!(result.status, 200);
        client.shutdown().await.unwrap();

        let mut buf = Vec::new();
        client_read.read_to_end(&mut buf).await.unwrap();
        let resp = String::from_utf8_lossy(&buf);
        assert!(
            resp.starts_with("HTTP/1.1 103 Early"),
            "unexpected forwarded response: {resp:?}"
        );
        assert!(resp.contains("HTTP/1.1 100 Continue"));
        assert!(resp.contains("HTTP/1.1 200 OK"));
        assert!(resp.ends_with("hello"));
        assert!(resp.find("103").unwrap() < resp.find("100").unwrap());
        assert!(resp.find("100").unwrap() < resp.find("200").unwrap());
    }

    #[tokio::test]
    async fn test_forward_response_rejects_switching_protocols() {
        use tokio::io::AsyncWriteExt;

        let (upstream_read, mut upstream_write) = tokio::io::duplex(1024);
        tokio::spawn(async move {
            upstream_write
                .write_all(b"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\n\r\n")
                .await
                .unwrap();
        });
        let (_client_read, client_write) = tokio::io::duplex(1024);
        let mut upstream: BoxStream = Box::new(upstream_read);
        let mut client: BoxStream = Box::new(client_write);

        assert!(matches!(
            forward_response(&mut upstream, &mut client).await,
            Err(HttpError::UpgradeUnsupported)
        ));
    }

    #[tokio::test]
    async fn test_forward_response_rejects_invalid_content_length() {
        use tokio::io::AsyncWriteExt;

        let (upstream_read, mut upstream_write) = tokio::io::duplex(1024);
        tokio::spawn(async move {
            upstream_write
                .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: invalid\r\n\r\n")
                .await
                .unwrap();
        });
        let (_client_read, client_write) = tokio::io::duplex(1024);
        let mut upstream: BoxStream = Box::new(upstream_read);
        let mut client: BoxStream = Box::new(client_write);

        assert!(matches!(
            forward_response(&mut upstream, &mut client).await,
            Err(HttpError::InvalidContentLength)
        ));
    }

    #[tokio::test]
    async fn test_forward_response_accepts_equal_duplicate_content_length() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};

        let (upstream_read, mut upstream_write) = tokio::io::duplex(1024);
        tokio::spawn(async move {
            upstream_write
                .write_all(
                    b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\nContent-Length: 5\r\n\r\nhello",
                )
                .await
                .unwrap();
        });
        let (mut client_read, client_write) = tokio::io::duplex(1024);
        let mut upstream: BoxStream = Box::new(upstream_read);
        let mut client: BoxStream = Box::new(client_write);

        let result = forward_response(&mut upstream, &mut client).await.unwrap();
        assert_eq!(result.status, 200);
        client.shutdown().await.unwrap();
        let mut buf = Vec::new();
        client_read.read_to_end(&mut buf).await.unwrap();
        assert!(String::from_utf8_lossy(&buf).ends_with("hello"));
    }

    #[tokio::test]
    async fn test_forward_response_rejects_conflicting_duplicate_content_length() {
        use tokio::io::AsyncWriteExt;

        let (upstream_read, mut upstream_write) = tokio::io::duplex(1024);
        tokio::spawn(async move {
            upstream_write
                .write_all(
                    b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\nContent-Length: 6\r\n\r\nhello",
                )
                .await
                .unwrap();
        });
        let (_client_read, client_write) = tokio::io::duplex(1024);
        let mut upstream: BoxStream = Box::new(upstream_read);
        let mut client: BoxStream = Box::new(client_write);

        assert!(matches!(
            forward_response(&mut upstream, &mut client).await,
            Err(HttpError::ConflictingContentLength)
        ));
    }

    #[tokio::test]
    async fn test_forward_response_rejects_invalid_chunk_size() {
        use tokio::io::AsyncWriteExt;

        let (upstream_read, mut upstream_write) = tokio::io::duplex(1024);
        tokio::spawn(async move {
            upstream_write
                .write_all(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\nnope\r\n")
                .await
                .unwrap();
        });
        let (_client_read, client_write) = tokio::io::duplex(1024);
        let mut upstream: BoxStream = Box::new(upstream_read);
        let mut client: BoxStream = Box::new(client_write);

        assert!(matches!(
            forward_response(&mut upstream, &mut client).await,
            Err(HttpError::MalformedResponse(message)) if message.contains("invalid chunk size")
        ));
    }

    #[tokio::test]
    async fn test_forward_response_bounds_informational_responses() {
        use tokio::io::AsyncWriteExt;

        let response = b"HTTP/1.1 103 Early Hints\r\n\r\n";
        let (upstream_read, mut upstream_write) = tokio::io::duplex(4096);
        tokio::spawn(async move {
            for _ in 0..=MAX_INFORMATIONAL_RESPONSES {
                upstream_write.write_all(response).await.unwrap();
            }
        });
        let (_client_read, client_write) = tokio::io::duplex(4096);
        let mut upstream: BoxStream = Box::new(upstream_read);
        let mut client: BoxStream = Box::new(client_write);

        assert!(matches!(
            forward_response(&mut upstream, &mut client).await,
            Err(HttpError::TooManyInformationalResponses)
        ));
    }
}