asupersync 0.3.1

Spec-first, cancel-correct, capability-secure async runtime for Rust.
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
//! WebSocket handshake implementation (RFC 6455 Section 4).
//!
//! Implements the HTTP upgrade handshake for both client and server roles.
//!
//! # Client Handshake
//!
//! ```http
//! GET /chat HTTP/1.1
//! Host: server.example.com
//! Upgrade: websocket
//! Connection: Upgrade
//! Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
//! Sec-WebSocket-Version: 13
//! ```
//!
//! # Server Response
//!
//! ```http
//! HTTP/1.1 101 Switching Protocols
//! Upgrade: websocket
//! Connection: Upgrade
//! Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
//! ```

use crate::util::EntropySource;
use base64::Engine;
use sha1::{Digest, Sha1};
use std::collections::BTreeMap;
use std::fmt;

/// RFC 6455 GUID for Sec-WebSocket-Accept calculation.
const WS_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

/// Compute the Sec-WebSocket-Accept value from a client key.
///
/// Per RFC 6455 Section 4.2.2:
/// 1. Concatenate the client's Sec-WebSocket-Key with the GUID
/// 2. Take the SHA-1 hash
/// 3. Base64 encode the result
///
/// # Example
///
/// ```
/// use asupersync::net::websocket::compute_accept_key;
///
/// let client_key = "dGhlIHNhbXBsZSBub25jZQ==";
/// let accept = compute_accept_key(client_key);
/// assert_eq!(accept, "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=");
/// ```
#[must_use]
pub fn compute_accept_key(client_key: &str) -> String {
    let mut hasher = Sha1::new();
    hasher.update(client_key.as_bytes());
    hasher.update(WS_GUID.as_bytes());
    let hash = hasher.finalize();
    base64::engine::general_purpose::STANDARD.encode(hash)
}

/// Generate a random 16-byte key for the client handshake.
fn generate_client_key(entropy: &dyn EntropySource) -> String {
    let mut key = [0u8; 16];
    entropy.fill_bytes(&mut key);
    base64::engine::general_purpose::STANDARD.encode(key)
}

fn parse_extension_offers(header_value: &str) -> Vec<String> {
    header_value
        .split(',')
        .map(str::trim)
        .filter(|v| !v.is_empty())
        .map(ToOwned::to_owned)
        .collect()
}

fn extension_token(offer: &str) -> &str {
    offer.split(';').next().unwrap_or("").trim()
}

fn header_has_token(value: &str, token: &str) -> bool {
    value
        .split(',')
        .map(str::trim)
        .any(|part| part.eq_ignore_ascii_case(token))
}

fn split_http_header_block(data: &[u8]) -> Result<(&[u8], &[u8]), HandshakeError> {
    let crlf_pos = data
        .windows(4)
        .position(|w| w == b"\r\n\r\n")
        .map(|p| p + 4);
    let lf_pos = data.windows(2).position(|w| w == b"\n\n").map(|p| p + 2);

    let split_at = match (crlf_pos, lf_pos) {
        (Some(c), Some(l)) => Some(std::cmp::min(c, l)),
        (Some(c), None) => Some(c),
        (None, Some(l)) => Some(l),
        (None, None) => None,
    };

    split_at.map_or_else(
        || {
            Err(HandshakeError::InvalidRequest(
                "incomplete HTTP headers".into(),
            ))
        },
        |pos| Ok((&data[..pos], &data[pos..])),
    )
}

/// Parsed WebSocket URL.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WsUrl {
    /// Host name or IP address.
    pub host: String,
    /// Port number (default: 80 for ws, 443 for wss).
    pub port: u16,
    /// Request path (default: "/").
    pub path: String,
    /// Whether TLS is required (wss://).
    pub tls: bool,
}

impl WsUrl {
    /// Parse a WebSocket URL (ws:// or wss://).
    ///
    /// # Errors
    ///
    /// Returns `HandshakeError::InvalidUrl` if the URL is malformed.
    pub fn parse(url: &str) -> Result<Self, HandshakeError> {
        let (scheme, rest) = url
            .split_once("://")
            .ok_or_else(|| HandshakeError::InvalidUrl("missing scheme".into()))?;

        let tls = match scheme {
            "ws" => false,
            "wss" => true,
            _ => {
                return Err(HandshakeError::InvalidUrl(format!(
                    "unsupported scheme: {scheme}"
                )));
            }
        };

        let default_port = if tls { 443 } else { 80 };

        // Split host:port from path
        let (host_port, path) = rest
            .find('/')
            .map_or((rest, "/"), |idx| (&rest[..idx], &rest[idx..]));

        // Parse host and port
        let (host, port) = if host_port.starts_with('[') {
            host_port.find(']').map_or_else(
                || {
                    Err(HandshakeError::InvalidUrl(
                        "missing closing bracket for IPv6 address".into(),
                    ))
                },
                |bracket_end| {
                    let host = &host_port[1..bracket_end];
                    let port = if host_port.len() > bracket_end + 1
                        && host_port.as_bytes()[bracket_end + 1] == b':'
                    {
                        host_port[bracket_end + 2..]
                            .parse()
                            .map_err(|_| HandshakeError::InvalidUrl("invalid port".into()))?
                    } else {
                        default_port
                    };
                    Ok((host.to_string(), port))
                },
            )?
        } else if host_port.matches(':').count() > 1 {
            // Unbracketed IPv6 address - cannot safely have a port (ambiguous)
            (host_port.to_string(), default_port)
        } else if let Some(colon_idx) = host_port.rfind(':') {
            // host:port
            let host = &host_port[..colon_idx];
            let port = host_port[colon_idx + 1..]
                .parse()
                .map_err(|_| HandshakeError::InvalidUrl("invalid port".into()))?;
            (host.to_string(), port)
        } else {
            (host_port.to_string(), default_port)
        };

        if host.is_empty() {
            return Err(HandshakeError::InvalidUrl("empty host".into()));
        }

        Ok(Self {
            host,
            port,
            path: path.to_string(),
            tls,
        })
    }

    /// Returns the Host header value.
    #[must_use]
    pub fn host_header(&self) -> String {
        let default_port = if self.tls { 443 } else { 80 };
        let host_str = if self.host.contains(':') {
            format!("[{}]", self.host)
        } else {
            self.host.clone()
        };

        if self.port == default_port {
            host_str
        } else {
            format!("{}:{}", host_str, self.port)
        }
    }
}

/// WebSocket handshake errors.
#[derive(Debug)]
pub enum HandshakeError {
    /// Invalid URL format.
    InvalidUrl(String),
    /// Invalid HTTP request.
    InvalidRequest(String),
    /// Missing required header.
    MissingHeader(&'static str),
    /// Invalid Sec-WebSocket-Key.
    InvalidKey,
    /// Invalid Sec-WebSocket-Accept (response validation).
    InvalidAccept {
        /// Expected accept value.
        expected: String,
        /// Actual accept value.
        actual: String,
    },
    /// Unsupported WebSocket version.
    UnsupportedVersion(String),
    /// Protocol negotiation failed.
    ProtocolMismatch {
        /// Requested protocols.
        requested: Vec<String>,
        /// Offered protocol (if any).
        offered: Option<String>,
    },
    /// Extension negotiation failed.
    ExtensionMismatch {
        /// Requested extensions.
        requested: Vec<String>,
        /// Offered extensions.
        offered: Vec<String>,
    },
    /// Server rejected upgrade with HTTP status.
    Rejected {
        /// HTTP status code.
        status: u16,
        /// Status reason phrase.
        reason: String,
    },
    /// HTTP response not 101 Switching Protocols.
    NotSwitchingProtocols(u16),
    /// I/O error.
    Io(std::io::Error),
}

impl fmt::Display for HandshakeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidUrl(msg) => write!(f, "invalid URL: {msg}"),
            Self::InvalidRequest(msg) => write!(f, "invalid HTTP request: {msg}"),
            Self::MissingHeader(name) => write!(f, "missing required header: {name}"),
            Self::InvalidKey => write!(f, "invalid Sec-WebSocket-Key"),
            Self::InvalidAccept { expected, actual } => {
                write!(
                    f,
                    "invalid Sec-WebSocket-Accept: expected {expected}, got {actual}"
                )
            }
            Self::UnsupportedVersion(v) => write!(f, "unsupported WebSocket version: {v}"),
            Self::ProtocolMismatch { requested, offered } => {
                write!(
                    f,
                    "protocol mismatch: requested {requested:?}, offered {offered:?}"
                )
            }
            Self::ExtensionMismatch { requested, offered } => {
                write!(
                    f,
                    "extension mismatch: requested {requested:?}, offered {offered:?}"
                )
            }
            Self::Rejected { status, reason } => {
                write!(f, "server rejected upgrade: {status} {reason}")
            }
            Self::NotSwitchingProtocols(status) => {
                write!(f, "expected 101 Switching Protocols, got {status}")
            }
            Self::Io(e) => write!(f, "I/O error: {e}"),
        }
    }
}

impl std::error::Error for HandshakeError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io(e) => Some(e),
            _ => None,
        }
    }
}

impl From<std::io::Error> for HandshakeError {
    fn from(err: std::io::Error) -> Self {
        Self::Io(err)
    }
}

/// Client-side WebSocket handshake configuration.
#[derive(Debug, Clone)]
pub struct ClientHandshake {
    /// Target URL.
    url: WsUrl,
    /// Random client key (base64 encoded).
    key: String,
    /// Requested subprotocols.
    protocols: Vec<String>,
    /// Requested extensions.
    extensions: Vec<String>,
    /// Additional headers.
    headers: BTreeMap<String, String>,
}

impl ClientHandshake {
    /// Internal constructor for deterministic testing.
    #[doc(hidden)]
    pub fn new_for_test(
        url: WsUrl,
        key: String,
        protocols: Vec<String>,
        extensions: Vec<String>,
        headers: BTreeMap<String, String>,
    ) -> Self {
        Self {
            url,
            key,
            protocols,
            extensions,
            headers,
        }
    }

    /// Initiates a new client handshake to the specified URL.
    ///
    /// # Errors
    ///
    /// Returns `HandshakeError::InvalidUrl` if the URL is malformed.
    pub fn new(url: &str, entropy: &dyn EntropySource) -> Result<Self, HandshakeError> {
        let parsed_url = WsUrl::parse(url)?;
        Ok(Self {
            url: parsed_url,
            key: generate_client_key(entropy),
            protocols: Vec::new(),
            extensions: Vec::new(),
            headers: BTreeMap::new(),
        })
    }

    /// Add a subprotocol to request.
    #[must_use]
    pub fn protocol(mut self, protocol: impl Into<String>) -> Self {
        self.protocols.push(protocol.into());
        self
    }

    /// Add an extension to request.
    #[must_use]
    pub fn extension(mut self, extension: impl Into<String>) -> Self {
        self.extensions.push(extension.into());
        self
    }

    /// Add a custom header.
    #[must_use]
    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.insert(name.into(), value.into());
        self
    }

    /// Returns the parsed URL.
    #[must_use]
    pub fn url(&self) -> &WsUrl {
        &self.url
    }

    /// Returns the client key (for validation).
    #[must_use]
    pub fn key(&self) -> &str {
        &self.key
    }

    /// Generate the HTTP upgrade request as bytes.
    #[must_use]
    pub fn request_bytes(&self) -> Vec<u8> {
        let mut request = format!(
            "GET {} HTTP/1.1\r\n\
             Host: {}\r\n\
             Upgrade: websocket\r\n\
             Connection: Upgrade\r\n\
             Sec-WebSocket-Key: {}\r\n\
             Sec-WebSocket-Version: 13\r\n",
            self.url.path,
            self.url.host_header(),
            self.key
        );

        if !self.protocols.is_empty() {
            request.push_str("Sec-WebSocket-Protocol: ");
            let sanitized: Vec<String> = self
                .protocols
                .iter()
                .map(|p| p.replace(['\r', '\n'], ""))
                .collect();
            request.push_str(&sanitized.join(", "));
            request.push_str("\r\n");
        }

        if !self.extensions.is_empty() {
            request.push_str("Sec-WebSocket-Extensions: ");
            let sanitized: Vec<String> = self
                .extensions
                .iter()
                .map(|e| e.replace(['\r', '\n'], ""))
                .collect();
            request.push_str(&sanitized.join(", "));
            request.push_str("\r\n");
        }

        for (name, value) in &self.headers {
            // Sanitize CRLF to prevent HTTP header injection.
            let name = name.replace(['\r', '\n'], "");
            let value = value.replace(['\r', '\n'], "");
            request.push_str(&name);
            request.push_str(": ");
            request.push_str(&value);
            request.push_str("\r\n");
        }

        request.push_str("\r\n");
        request.into_bytes()
    }

    /// Validate the server's HTTP response.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Status is not 101 Switching Protocols
    /// - Required headers are missing
    /// - Sec-WebSocket-Accept is invalid
    /// - Server-selected subprotocol was not requested by the client
    pub fn validate_response(&self, response: &HttpResponse) -> Result<(), HandshakeError> {
        // Check status code
        if response.status != 101 {
            return Err(HandshakeError::NotSwitchingProtocols(response.status));
        }

        // Check Upgrade header
        let upgrade = response
            .header("upgrade")
            .ok_or(HandshakeError::MissingHeader("Upgrade"))?;
        if !header_has_token(upgrade, "websocket") {
            return Err(HandshakeError::InvalidRequest(format!(
                "Upgrade header must contain 'websocket', got '{upgrade}'"
            )));
        }

        // Check Connection header
        let connection = response
            .header("connection")
            .ok_or(HandshakeError::MissingHeader("Connection"))?;
        if !header_has_token(connection, "upgrade") {
            return Err(HandshakeError::InvalidRequest(format!(
                "Connection header must contain 'Upgrade', got '{connection}'"
            )));
        }

        // Validate Sec-WebSocket-Accept
        let accept = response
            .header("sec-websocket-accept")
            .ok_or(HandshakeError::MissingHeader("Sec-WebSocket-Accept"))?;

        let expected = compute_accept_key(&self.key);
        if accept != expected {
            return Err(HandshakeError::InvalidAccept {
                expected,
                actual: accept.to_string(),
            });
        }

        // Validate subprotocol negotiation when server selected one.
        if let Some(offered_protocol) = response.header("sec-websocket-protocol") {
            let offered = offered_protocol.trim().to_string();
            if !self.protocols.iter().any(|requested| requested == &offered) {
                return Err(HandshakeError::ProtocolMismatch {
                    requested: self.protocols.clone(),
                    offered: Some(offered),
                });
            }
        }

        if let Some(offered_extensions) = response.header("sec-websocket-extensions") {
            let offered = parse_extension_offers(offered_extensions);
            let mut invalid = Vec::new();

            for extension in &offered {
                let token = extension_token(extension);
                if token.is_empty()
                    || !self
                        .extensions
                        .iter()
                        .any(|requested| requested.eq_ignore_ascii_case(token))
                {
                    invalid.push(extension.clone());
                }
            }

            if !invalid.is_empty() {
                return Err(HandshakeError::ExtensionMismatch {
                    requested: self.extensions.clone(),
                    offered: invalid,
                });
            }
        }

        Ok(())
    }
}

/// Server-side WebSocket handshake configuration.
#[derive(Debug, Clone, Default)]
pub struct ServerHandshake {
    /// Supported subprotocols.
    supported_protocols: Vec<String>,
    /// Supported extensions.
    supported_extensions: Vec<String>,
}

impl ServerHandshake {
    /// Create a new server handshake configuration.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a supported subprotocol.
    #[must_use]
    pub fn protocol(mut self, protocol: impl Into<String>) -> Self {
        self.supported_protocols.push(protocol.into());
        self
    }

    /// Add a supported extension.
    #[must_use]
    pub fn extension(mut self, extension: impl Into<String>) -> Self {
        self.supported_extensions.push(extension.into());
        self
    }

    /// Validate client request and generate accept response.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Required headers are missing
    /// - WebSocket version is unsupported
    /// - Sec-WebSocket-Key is invalid
    pub fn accept(&self, request: &HttpRequest) -> Result<AcceptResponse, HandshakeError> {
        // Validate HTTP method
        if request.method != "GET" {
            return Err(HandshakeError::InvalidRequest(format!(
                "method must be GET, got '{}'",
                request.method
            )));
        }

        // Check Upgrade header
        let upgrade = request
            .header("upgrade")
            .ok_or(HandshakeError::MissingHeader("Upgrade"))?;
        if !header_has_token(upgrade, "websocket") {
            return Err(HandshakeError::InvalidRequest(format!(
                "Upgrade header must contain 'websocket', got '{upgrade}'"
            )));
        }

        // Check Connection header
        let connection = request
            .header("connection")
            .ok_or(HandshakeError::MissingHeader("Connection"))?;
        if !header_has_token(connection, "upgrade") {
            return Err(HandshakeError::InvalidRequest(format!(
                "Connection header must contain 'Upgrade', got '{connection}'"
            )));
        }

        // Check WebSocket version
        let version = request
            .header("sec-websocket-version")
            .ok_or(HandshakeError::MissingHeader("Sec-WebSocket-Version"))?;
        if version != "13" {
            return Err(HandshakeError::UnsupportedVersion(version.to_string()));
        }

        // Get and validate client key
        let client_key = request
            .header("sec-websocket-key")
            .ok_or(HandshakeError::MissingHeader("Sec-WebSocket-Key"))?;

        // Validate key is valid base64 of 16 bytes (24 chars with padding)
        match base64::engine::general_purpose::STANDARD.decode(client_key) {
            Ok(decoded) if decoded.len() == 16 => {}
            _ => return Err(HandshakeError::InvalidKey),
        }

        // Compute accept key
        let accept_key = compute_accept_key(client_key);

        // Negotiate subprotocol.
        //
        // RFC 6455 §4.2.2: the server selects one of the client-offered
        // subprotocols, honoring the client's preference order. Iterate the
        // client's list first and return the first entry the server supports.
        //
        // If the server has been configured with a non-empty set of supported
        // protocols and the client offers protocols, fail the handshake with
        // `ProtocolMismatch` when none of the client's offers are supported.
        let selected_protocol = if let Some(requested) = request.header("sec-websocket-protocol") {
            let offered: Vec<String> = requested
                .split(',')
                .map(str::trim)
                .filter(|candidate| !candidate.is_empty())
                .map(ToOwned::to_owned)
                .collect();
            let selected = offered.iter().find(|candidate| {
                self.supported_protocols
                    .iter()
                    .any(|supported| supported.as_str() == candidate.as_str())
            });
            match selected {
                Some(s) => Some(s.clone()),
                None if !self.supported_protocols.is_empty() && !offered.is_empty() => {
                    return Err(HandshakeError::ProtocolMismatch {
                        requested: offered,
                        offered: None,
                    });
                }
                None => None,
            }
        } else {
            None
        };

        let negotiated_extensions =
            request
                .header("sec-websocket-extensions")
                .map_or_else(Vec::new, |requested| {
                    let mut accepted = Vec::new();
                    let mut accepted_tokens = std::collections::BTreeSet::new();
                    for offer in parse_extension_offers(requested) {
                        let token = extension_token(&offer);
                        if token.is_empty() {
                            continue;
                        }
                        if self
                            .supported_extensions
                            .iter()
                            .any(|supported| supported.eq_ignore_ascii_case(token))
                        {
                            let normalized = token.to_ascii_lowercase();
                            if accepted_tokens.insert(normalized) {
                                // Sanitize: strip CR/LF to prevent HTTP response splitting.
                                let safe = offer.replace(['\r', '\n'], "");
                                accepted.push(safe);
                            }
                        }
                    }
                    accepted
                });

        Ok(AcceptResponse {
            accept_key,
            protocol: selected_protocol,
            extensions: negotiated_extensions,
        })
    }

    /// Generate a rejection response with the given HTTP status code.
    #[must_use]
    pub fn reject(status: u16, reason: &str) -> Vec<u8> {
        // Sanitize CRLF to prevent HTTP response header injection.
        let reason = reason.replace(['\r', '\n'], "");
        format!(
            "HTTP/1.1 {status} {reason}\r\n\
             Connection: close\r\n\
             \r\n"
        )
        .into_bytes()
    }
}

/// Result of accepting a WebSocket upgrade.
#[derive(Debug, Clone)]
pub struct AcceptResponse {
    /// Computed Sec-WebSocket-Accept value.
    pub accept_key: String,
    /// Negotiated subprotocol (if any).
    pub protocol: Option<String>,
    /// Negotiated extensions.
    pub extensions: Vec<String>,
}

impl AcceptResponse {
    /// Generate the HTTP 101 response as bytes.
    #[must_use]
    pub fn response_bytes(&self) -> Vec<u8> {
        let mut response = String::from(
            "HTTP/1.1 101 Switching Protocols\r\n\
             Upgrade: websocket\r\n\
             Connection: Upgrade\r\n",
        );

        response.push_str("Sec-WebSocket-Accept: ");
        response.push_str(&self.accept_key);
        response.push_str("\r\n");

        if let Some(ref protocol) = self.protocol {
            response.push_str("Sec-WebSocket-Protocol: ");
            response.push_str(protocol);
            response.push_str("\r\n");
        }

        if !self.extensions.is_empty() {
            response.push_str("Sec-WebSocket-Extensions: ");
            response.push_str(&self.extensions.join(", "));
            response.push_str("\r\n");
        }

        response.push_str("\r\n");
        response.into_bytes()
    }
}

/// Minimal HTTP request representation for handshake.
#[derive(Debug, Clone)]
pub struct HttpRequest {
    /// HTTP method (should be GET for WebSocket).
    pub method: String,
    /// Request path.
    pub path: String,
    /// HTTP headers (lowercase keys).
    headers: BTreeMap<String, String>,
}

impl HttpRequest {
    /// Parse an HTTP request from bytes, returning the parsed request and any trailing bytes.
    ///
    /// # Errors
    ///
    /// Returns `HandshakeError::InvalidRequest` if parsing fails.
    #[allow(clippy::option_if_let_else)]
    pub fn parse_with_trailing(data: &[u8]) -> Result<(Self, &[u8]), HandshakeError> {
        let (header_bytes, trailing) = split_http_header_block(data)?;

        let text = std::str::from_utf8(header_bytes)
            .map_err(|_| HandshakeError::InvalidRequest("invalid UTF-8".into()))?;

        let mut lines = text.lines();

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

        let mut parts = request_line.split_whitespace();
        let method = parts
            .next()
            .ok_or_else(|| HandshakeError::InvalidRequest("missing method".into()))?
            .to_string();
        let path = parts
            .next()
            .ok_or_else(|| HandshakeError::InvalidRequest("missing path".into()))?
            .to_string();

        // Parse headers
        let mut headers = BTreeMap::new();
        for line in lines {
            if line.is_empty() {
                break;
            }
            if let Some((name, value)) = line.split_once(':') {
                headers.insert(name.trim().to_ascii_lowercase(), value.trim().to_string());
            }
        }

        Ok((
            Self {
                method,
                path,
                headers,
            },
            trailing,
        ))
    }

    /// Parse an HTTP request from bytes.
    ///
    /// # Errors
    ///
    /// Returns `HandshakeError::InvalidRequest` if parsing fails.
    pub fn parse(data: &[u8]) -> Result<Self, HandshakeError> {
        Self::parse_with_trailing(data).map(|(req, _)| req)
    }

    /// Get a header value by name (case-insensitive).
    #[must_use]
    pub fn header(&self, name: &str) -> Option<&str> {
        self.headers
            .get(&name.to_ascii_lowercase())
            .map(String::as_str)
    }
}

/// Minimal HTTP response representation for handshake.
#[derive(Debug, Clone)]
pub struct HttpResponse {
    /// HTTP status code.
    pub status: u16,
    /// Status reason phrase.
    pub reason: String,
    /// HTTP headers (lowercase keys).
    headers: BTreeMap<String, String>,
}

impl HttpResponse {
    /// Parse an HTTP response from bytes.
    ///
    /// # Errors
    ///
    /// Returns `HandshakeError::InvalidRequest` if parsing fails.
    pub fn parse(data: &[u8]) -> Result<Self, HandshakeError> {
        let (header_bytes, _trailing) = split_http_header_block(data)?;
        let text = std::str::from_utf8(header_bytes)
            .map_err(|_| HandshakeError::InvalidRequest("invalid UTF-8".into()))?;

        let mut lines = text.lines();

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

        let mut parts = status_line.splitn(3, ' ');
        let _version = parts
            .next()
            .ok_or_else(|| HandshakeError::InvalidRequest("missing HTTP version".into()))?;
        let status: u16 = parts
            .next()
            .ok_or_else(|| HandshakeError::InvalidRequest("missing status code".into()))?
            .parse()
            .map_err(|_| HandshakeError::InvalidRequest("invalid status code".into()))?;
        let reason = parts.next().unwrap_or("").to_string();

        // Parse headers
        let mut headers = BTreeMap::new();
        for line in lines {
            if line.is_empty() {
                break;
            }
            if let Some((name, value)) = line.split_once(':') {
                headers.insert(name.trim().to_ascii_lowercase(), value.trim().to_string());
            }
        }

        Ok(Self {
            status,
            reason,
            headers,
        })
    }

    /// Get a header value by name (case-insensitive).
    #[must_use]
    pub fn header(&self, name: &str) -> Option<&str> {
        self.headers
            .get(&name.to_ascii_lowercase())
            .map(String::as_str)
    }
}

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

    #[test]
    fn test_compute_accept_key() {
        // RFC 6455 example
        let client_key = "dGhlIHNhbXBsZSBub25jZQ==";
        let accept = compute_accept_key(client_key);
        assert_eq!(accept, "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=");
    }

    #[test]
    fn test_ws_url_parse() {
        // Basic ws://
        let url = WsUrl::parse("ws://example.com/chat").unwrap();
        assert_eq!(url.host, "example.com");
        assert_eq!(url.port, 80);
        assert_eq!(url.path, "/chat");
        assert!(!url.tls);

        // wss:// with port
        let url = WsUrl::parse("wss://example.com:8443/ws").unwrap();
        assert_eq!(url.host, "example.com");
        assert_eq!(url.port, 8443);
        assert_eq!(url.path, "/ws");
        assert!(url.tls);

        // No path
        let url = WsUrl::parse("ws://localhost:9000").unwrap();
        assert_eq!(url.host, "localhost");
        assert_eq!(url.port, 9000);
        assert_eq!(url.path, "/");

        // IPv6
        let url = WsUrl::parse("ws://[::1]:8080/test").unwrap();
        assert_eq!(url.host, "::1");
        assert_eq!(url.port, 8080);
        assert_eq!(url.path, "/test");
    }

    #[test]
    fn test_ws_url_host_header() {
        let url = WsUrl::parse("ws://example.com/chat").unwrap();
        assert_eq!(url.host_header(), "example.com");

        let url = WsUrl::parse("ws://example.com:8080/chat").unwrap();
        assert_eq!(url.host_header(), "example.com:8080");

        let url = WsUrl::parse("wss://example.com/chat").unwrap();
        assert_eq!(url.host_header(), "example.com");

        let url = WsUrl::parse("wss://example.com:443/chat").unwrap();
        assert_eq!(url.host_header(), "example.com");
    }

    #[test]
    fn test_client_handshake_request() {
        let entropy = DetEntropy::new(7);
        let handshake = ClientHandshake::new("ws://example.com/chat", &entropy)
            .unwrap()
            .protocol("chat");

        let request = handshake.request_bytes();
        let text = String::from_utf8(request).unwrap();

        assert!(text.starts_with("GET /chat HTTP/1.1\r\n"));
        assert!(text.contains("Host: example.com\r\n"));
        assert!(text.contains("Upgrade: websocket\r\n"));
        assert!(text.contains("Connection: Upgrade\r\n"));
        assert!(text.contains("Sec-WebSocket-Key: "));
        assert!(text.contains("Sec-WebSocket-Version: 13\r\n"));
        assert!(text.contains("Sec-WebSocket-Protocol: chat\r\n"));
        assert!(text.ends_with("\r\n\r\n"));
    }

    #[test]
    fn test_client_validate_response() {
        let handshake = ClientHandshake {
            url: WsUrl::parse("ws://example.com/chat").unwrap(),
            key: "dGhlIHNhbXBsZSBub25jZQ==".to_string(),
            protocols: vec![],
            extensions: vec![],
            headers: BTreeMap::new(),
        };

        let response = HttpResponse::parse(
            b"HTTP/1.1 101 Switching Protocols\r\n\
              Upgrade: websocket\r\n\
              Connection: Upgrade\r\n\
              Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\
              \r\n",
        )
        .unwrap();

        assert!(handshake.validate_response(&response).is_ok());
    }

    #[test]
    fn test_client_validate_response_rejects_connection_substring_false_positive() {
        let handshake = ClientHandshake {
            url: WsUrl::parse("ws://example.com/chat").unwrap(),
            key: "dGhlIHNhbXBsZSBub25jZQ==".to_string(),
            protocols: vec![],
            extensions: vec![],
            headers: BTreeMap::new(),
        };

        let response = HttpResponse::parse(
            b"HTTP/1.1 101 Switching Protocols\r\n\
              Upgrade: websocket\r\n\
              Connection: notupgrade\r\n\
              Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\
              \r\n",
        )
        .unwrap();

        let err = handshake.validate_response(&response).unwrap_err();
        assert!(matches!(err, HandshakeError::InvalidRequest(_)));
    }

    #[test]
    fn test_client_validate_response_allows_upgrade_header_token_list() {
        let handshake = ClientHandshake {
            url: WsUrl::parse("ws://example.com/chat").unwrap(),
            key: "dGhlIHNhbXBsZSBub25jZQ==".to_string(),
            protocols: vec![],
            extensions: vec![],
            headers: BTreeMap::new(),
        };

        let response = HttpResponse::parse(
            b"HTTP/1.1 101 Switching Protocols\r\n\
              Upgrade: h2c, websocket\r\n\
              Connection: keep-alive, Upgrade\r\n\
              Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\
              \r\n",
        )
        .unwrap();

        assert!(handshake.validate_response(&response).is_ok());
    }

    #[test]
    fn test_client_validate_response_bad_accept() {
        let handshake = ClientHandshake {
            url: WsUrl::parse("ws://example.com/chat").unwrap(),
            key: "dGhlIHNhbXBsZSBub25jZQ==".to_string(),
            protocols: vec![],
            extensions: vec![],
            headers: BTreeMap::new(),
        };

        let response = HttpResponse::parse(
            b"HTTP/1.1 101 Switching Protocols\r\n\
              Upgrade: websocket\r\n\
              Connection: Upgrade\r\n\
              Sec-WebSocket-Accept: wrong-accept-key\r\n\
              \r\n",
        )
        .unwrap();

        let err = handshake.validate_response(&response).unwrap_err();
        assert!(matches!(err, HandshakeError::InvalidAccept { .. }));
    }

    #[test]
    fn test_client_validate_response_unsolicited_protocol_rejected() {
        let handshake = ClientHandshake {
            url: WsUrl::parse("ws://example.com/chat").expect("valid url"),
            key: "dGhlIHNhbXBsZSBub25jZQ==".to_string(),
            protocols: vec![],
            extensions: vec![],
            headers: BTreeMap::new(),
        };

        let response = HttpResponse::parse(
            b"HTTP/1.1 101 Switching Protocols\r\n\
              Upgrade: websocket\r\n\
              Connection: Upgrade\r\n\
              Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\
              Sec-WebSocket-Protocol: chat\r\n\
              \r\n",
        )
        .expect("response must parse");

        let err = handshake
            .validate_response(&response)
            .expect_err("unsolicited protocol must be rejected");
        assert!(matches!(err, HandshakeError::ProtocolMismatch { .. }));
    }

    #[test]
    fn test_client_validate_response_unrequested_protocol_rejected() {
        let handshake = ClientHandshake {
            url: WsUrl::parse("ws://example.com/chat").expect("valid url"),
            key: "dGhlIHNhbXBsZSBub25jZQ==".to_string(),
            protocols: vec!["chat".to_string()],
            extensions: vec![],
            headers: BTreeMap::new(),
        };

        let response = HttpResponse::parse(
            b"HTTP/1.1 101 Switching Protocols\r\n\
              Upgrade: websocket\r\n\
              Connection: Upgrade\r\n\
              Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\
              Sec-WebSocket-Protocol: superchat\r\n\
              \r\n",
        )
        .expect("response must parse");

        let err = handshake
            .validate_response(&response)
            .expect_err("protocol not in request must be rejected");
        assert!(matches!(err, HandshakeError::ProtocolMismatch { .. }));
    }

    #[test]
    fn test_client_validate_response_requested_protocol_accepted() {
        let handshake = ClientHandshake {
            url: WsUrl::parse("ws://example.com/chat").expect("valid url"),
            key: "dGhlIHNhbXBsZSBub25jZQ==".to_string(),
            protocols: vec!["chat".to_string(), "superchat".to_string()],
            extensions: vec![],
            headers: BTreeMap::new(),
        };

        let response = HttpResponse::parse(
            b"HTTP/1.1 101 Switching Protocols\r\n\
              Upgrade: websocket\r\n\
              Connection: Upgrade\r\n\
              Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\
              Sec-WebSocket-Protocol: superchat\r\n\
              \r\n",
        )
        .expect("response must parse");

        assert!(handshake.validate_response(&response).is_ok());
    }

    #[test]
    fn test_server_accept() {
        let server = ServerHandshake::new().protocol("chat");

        let request = HttpRequest::parse(
            b"GET /chat HTTP/1.1\r\n\
              Host: example.com\r\n\
              Upgrade: websocket\r\n\
              Connection: Upgrade\r\n\
              Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\
              Sec-WebSocket-Version: 13\r\n\
              Sec-WebSocket-Protocol: chat\r\n\
              \r\n",
        )
        .unwrap();

        let accept = server.accept(&request).unwrap();
        assert_eq!(accept.accept_key, "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=");
        assert_eq!(accept.protocol, Some("chat".to_string()));
    }

    #[test]
    fn test_server_accept_allows_upgrade_header_token_list() {
        let server = ServerHandshake::new();

        let request = HttpRequest::parse(
            b"GET /chat HTTP/1.1\r\n\
              Host: example.com\r\n\
              Upgrade: h2c, websocket\r\n\
              Connection: keep-alive, Upgrade\r\n\
              Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\
              Sec-WebSocket-Version: 13\r\n\
              \r\n",
        )
        .unwrap();

        let accept = server.accept(&request).unwrap();
        assert_eq!(accept.accept_key, "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=");
    }

    #[test]
    fn test_server_accept_rejects_connection_substring_false_positive() {
        let server = ServerHandshake::new();

        let request = HttpRequest::parse(
            b"GET /chat HTTP/1.1\r\n\
              Host: example.com\r\n\
              Upgrade: websocket\r\n\
              Connection: notupgrade\r\n\
              Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\
              Sec-WebSocket-Version: 13\r\n\
              \r\n",
        )
        .unwrap();

        let err = server.accept(&request).unwrap_err();
        assert!(matches!(err, HandshakeError::InvalidRequest(_)));
    }

    #[test]
    fn test_server_accept_negotiates_extensions() {
        let server = ServerHandshake::new()
            .extension("permessage-deflate")
            .extension("x-webkit-deflate-frame");

        let request = HttpRequest::parse(
            b"GET /chat HTTP/1.1\r\n\
              Host: example.com\r\n\
              Upgrade: websocket\r\n\
              Connection: Upgrade\r\n\
              Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\
              Sec-WebSocket-Version: 13\r\n\
              Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits, x-ignored\r\n\
              \r\n",
        )
        .unwrap();

        let accept = server.accept(&request).unwrap();
        assert_eq!(
            accept.extensions,
            vec!["permessage-deflate; client_max_window_bits".to_string()]
        );
    }

    #[test]
    fn test_server_reject_bad_version() {
        let server = ServerHandshake::new();

        let request = HttpRequest::parse(
            b"GET /chat HTTP/1.1\r\n\
              Host: example.com\r\n\
              Upgrade: websocket\r\n\
              Connection: Upgrade\r\n\
              Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\
              Sec-WebSocket-Version: 8\r\n\
              \r\n",
        )
        .unwrap();

        let err = server.accept(&request).unwrap_err();
        assert!(matches!(err, HandshakeError::UnsupportedVersion(_)));
    }

    #[test]
    fn test_accept_response_bytes() {
        let accept = AcceptResponse {
            accept_key: "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=".to_string(),
            protocol: Some("chat".to_string()),
            extensions: vec![],
        };

        let response = accept.response_bytes();
        let text = String::from_utf8(response).unwrap();

        assert!(text.starts_with("HTTP/1.1 101 Switching Protocols\r\n"));
        assert!(text.contains("Upgrade: websocket\r\n"));
        assert!(text.contains("Connection: Upgrade\r\n"));
        assert!(text.contains("Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n"));
        assert!(text.contains("Sec-WebSocket-Protocol: chat\r\n"));
        assert!(text.ends_with("\r\n\r\n"));
    }

    #[test]
    fn test_accept_response_snapshot_negotiated_protocol_and_extension() {
        let server = ServerHandshake::new()
            .protocol("superchat")
            .extension("permessage-deflate");

        let request = HttpRequest::parse(
            b"GET /chat HTTP/1.1\r\n\
              Host: example.com\r\n\
              Upgrade: websocket\r\n\
              Connection: keep-alive, Upgrade\r\n\
              Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\
              Sec-WebSocket-Version: 13\r\n\
              Sec-WebSocket-Protocol: chat, superchat\r\n\
              Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits, x-ignored\r\n\
              \r\n",
        )
        .unwrap();

        let accept = server.accept(&request).unwrap();
        let response = String::from_utf8(accept.response_bytes()).unwrap();

        insta::assert_snapshot!(
            "accept_response_negotiated_protocol_and_extension",
            response
        );
    }

    #[test]
    fn test_client_validate_response_rejects_unsolicited_extensions() {
        let handshake = ClientHandshake {
            url: WsUrl::parse("ws://example.com/chat").expect("valid url"),
            key: "dGhlIHNhbXBsZSBub25jZQ==".to_string(),
            protocols: vec![],
            extensions: vec!["permessage-deflate".to_string()],
            headers: BTreeMap::new(),
        };

        let response = HttpResponse::parse(
            b"HTTP/1.1 101 Switching Protocols\r\n\
              Upgrade: websocket\r\n\
              Connection: Upgrade\r\n\
              Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\
              Sec-WebSocket-Extensions: x-unrequested\r\n\
              \r\n",
        )
        .expect("response must parse");

        let err = handshake
            .validate_response(&response)
            .expect_err("unrequested extension must be rejected");
        assert!(matches!(err, HandshakeError::ExtensionMismatch { .. }));
    }

    #[test]
    fn test_client_validate_response_accepts_requested_extensions() {
        let handshake = ClientHandshake {
            url: WsUrl::parse("ws://example.com/chat").expect("valid url"),
            key: "dGhlIHNhbXBsZSBub25jZQ==".to_string(),
            protocols: vec![],
            extensions: vec!["permessage-deflate".to_string()],
            headers: BTreeMap::new(),
        };

        let response = HttpResponse::parse(
            b"HTTP/1.1 101 Switching Protocols\r\n\
              Upgrade: websocket\r\n\
              Connection: Upgrade\r\n\
              Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\
              Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits\r\n\
              \r\n",
        )
        .expect("response must parse");

        assert!(handshake.validate_response(&response).is_ok());
    }

    #[test]
    fn test_http_request_parse() {
        let request = HttpRequest::parse(
            b"GET /chat HTTP/1.1\r\n\
              Host: example.com\r\n\
              Upgrade: WebSocket\r\n\
              Connection: Upgrade\r\n\
              \r\n",
        )
        .unwrap();

        assert_eq!(request.method, "GET");
        assert_eq!(request.path, "/chat");
        assert_eq!(request.header("host"), Some("example.com"));
        assert_eq!(request.header("upgrade"), Some("WebSocket"));
        assert_eq!(request.header("connection"), Some("Upgrade"));
    }

    #[test]
    fn test_http_request_parse_rejects_incomplete_headers() {
        let err = HttpRequest::parse(
            b"GET /chat HTTP/1.1\r\n\
              Host: example.com\r\n\
              Upgrade: websocket\r\n\
              Connection: Upgrade\r\n",
        )
        .expect_err("missing blank line must be treated as an incomplete request");

        assert!(matches!(err, HandshakeError::InvalidRequest(_)));
    }

    #[test]
    fn test_http_response_parse() {
        let response = HttpResponse::parse(
            b"HTTP/1.1 101 Switching Protocols\r\n\
              Upgrade: websocket\r\n\
              Connection: Upgrade\r\n\
              Sec-WebSocket-Accept: xyz\r\n\
              \r\n",
        )
        .unwrap();

        assert_eq!(response.status, 101);
        assert_eq!(response.reason, "Switching Protocols");
        assert_eq!(response.header("upgrade"), Some("websocket"));
        assert_eq!(response.header("sec-websocket-accept"), Some("xyz"));
    }

    #[test]
    fn test_http_response_parse_rejects_incomplete_headers() {
        let err = HttpResponse::parse(
            b"HTTP/1.1 101 Switching Protocols\r\n\
              Upgrade: websocket\r\n\
              Connection: Upgrade\r\n\
              Sec-WebSocket-Accept: xyz\r\n",
        )
        .expect_err("missing blank line must be treated as an incomplete response");

        assert!(matches!(err, HandshakeError::InvalidRequest(_)));
    }

    #[test]
    fn test_split_http_header_block_prefers_earliest_complete_terminator() {
        let data = b"GET /chat HTTP/1.1\n\
Host: example.com\n\
Upgrade: websocket\n\
Connection: Upgrade\n\
\n\
body-prefix\r\n\r\nstill-body";

        let (header, trailing) = split_http_header_block(data).unwrap();

        assert_eq!(
            header,
            b"GET /chat HTTP/1.1\n\
Host: example.com\n\
Upgrade: websocket\n\
Connection: Upgrade\n\
\n"
        );
        assert_eq!(trailing, b"body-prefix\r\n\r\nstill-body");
    }

    #[test]
    fn test_generate_client_key() {
        let entropy = DetEntropy::new(42);
        let key = generate_client_key(&entropy);
        // Should be valid base64 of 16 bytes = 24 chars with padding
        let decoded = base64::engine::general_purpose::STANDARD
            .decode(&key)
            .unwrap();
        assert_eq!(decoded.len(), 16);
    }

    #[test]
    fn ws_url_debug_clone_eq() {
        let u = WsUrl {
            host: "example.com".into(),
            port: 80,
            path: "/chat".into(),
            tls: false,
        };
        let dbg = format!("{u:?}");
        assert!(dbg.contains("WsUrl"));
        assert!(dbg.contains("example.com"));

        let u2 = u.clone();
        assert_eq!(u, u2);

        let u3 = WsUrl {
            host: "other.com".into(),
            port: 443,
            path: "/".into(),
            tls: true,
        };
        assert_ne!(u, u3);
    }

    #[test]
    fn server_handshake_debug_clone_default() {
        let s = ServerHandshake::default();
        let dbg = format!("{s:?}");
        assert!(dbg.contains("ServerHandshake"));

        let s2 = s;
        let dbg2 = format!("{s2:?}");
        assert_eq!(dbg, dbg2);
    }

    #[test]
    fn http_request_debug_clone() {
        let r = HttpRequest::parse(b"GET /test HTTP/1.1\r\nHost: localhost\r\n\r\n").unwrap();
        let dbg = format!("{r:?}");
        assert!(dbg.contains("HttpRequest"));

        let r2 = r;
        assert_eq!(r2.method, "GET");
        assert_eq!(r2.path, "/test");
    }

    #[test]
    fn server_accept_strips_crlf_from_extension_offers() {
        // Regression: unsanitized extension offers could inject \r\n into
        // the HTTP response, enabling response splitting.
        let raw_request = "GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\n\
             Connection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\
             Sec-WebSocket-Version: 13\r\n\r\n";
        let mut request = HttpRequest::parse(raw_request.as_bytes()).unwrap();
        // Inject a malicious extension header with embedded CRLF. In a real
        // scenario this could come from a misbehaving HTTP/1.1 parser or a
        // crafted client that smuggles newlines past line-folding rules.
        request.headers.insert(
            "sec-websocket-extensions".to_string(),
            "permessage-deflate; x\r\nX-Injected: evil".to_string(),
        );

        let server = ServerHandshake::new().extension("permessage-deflate");
        let accept = server.accept(&request).unwrap();
        let response = accept.response_bytes();
        let response_str = String::from_utf8_lossy(&response);
        // Count the number of lines — response splitting would add extra header lines.
        let line_count = response_str.lines().count();
        // Normal 101 response has: status + 3 headers + extensions + empty = 6 lines.
        assert!(
            line_count <= 7,
            "response splitting injected extra header lines: {response_str}"
        );
        // Verify the extension value has \r\n stripped (no standalone "X-Injected:" header).
        for line in response_str.lines() {
            if line.starts_with("Sec-WebSocket-Extensions:") {
                assert!(
                    !line.contains('\r') && !line.contains('\n'),
                    "extension header must not contain embedded CRLF: {line}"
                );
            }
        }
    }

    // =========================================================================
    // RFC 6455 Sec-WebSocket-Key Validation Golden Conformance Tests
    // =========================================================================

    /// Golden Test #1: 16-byte base64 key validation per RFC 6455 Section 4.1
    #[test]
    fn golden_16_byte_base64_key_validation() {
        // Test comprehensive validation of Sec-WebSocket-Key format requirements

        let server = ServerHandshake::new();

        // Valid 16-byte keys (should succeed)
        let valid_keys = vec![
            "dGhlIHNhbXBsZSBub25jZQ==",    // RFC 6455 example
            "AQIDBAUGBwgJCgsMDQ4PEA==",    // Sequential bytes 0x01-0x10
            "/////////////////////w==",    // All 0xFF bytes (16 bytes)
            "AAAAAAAAAAAAAAAAAAAAAA==",    // All zero bytes
            "MTIzNDU2Nzg5YWJjZGVmZw==",    // "1234567890abcdefg" (16 bytes)
        ];

        for (i, key) in valid_keys.iter().enumerate() {
            let request_data = format!(
                "GET /test HTTP/1.1\r\n\
                 Host: localhost\r\n\
                 Upgrade: websocket\r\n\
                 Connection: Upgrade\r\n\
                 Sec-WebSocket-Key: {}\r\n\
                 Sec-WebSocket-Version: 13\r\n\r\n",
                key
            );

            let request = HttpRequest::parse(request_data.as_bytes())
                .expect(&format!("Failed to parse request {}", i));

            let result = server.accept(&request);
            assert!(
                result.is_ok(),
                "Valid 16-byte key #{} should be accepted: '{}', error: {:?}",
                i,
                key,
                result.unwrap_err()
            );

            // Verify the decoded key is exactly 16 bytes
            let decoded = base64::engine::general_purpose::STANDARD
                .decode(key)
                .expect("Key should decode properly");
            assert_eq!(
                decoded.len(),
                16,
                "Key #{} should decode to exactly 16 bytes: '{}'",
                i,
                key
            );
        }

        // Invalid keys (should fail with InvalidKey error)
        let invalid_keys = vec![
            ("", "empty key"),
            ("dGhlIHNhbXBsZSBub25jZQ", "missing padding"),
            ("dGhlIHNhbXBsZSBub25jZQ====", "too much padding"),
            ("dGhlIHNhbXBsZSBub25jZ===", "15 bytes (one short)"),
            ("dGhlIHNhbXBsZSBub25jZGQ=", "17 bytes (one too many)"),
            ("dGhlIHNhbXBsZSBub25jZGRk", "18 bytes"),
            ("MTIzNA==", "only 4 bytes"),
            ("!@#$%^&*()_+{}|:<>?", "invalid base64 characters"),
            ("dGhlIHNhbXBsZSBub25jZQ=", "invalid padding"),
            ("AAAAAAAAAAAAAAAAAAAAAAAAAAAA", "32 bytes"),
        ];

        for (key, description) in invalid_keys {
            let request_data = format!(
                "GET /test HTTP/1.1\r\n\
                 Host: localhost\r\n\
                 Upgrade: websocket\r\n\
                 Connection: Upgrade\r\n\
                 Sec-WebSocket-Key: {}\r\n\
                 Sec-WebSocket-Version: 13\r\n\r\n",
                key
            );

            let request = HttpRequest::parse(request_data.as_bytes())
                .expect(&format!("Failed to parse request for {}", description));

            let result = server.accept(&request);
            assert!(
                result.is_err(),
                "Invalid key should be rejected: {} ({})",
                key,
                description
            );

            if let Err(error) = result {
                assert!(
                    matches!(error, HandshakeError::InvalidKey),
                    "Should fail with InvalidKey error for {}: got {:?}",
                    description,
                    error
                );
            }
        }
    }

    /// Golden Test #2: SHA-1 + fixed GUID concatenation per RFC 6455 Section 4.2.2
    #[test]
    fn golden_sha1_fixed_guid_concatenation() {
        // Test exact SHA-1 computation with RFC 6455 GUID per specification

        // RFC 6455 Section 4.2.2 test vector
        let client_key = "dGhlIHNhbXBsZSBub25jZQ==";
        let expected_accept = "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=";

        let actual_accept = compute_accept_key(client_key);
        assert_eq!(
            actual_accept, expected_accept,
            "RFC 6455 test vector must match exactly"
        );

        // Verify the computation step by step
        let concatenated = format!("{}{}", client_key, WS_GUID);
        assert_eq!(
            concatenated,
            "dGhlIHNhbXBsZSBub25jZQ==258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
        );

        let mut hasher = Sha1::new();
        hasher.update(concatenated.as_bytes());
        let hash = hasher.finalize();

        let manual_accept = base64::engine::general_purpose::STANDARD.encode(hash);
        assert_eq!(
            manual_accept, expected_accept,
            "Manual computation should match library computation"
        );

        // Test additional known vectors to ensure consistency.
        // Each expected value was produced by concatenating the key with the
        // RFC 6455 GUID, computing SHA-1, and base64-encoding the digest.
        let test_vectors = vec![
            ("AQIDBAUGBwgJCgsMDQ4PEA==", "C/0nmHhBztSRGR1CwL6Tf4ZjwpY="),
            ("AAAAAAAAAAAAAAAAAAAAAA==", "ICX+Yqv66kxgM0FcWaLWlFLwTAI="),
            ("/////////////////////w==", "XXpj4jYzLM2yUE0C7TIgMwTQh2g="),
        ];

        for (key, expected) in test_vectors {
            let computed = compute_accept_key(key);
            assert_eq!(
                computed, expected,
                "Accept key computation failed for test vector: key={}, expected={}, got={}",
                key, expected, computed
            );

            // Verify computation is deterministic (same result every time)
            let computed_again = compute_accept_key(key);
            assert_eq!(
                computed, computed_again,
                "Accept key computation should be deterministic"
            );
        }

        // Verify GUID constant is exactly per RFC 6455
        assert_eq!(WS_GUID, "258EAFA5-E914-47DA-95CA-C5AB0DC85B11");

        // Test that changing GUID breaks the computation (negative test)
        let wrong_guid = "358EAFA5-E914-47DA-95CA-C5AB0DC85B11"; // Changed first digit
        let concatenated_wrong = format!("{}{}", client_key, wrong_guid);
        let mut hasher_wrong = Sha1::new();
        hasher_wrong.update(concatenated_wrong.as_bytes());
        let hash_wrong = hasher_wrong.finalize();
        let wrong_accept = base64::engine::general_purpose::STANDARD.encode(hash_wrong);

        assert_ne!(
            wrong_accept, expected_accept,
            "Wrong GUID should produce different result"
        );
    }

    /// Golden Test #3: Key reuse detection across multiple connections
    #[test]
    fn golden_key_reuse_detection() {
        // Test that the same key can be reused (RFC 6455 doesn't prohibit this)
        // but verify deterministic behavior for identical inputs

        let server = ServerHandshake::new().protocol("chat");
        let reused_key = "dGhlIHNhbXBsZSBub25jZQ==";

        // First connection with the key
        let request1_data = format!(
            "GET /test1 HTTP/1.1\r\n\
             Host: localhost\r\n\
             Upgrade: websocket\r\n\
             Connection: Upgrade\r\n\
             Sec-WebSocket-Key: {}\r\n\
             Sec-WebSocket-Version: 13\r\n\
             Sec-WebSocket-Protocol: chat\r\n\r\n",
            reused_key
        );

        let request1 =
            HttpRequest::parse(request1_data.as_bytes()).expect("First request should parse");

        let accept1 = server
            .accept(&request1)
            .expect("First connection should be accepted");

        // Second connection with the same key (different path)
        let request2_data = format!(
            "GET /test2 HTTP/1.1\r\n\
             Host: localhost\r\n\
             Upgrade: websocket\r\n\
             Connection: Upgrade\r\n\
             Sec-WebSocket-Key: {}\r\n\
             Sec-WebSocket-Version: 13\r\n\
             Sec-WebSocket-Protocol: chat\r\n\r\n",
            reused_key
        );

        let request2 =
            HttpRequest::parse(request2_data.as_bytes()).expect("Second request should parse");

        let accept2 = server
            .accept(&request2)
            .expect("Second connection should be accepted");

        // Verify both connections produce the same accept key (deterministic)
        assert_eq!(
            accept1.accept_key, accept2.accept_key,
            "Same client key should always produce same accept key"
        );

        // Verify the accept key matches RFC test vector
        assert_eq!(accept1.accept_key, "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=");

        // Test multiple rapid connections with same key (stress test)
        for i in 0..10 {
            let request_data = format!(
                "GET /test{} HTTP/1.1\r\n\
                 Host: localhost\r\n\
                 Upgrade: websocket\r\n\
                 Connection: Upgrade\r\n\
                 Sec-WebSocket-Key: {}\r\n\
                 Sec-WebSocket-Version: 13\r\n\r\n",
                i, reused_key
            );

            let request = HttpRequest::parse(request_data.as_bytes())
                .expect(&format!("Request {} should parse", i));

            let accept = server
                .accept(&request)
                .expect(&format!("Connection {} should be accepted", i));

            assert_eq!(
                accept.accept_key, "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=",
                "Connection {} should have consistent accept key",
                i
            );
        }

        // Test that different keys produce different accept values
        let different_keys = vec![
            "AQIDBAUGBwgJCgsMDQ4PEA==",
            "AAAAAAAAAAAAAAAAAAAAAA==",
            "/////////////////////w==",
        ];

        let mut accept_keys = vec![accept1.accept_key.clone()];
        for (i, key) in different_keys.iter().enumerate() {
            let request_data = format!(
                "GET /unique{} HTTP/1.1\r\n\
                 Host: localhost\r\n\
                 Upgrade: websocket\r\n\
                 Connection: Upgrade\r\n\
                 Sec-WebSocket-Key: {}\r\n\
                 Sec-WebSocket-Version: 13\r\n\r\n",
                i, key
            );

            let request = HttpRequest::parse(request_data.as_bytes())
                .expect(&format!("Request for key {} should parse", i));

            let accept = server
                .accept(&request)
                .expect(&format!("Connection for key {} should be accepted", i));

            accept_keys.push(accept.accept_key.clone());
        }

        // Verify all accept keys are different
        for i in 0..accept_keys.len() {
            for j in (i + 1)..accept_keys.len() {
                assert_ne!(
                    accept_keys[i], accept_keys[j],
                    "Accept keys {} and {} should be different: '{}' vs '{}'",
                    i, j, accept_keys[i], accept_keys[j]
                );
            }
        }
    }

    /// Golden Test #4: Multiple Sec-WebSocket-Protocol negotiation per RFC 6455 Section 4.2.2
    #[test]
    fn golden_multiple_sec_websocket_protocol_negotiation() {
        // Test comprehensive protocol negotiation scenarios

        // Test case 1: Server supports multiple protocols, client requests multiple
        let server = ServerHandshake::new()
            .protocol("chat")
            .protocol("superchat")
            .protocol("echo");

        // Client requests multiple protocols in preference order
        let request_data = "GET /test HTTP/1.1\r\n\
            Host: localhost\r\n\
            Upgrade: websocket\r\n\
            Connection: Upgrade\r\n\
            Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\
            Sec-WebSocket-Version: 13\r\n\
            Sec-WebSocket-Protocol: superchat, chat, echo\r\n\r\n";

        let request = HttpRequest::parse(request_data.as_bytes())
            .expect("Multiple protocol request should parse");

        let accept = server
            .accept(&request)
            .expect("Multiple protocol negotiation should succeed");

        // Server should select first matching protocol from client list
        assert_eq!(
            accept.protocol,
            Some("superchat".to_string()),
            "Should select first matching protocol from client preference order"
        );

        // Test case 2: Client requests protocols server doesn't support
        let server_limited = ServerHandshake::new().protocol("private-protocol");

        let request_data = "GET /test HTTP/1.1\r\n\
            Host: localhost\r\n\
            Upgrade: websocket\r\n\
            Connection: Upgrade\r\n\
            Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\
            Sec-WebSocket-Version: 13\r\n\
            Sec-WebSocket-Protocol: chat, superchat, echo\r\n\r\n";

        let request = HttpRequest::parse(request_data.as_bytes())
            .expect("Unsupported protocol request should parse");

        let result = server_limited.accept(&request);
        assert!(result.is_err(), "Should reject when no protocols match");

        if let Err(error) = result {
            assert!(
                matches!(error, HandshakeError::ProtocolMismatch { .. }),
                "Should fail with ProtocolMismatch error: {:?}",
                error
            );
        }

        // Test case 3: Single protocol negotiation
        let server_single = ServerHandshake::new().protocol("websocket-chat");

        let request_data = "GET /test HTTP/1.1\r\n\
            Host: localhost\r\n\
            Upgrade: websocket\r\n\
            Connection: Upgrade\r\n\
            Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\
            Sec-WebSocket-Version: 13\r\n\
            Sec-WebSocket-Protocol: websocket-chat\r\n\r\n";

        let request = HttpRequest::parse(request_data.as_bytes())
            .expect("Single protocol request should parse");

        let accept = server_single
            .accept(&request)
            .expect("Single protocol negotiation should succeed");

        assert_eq!(
            accept.protocol,
            Some("websocket-chat".to_string()),
            "Should accept exact protocol match"
        );

        // Test case 4: No protocol requested, server has protocols
        let request_data = "GET /test HTTP/1.1\r\n\
            Host: localhost\r\n\
            Upgrade: websocket\r\n\
            Connection: Upgrade\r\n\
            Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\
            Sec-WebSocket-Version: 13\r\n\r\n";

        let request =
            HttpRequest::parse(request_data.as_bytes()).expect("No protocol request should parse");

        let accept = server
            .accept(&request)
            .expect("Should accept connection without protocol when client doesn't request any");

        assert_eq!(
            accept.protocol, None,
            "Should not select protocol when client doesn't request any"
        );

        // Test case 5: Protocol list parsing edge cases.
        // In each case the server (below) only supports "chat", so the
        // negotiated protocol must be "chat" whenever the client offers it.
        let protocol_test_cases = vec![
            ("chat", "chat"),
            ("chat, superchat", "chat"),         // First in list
            ("  chat  ,  superchat  ", "chat"),  // Whitespace handling
            ("superchat,chat,echo", "chat"),     // No spaces (server only supports "chat")
            ("unknown, chat, unknown2", "chat"), // Mixed known/unknown
        ];

        let server_chat = ServerHandshake::new().protocol("chat");

        for (protocol_header, expected) in protocol_test_cases {
            let request_data = format!(
                "GET /test HTTP/1.1\r\n\
                 Host: localhost\r\n\
                 Upgrade: websocket\r\n\
                 Connection: Upgrade\r\n\
                 Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\
                 Sec-WebSocket-Version: 13\r\n\
                 Sec-WebSocket-Protocol: {}\r\n\r\n",
                protocol_header
            );

            let request = HttpRequest::parse(request_data.as_bytes()).expect(&format!(
                "Protocol header '{}' should parse",
                protocol_header
            ));

            let accept = server_chat.accept(&request).expect(&format!(
                "Protocol negotiation should succeed for '{}'",
                protocol_header
            ));

            assert_eq!(
                accept.protocol,
                Some(expected.to_string()),
                "Protocol header '{}' should select '{}'",
                protocol_header,
                expected
            );
        }

        // Test case 6: Case sensitivity (protocols are case-sensitive per RFC)
        let server_case = ServerHandshake::new().protocol("Chat");

        let request_data = "GET /test HTTP/1.1\r\n\
            Host: localhost\r\n\
            Upgrade: websocket\r\n\
            Connection: Upgrade\r\n\
            Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\
            Sec-WebSocket-Version: 13\r\n\
            Sec-WebSocket-Protocol: chat\r\n\r\n"; // lowercase

        let request =
            HttpRequest::parse(request_data.as_bytes()).expect("Case test request should parse");

        let result = server_case.accept(&request);
        assert!(
            result.is_err(),
            "Protocol matching should be case-sensitive: 'Chat' != 'chat'"
        );
    }

    /// Golden Test #5: RFC 6455 compliant status codes and error conditions
    #[test]
    fn golden_rfc6455_compliant_status_codes() {
        // Test comprehensive status code compliance per RFC 6455

        // Test case 1: Successful handshake returns 101 Switching Protocols
        let server = ServerHandshake::new();
        let valid_request_data = "GET /test HTTP/1.1\r\n\
            Host: localhost\r\n\
            Upgrade: websocket\r\n\
            Connection: Upgrade\r\n\
            Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\
            Sec-WebSocket-Version: 13\r\n\r\n";

        let request =
            HttpRequest::parse(valid_request_data.as_bytes()).expect("Valid request should parse");

        let accept = server
            .accept(&request)
            .expect("Valid request should be accepted");

        let response_bytes = accept.response_bytes();
        let response_str = String::from_utf8_lossy(&response_bytes);

        // Verify 101 status code in response
        assert!(
            response_str.starts_with("HTTP/1.1 101 Switching Protocols"),
            "Successful handshake should return 101 Switching Protocols"
        );

        // Test case 2: Missing required headers trigger appropriate errors
        let missing_header_tests = vec![
            // (request_data, expected_error_type, description)
            (
                "GET /test HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\n\r\n",
                "MissingHeader",
                "Missing Connection header",
            ),
            (
                "GET /test HTTP/1.1\r\nHost: localhost\r\nConnection: Upgrade\r\n\r\n",
                "MissingHeader",
                "Missing Upgrade header",
            ),
            (
                "GET /test HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n",
                "MissingHeader",
                "Missing Sec-WebSocket-Key header",
            ),
            (
                "GET /test HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n",
                "MissingHeader",
                "Missing Sec-WebSocket-Version header",
            ),
        ];

        for (request_data, expected_error, description) in missing_header_tests {
            let request = HttpRequest::parse(request_data.as_bytes())
                .expect(&format!("Request should parse: {}", description));

            let result = server.accept(&request);
            assert!(result.is_err(), "Should reject request: {}", description);

            let error = result.unwrap_err();
            let error_str = format!("{:?}", error);
            assert!(
                error_str.contains(expected_error),
                "Should fail with {}: {} - got {:?}",
                expected_error,
                description,
                error
            );
        }

        // Test case 3: Invalid WebSocket version
        let invalid_version_data = "GET /test HTTP/1.1\r\n\
            Host: localhost\r\n\
            Upgrade: websocket\r\n\
            Connection: Upgrade\r\n\
            Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\
            Sec-WebSocket-Version: 12\r\n\r\n"; // Wrong version

        let request = HttpRequest::parse(invalid_version_data.as_bytes())
            .expect("Invalid version request should parse");

        let result = server.accept(&request);
        assert!(result.is_err(), "Should reject invalid WebSocket version");

        if let Err(error) = result {
            assert!(
                matches!(error, HandshakeError::UnsupportedVersion(_)),
                "Should fail with UnsupportedVersion error: {:?}",
                error
            );
        }

        // Test case 4: Client validation of server response status codes
        let handshake = ClientHandshake {
            url: crate::net::websocket::handshake::WsUrl::parse("ws://example.com/test").unwrap(),
            key: "dGhlIHNhbXBsZSBub25jZQ==".to_string(),
            protocols: vec![],
            extensions: vec![],
            headers: std::collections::BTreeMap::new(),
        };

        // Test various invalid status codes
        let invalid_status_tests = vec![
            (200, "200 OK"),
            (400, "400 Bad Request"),
            (404, "404 Not Found"),
            (426, "426 Upgrade Required"),
            (500, "500 Internal Server Error"),
        ];

        for (status_code, status_text) in invalid_status_tests {
            let response_data = format!(
                "HTTP/1.1 {} {}\r\n\
                 Upgrade: websocket\r\n\
                 Connection: Upgrade\r\n\
                 Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\r\n",
                status_code, status_text
            );

            let response = HttpResponse::parse(response_data.as_bytes()).expect(&format!(
                "Response with status {} should parse",
                status_code
            ));

            let result = handshake.validate_response(&response);
            assert!(
                result.is_err(),
                "Should reject response with status code {}",
                status_code
            );

            if let Err(error) = result {
                assert!(
                    matches!(error, HandshakeError::NotSwitchingProtocols(_)),
                    "Should fail with NotSwitchingProtocols for status {}: {:?}",
                    status_code,
                    error
                );
            }
        }

        // Test case 5: Verify complete successful response format.
        // Re-parse the valid request so we don't accidentally reuse the
        // unsupported-version request bound above.
        let valid_request_for_response = HttpRequest::parse(valid_request_data.as_bytes())
            .expect("Valid request should parse");
        let accept = server
            .accept(&valid_request_for_response)
            .expect("Valid request should be accepted");
        let response_bytes = accept.response_bytes();
        let response_str = String::from_utf8_lossy(&response_bytes);

        // Check all required response headers are present
        assert!(
            response_str.contains("Upgrade: websocket"),
            "Response should contain Upgrade header"
        );
        assert!(
            response_str.contains("Connection: Upgrade"),
            "Response should contain Connection header"
        );
        assert!(
            response_str.contains("Sec-WebSocket-Accept: "),
            "Response should contain Sec-WebSocket-Accept header"
        );

        // Verify response ends with CRLF CRLF
        assert!(
            response_str.ends_with("\r\n\r\n"),
            "Response should end with CRLF CRLF"
        );

        // Verify no extra headers are added by default
        let line_count = response_str.lines().count();
        assert!(
            line_count <= 6,
            "Response should not have extra headers: {}",
            response_str
        );

        // Test case 6: Malformed request handling
        let malformed_requests: Vec<&[u8]> = vec![
            b"NOT HTTP\r\n\r\n",
            b"GET /test\r\n\r\n",          // Missing HTTP version
            b"GET /test HTTP/1.0\r\n\r\n", // Wrong HTTP version should still work
            b"",
        ];

        for (i, malformed) in malformed_requests.iter().enumerate() {
            let result = HttpRequest::parse(malformed);
            if i < 3 {
                // Some malformed requests might still parse but should fail validation
                if let Ok(request) = result {
                    let server_result = server.accept(&request);
                    // Should either fail to parse or fail validation
                    assert!(
                        server_result.is_err(),
                        "Malformed request {} should be rejected",
                        i
                    );
                }
            } else {
                // Completely empty request should fail to parse
                assert!(result.is_err(), "Empty request should fail to parse");
            }
        }
    }

    /// Additional Golden Test: Comprehensive end-to-end handshake validation
    #[test]
    fn golden_end_to_end_handshake_validation() {
        // Test complete handshake flow with all components

        let entropy = crate::util::entropy::DetEntropy::new(12345);
        let client = ClientHandshake::new("ws://localhost:8080/socket", &entropy)
            .expect("Client handshake should initialize")
            .protocol("chat")
            .protocol("echo")
            .extension("permessage-deflate");

        let server = ServerHandshake::new()
            .protocol("echo")
            .protocol("chat") // Different order than client
            .extension("permessage-deflate");

        // Generate client request
        let request_bytes = client.request_bytes();
        let request_str = String::from_utf8_lossy(&request_bytes);

        // Verify client request format
        assert!(request_str.contains("GET /socket HTTP/1.1"));
        assert!(request_str.contains("Host: localhost:8080"));
        assert!(request_str.contains("Upgrade: websocket"));
        assert!(request_str.contains("Connection: Upgrade"));
        assert!(request_str.contains("Sec-WebSocket-Key: "));
        assert!(request_str.contains("Sec-WebSocket-Version: 13"));
        assert!(request_str.contains("Sec-WebSocket-Protocol: chat, echo"));

        // Parse and validate on server side
        let request =
            HttpRequest::parse(&request_bytes).expect("Client request should parse on server");

        let accept = server
            .accept(&request)
            .expect("Server should accept valid client request");

        // Verify protocol negotiation (server should pick first match from client list)
        assert_eq!(
            accept.protocol,
            Some("chat".to_string()),
            "Server should select first client protocol it supports"
        );

        // Generate server response
        let response_bytes = accept.response_bytes();
        let response_str = String::from_utf8_lossy(&response_bytes);

        // Verify server response format
        assert!(response_str.contains("HTTP/1.1 101 Switching Protocols"));
        assert!(response_str.contains(&format!("Sec-WebSocket-Accept: {}", accept.accept_key)));
        assert!(response_str.contains("Sec-WebSocket-Protocol: chat"));

        // Validate response on client side
        let response =
            HttpResponse::parse(&response_bytes).expect("Server response should parse on client");

        let validation_result = client.validate_response(&response);
        assert!(
            validation_result.is_ok(),
            "Client should validate server response: {:?}",
            validation_result.unwrap_err()
        );

        // Verify key computation is correct
        let expected_accept = compute_accept_key(&client.key);
        assert_eq!(
            accept.accept_key, expected_accept,
            "Server accept key should match computed value"
        );

        // Test extension negotiation
        if !accept.extensions.is_empty() {
            assert!(
                response_str.contains("Sec-WebSocket-Extensions:"),
                "Response should include extension header when extensions are negotiated"
            );
        }
    }
}