rustf 1.0.0

A simple MVC web framework inspired by Total.js
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
use crate::error::{Error, Result};
use crate::http::files::{FileCollection, MultipartParser};
use http_body_util::BodyExt;
use hyper::Request as HyperRequest;
use ipnetwork::IpNetwork;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use simd_json;
use std::collections::HashMap;
use std::net::{IpAddr, SocketAddr};
use std::path::Path;
use std::sync::Arc;
use url::Url;

/// Represents form data that can be either a single value or an array of values
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum FormValue {
    Single(String),
    Multiple(Vec<String>),
}

impl FormValue {
    /// Get as a single value (returns first element if array)
    pub fn as_string(&self) -> &str {
        match self {
            FormValue::Single(s) => s,
            FormValue::Multiple(v) => v.first().map(|s| s.as_str()).unwrap_or(""),
        }
    }

    /// Get as array (wraps single value in array if needed)
    pub fn as_array(&self) -> Vec<&str> {
        match self {
            FormValue::Single(s) => vec![s.as_str()],
            FormValue::Multiple(v) => v.iter().map(|s| s.as_str()).collect(),
        }
    }

    /// Check if this is an array value
    pub fn is_array(&self) -> bool {
        matches!(self, FormValue::Multiple(_))
    }
}

/// Parsed form data with typed getters (e.g. `get_int`, `get_str`).
///
/// Returned by [`Context::body_form`](crate::Context::body_form).
///
/// Multi-value fields — repeated checkboxes, `tags[]` — keep every value.
/// [`get`](Self::get) returns the first, [`get_all`](Self::get_all) returns
/// them all. Prefer the typed getters (`get_int`, `get_bool`, `get_as::<T>`)
/// over parsing strings by hand.
#[derive(Debug, Clone, Default, Serialize)]
#[serde(transparent)]
pub struct FormData(HashMap<String, FormValue>);

impl FormData {
    /// Create from a parsed form map (used by `Context::body_form`).
    pub fn new(map: HashMap<String, FormValue>) -> Self {
        Self(map)
    }

    /// First value submitted for `key`, or `None` if the field is absent.
    pub fn get(&self, key: &str) -> Option<&str> {
        self.0.get(key).map(FormValue::as_string)
    }

    /// Every value submitted for `key`; empty if the field is absent.
    ///
    /// A field submitted once yields a one-element vector, so a `tags[]` group
    /// with a single box ticked behaves like one with several.
    pub fn get_all(&self, key: &str) -> Vec<&str> {
        self.0.get(key).map(FormValue::as_array).unwrap_or_default()
    }

    /// The raw entry for `key`, single or multiple.
    pub fn get_value(&self, key: &str) -> Option<&FormValue> {
        self.0.get(key)
    }

    /// Whether the field was submitted at all (even empty).
    pub fn contains_key(&self, key: &str) -> bool {
        self.0.contains_key(key)
    }

    /// Number of distinct fields submitted.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Whether no fields were submitted.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Iterate over the submitted field names.
    pub fn keys(&self) -> impl Iterator<Item = &str> {
        self.0.keys().map(|k| k.as_str())
    }

    /// Iterate over the submitted fields and their raw values.
    pub fn iter(&self) -> impl Iterator<Item = (&str, &FormValue)> {
        self.0.iter().map(|(k, v)| (k.as_str(), v))
    }

    /// Consume the wrapper and return the underlying map.
    pub fn into_inner(self) -> HashMap<String, FormValue> {
        self.0
    }

    /// Get a required string field (errors if missing or empty).
    pub fn get_str(&self, key: &str) -> Result<String> {
        self.get(key)
            .filter(|s| !s.is_empty())
            .map(|s| s.to_string())
            .ok_or_else(|| Error::InvalidInput(format!("Field '{}' is required", key)))
    }

    /// Get a required integer field (errors if missing or invalid).
    pub fn get_int(&self, key: &str) -> Result<i32> {
        self.get_as(key)
    }

    /// Get a required boolean field (errors if missing). Accepts "true", "1", "yes", "on", "checked".
    pub fn get_bool(&self, key: &str) -> Result<bool> {
        let value = self.get_str(key)?;
        Ok(matches!(
            value.as_str(),
            "true" | "1" | "yes" | "on" | "checked"
        ))
    }

    /// Get a required field parsed into any `FromStr` type.
    ///
    /// Covers `f64`, `u64`, `Uuid`, `NaiveDate`, `Decimal`, `IpAddr` and the
    /// rest, so no call site needs a hand-written `.parse()` chain.
    pub fn get_as<T: std::str::FromStr>(&self, key: &str) -> Result<T> {
        let value = self.get_str(key)?;
        value.trim().parse::<T>().map_err(|_| {
            Error::InvalidInput(format!(
                "Field '{}' must be a valid {}",
                key,
                short_type_name::<T>()
            ))
        })
    }

    /// Get a string field, or a default if missing or empty.
    pub fn get_str_or(&self, key: &str, default: &str) -> String {
        self.get_str(key).unwrap_or_else(|_| default.to_string())
    }

    /// Get an integer field, or a default if missing or invalid.
    pub fn get_int_or(&self, key: &str, default: i32) -> i32 {
        self.get_int(key).unwrap_or(default)
    }

    /// Get a boolean field, or a default if missing. Accepts "true", "1", "yes", "on", "checked".
    pub fn get_bool_or(&self, key: &str, default: bool) -> bool {
        self.get_bool(key).unwrap_or(default)
    }

    /// Get a field parsed into any `FromStr` type, or a default if missing or invalid.
    pub fn get_as_or<T: std::str::FromStr>(&self, key: &str, default: T) -> T {
        self.get_as(key).unwrap_or(default)
    }

    /// Get every value for a multi-value field, each parsed into `T`.
    ///
    /// Errors on the first value that does not parse, naming the field.
    pub fn get_all_as<T: std::str::FromStr>(&self, key: &str) -> Result<Vec<T>> {
        self.get_all(key)
            .into_iter()
            .map(|value| {
                value.trim().parse::<T>().map_err(|_| {
                    Error::InvalidInput(format!(
                        "Field '{}' must contain only valid {} values",
                        key,
                        short_type_name::<T>()
                    ))
                })
            })
            .collect()
    }
}

/// Type name without its module path, for error messages an end user reads.
///
/// `std::any::type_name::<NaiveDate>()` yields `chrono::naive::date::NaiveDate`;
/// only the last segment is useful in a validation message.
pub(crate) fn short_type_name<T: ?Sized>() -> &'static str {
    let full = std::any::type_name::<T>();
    full.rsplit("::").next().unwrap_or(full)
}

/// Does this header set describe a WebSocket handshake?
///
/// RFC 6455 §4.2.1: a handshake is a `GET` carrying `Upgrade: websocket` and
/// `Connection: Upgrade`. Both header values are token lists, so
/// `Connection: keep-alive, Upgrade` — which several proxies emit — has to
/// count, and tokens are compared case-insensitively.
///
/// Deliberately *not* checked here: `Sec-WebSocket-Key` and
/// `Sec-WebSocket-Version`. This predicate only answers "is an upgrade being
/// attempted", so that a malformed handshake still reaches the socket route
/// and gets a descriptive `400` from handshake validation instead of a
/// misleading `426`.
///
/// `headers` must be keyed by lowercase header name, which is how
/// `from_hyper_with_connection` builds the map (hyper normalises names).
fn is_websocket_upgrade_headers(method: &str, headers: &HashMap<String, String>) -> bool {
    if !method.eq_ignore_ascii_case("GET") {
        return false;
    }

    let has_token = |name: &str, token: &str| {
        headers
            .get(name)
            .map(|value| {
                value
                    .split(',')
                    .any(|part| part.trim().eq_ignore_ascii_case(token))
            })
            .unwrap_or(false)
    };

    has_token("upgrade", "websocket") && has_token("connection", "upgrade")
}

pub struct Request {
    pub method: String,
    pub uri: String,
    pub headers: HashMap<String, String>,
    pub params: HashMap<String, String>,
    pub query: HashMap<String, String>,
    body_bytes: Vec<u8>,
    files: Option<FileCollection>,
    /// Cached multipart form data (parsed alongside files)
    multipart_form_data: Option<HashMap<String, String>>,
    /// Lazily-populated cache of the parsed `Cookie` header.
    ///
    /// Session, CSRF, and flash-message middleware all read cookies from the
    /// same request; without this cache each would re-tokenise the header
    /// and allocate a fresh `HashMap`.
    cookies_cache: once_cell::sync::OnceCell<HashMap<String, String>>,
    peer_addr: Option<SocketAddr>,
    trusted_proxies: Arc<Vec<IpNetwork>>,
    /// Pending HTTP upgrade handle, taken from the hyper request during
    /// construction when — and only when — the request is a WebSocket
    /// handshake.
    ///
    /// hyper stores this as a request extension that dies with the hyper
    /// request, so it has to be moved out *before* `into_body()` consumes it.
    /// `None` for every ordinary request, and for requests built by tests or
    /// benches (no server connection behind them, so nothing to upgrade).
    upgrade: Option<hyper::upgrade::OnUpgrade>,
    /// A singleton WebSocket handshake header arrived more than once.
    ///
    /// `headers` is a map, so the second value silently overwrites the first
    /// and the duplication becomes invisible. For `Origin` in particular that
    /// is a security problem — a proxy and this server could each act on a
    /// different value — so the fact is recorded here and the handshake is
    /// refused. Meaningless for non-handshake requests, which never read it.
    duplicate_handshake_header: bool,
}

impl Default for Request {
    fn default() -> Self {
        Self {
            method: String::new(),
            uri: String::new(),
            headers: HashMap::new(),
            params: HashMap::new(),
            query: HashMap::new(),
            body_bytes: Vec::new(),
            files: None,
            multipart_form_data: None,
            cookies_cache: once_cell::sync::OnceCell::new(),
            peer_addr: None,
            trusted_proxies: Arc::new(Vec::new()),
            upgrade: None,
            duplicate_handshake_header: false,
        }
    }
}

impl Request {
    /// Create a new Request for testing purposes
    /// This is only intended for testing and should not be used in production code
    #[doc(hidden)]
    pub fn new(method: &str, uri: &str, _version: &str) -> Self {
        Request {
            method: method.to_string(),
            uri: uri.to_string(),
            headers: HashMap::new(),
            params: HashMap::new(),
            query: HashMap::new(),
            body_bytes: Vec::new(),
            files: None,
            multipart_form_data: None,
            cookies_cache: once_cell::sync::OnceCell::new(),
            peer_addr: None,
            trusted_proxies: Arc::new(Vec::new()),
            upgrade: None,
            duplicate_handshake_header: false,
        }
    }

    /// Set body for testing purposes
    #[doc(hidden)]
    #[cfg(test)]
    pub fn set_body(&mut self, body: Vec<u8>) {
        self.body_bytes = body;
    }

    /// Build a `Request` from any hyper body. Production passes
    /// `hyper::body::Incoming` (network); tests/benches pass an in-memory body
    /// like `http_body_util::Full<Bytes>` — both collect the same way.
    pub async fn from_hyper<B>(req: HyperRequest<B>) -> Result<Self>
    where
        B: hyper::body::Body,
        B::Error: std::fmt::Display,
    {
        Self::from_hyper_with_connection(req, None, Arc::new(Vec::new())).await
    }

    /// Build a `Request` from Hyper plus connection metadata.
    pub async fn from_hyper_with_connection<B>(
        mut req: HyperRequest<B>,
        peer_addr: Option<SocketAddr>,
        trusted_proxies: Arc<Vec<IpNetwork>>,
    ) -> Result<Self>
    where
        B: hyper::body::Body,
        B::Error: std::fmt::Display,
    {
        let method = req.method().to_string();
        let uri = req.uri().to_string();

        // Extract headers. A repeated header collapses into one entry here, so
        // note it for the three handshake fields RFC 6455 allows exactly one
        // of — `validate` refuses the handshake rather than acting on whichever
        // value happened to win.
        const SINGLETON_HANDSHAKE_HEADERS: [&str; 3] =
            ["origin", "sec-websocket-key", "sec-websocket-version"];
        // Comma-list fields that a proxy or client may legitimately split
        // across several lines. Joining them keeps the value RFC 7230 says it
        // is; overwriting would turn `Connection: Upgrade` plus
        // `Connection: keep-alive` into a failed upgrade.
        const LIST_HANDSHAKE_HEADERS: [&str; 3] = [
            "connection",
            "sec-websocket-protocol",
            "sec-websocket-extensions",
        ];

        let mut headers = HashMap::new();
        let mut duplicate_handshake_header = false;
        for (name, value) in req.headers() {
            if let Ok(value_str) = value.to_str() {
                let name = name.to_string();

                if LIST_HANDSHAKE_HEADERS.contains(&name.as_str()) {
                    headers
                        .entry(name)
                        .and_modify(|existing: &mut String| {
                            existing.push_str(", ");
                            existing.push_str(value_str);
                        })
                        .or_insert_with(|| value_str.to_string());
                    continue;
                }

                let previous = headers.insert(name.clone(), value_str.to_string());
                if previous.is_some() && SINGLETON_HANDSHAKE_HEADERS.contains(&name.as_str()) {
                    duplicate_handshake_header = true;
                }
            }
        }

        // Extract query parameters
        let query = Self::parse_query(req.uri().query().unwrap_or(""));

        let content_length = req
            .headers()
            .get("content-length")
            .and_then(|value| value.to_str().ok())
            .and_then(|value| value.parse::<u64>().ok())
            .unwrap_or(0);
        let has_transfer_encoding = req.headers().contains_key("transfer-encoding");

        // Take the pending upgrade *before* `into_body()` drops the hyper
        // request and the extension with it. Only for real WebSocket
        // handshakes: `hyper::upgrade::on` removes the extension, and calling
        // it on an ordinary request would hand back a handle that can never
        // resolve. Handshakes carry no body, so `has_body` below is false and
        // nothing is read from a connection that is about to be upgraded.
        // The extension check matters: `hyper::upgrade::on` falls back to a
        // handle that never resolves when no upgrade is pending, so taking it
        // unconditionally would make `has_upgrade()` lie. hyper only inserts
        // the extension on HTTP/1.1 connections, which is also exactly where
        // WebSocket is supported — an h2 handshake therefore lands with
        // `upgrade: None` and is refused with a clear error instead of hanging.
        let upgrade = if is_websocket_upgrade_headers(&method, &headers)
            && req
                .extensions()
                .get::<hyper::upgrade::OnUpgrade>()
                .is_some()
        {
            Some(hyper::upgrade::on(&mut req))
        } else {
            None
        };

        let body_hint = req.body().size_hint();
        let has_body = content_length > 0 || has_transfer_encoding || body_hint.lower() > 0;

        // Read body (hyper 1.x: collect the body into bytes). Generic over the
        // body type, so map its error into our own rather than relying on the
        // `From<hyper::Error>` impl (which only covers `Incoming`).
        let body_bytes = if has_body {
            req.into_body()
                .collect()
                .await
                .map_err(|e| Error::Internal(format!("failed to read request body: {e}")))?
                .to_bytes()
                .to_vec()
        } else {
            Vec::new()
        };

        Ok(Request {
            method,
            uri,
            headers,
            params: HashMap::new(), // Will be filled by router
            query,
            body_bytes,
            files: None,               // Will be parsed on demand
            multipart_form_data: None, // Will be parsed on demand
            cookies_cache: once_cell::sync::OnceCell::new(),
            peer_addr,
            trusted_proxies,
            upgrade,
            duplicate_handshake_header,
        })
    }

    pub fn body_as_json<T: DeserializeOwned>(&self) -> Result<T> {
        // Use simd-json for faster parsing (2-3x faster than serde_json)
        let mut body_bytes = self.body_bytes.clone();
        simd_json::from_slice(&mut body_bytes)
            // The client sent the body, so a body that does not parse is its
            // mistake (400). The parser's diagnostic can name fields and enum
            // variants of the server-side type, so it goes to the log only.
            .map_err(|e| {
                log::debug!("Rejected JSON body: {}", e);
                Error::InvalidInput("Invalid JSON body".to_string())
            })
    }

    /// Parse request body as form (application/x-www-form-urlencoded or multipart/form-data).
    /// For multipart requests, parses on first call and uses cached fields so fields like `oldid` are present.
    /// Parse form data with support for arrays (field[] syntax)
    pub fn body_as_form_data(&mut self) -> Result<HashMap<String, FormValue>> {
        if let Some(ref form) = self.multipart_form_data {
            return Ok(form
                .iter()
                .map(|(key, value)| (key.clone(), FormValue::Single(value.clone())))
                .collect());
        }

        if self
            .headers
            .get("content-type")
            .map(|v| v.starts_with("multipart/form-data"))
            == Some(true)
        {
            self.parse_files()?;
            if let Some(ref form) = self.multipart_form_data {
                return Ok(form
                    .iter()
                    .map(|(key, value)| (key.clone(), FormValue::Single(value.clone())))
                    .collect());
            }
        }

        // Optimize: Check if body is valid UTF-8 to avoid unnecessary allocation
        let body_str = match std::str::from_utf8(&self.body_bytes) {
            Ok(s) => s,
            Err(_) => {
                return Ok(Self::parse_query_with_arrays(&String::from_utf8_lossy(
                    &self.body_bytes,
                )))
            }
        };
        Ok(Self::parse_query_with_arrays(body_str))
    }

    pub fn body_as_string(&self) -> String {
        String::from_utf8_lossy(&self.body_bytes).to_string()
    }

    fn parse_query(query: &str) -> HashMap<String, String> {
        let mut result = HashMap::new();
        for pair in query.split('&') {
            if pair.is_empty() {
                continue;
            }

            let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
            if key.is_empty() {
                continue;
            }

            if let (Some(decoded_key), Some(decoded_value)) =
                (urlencoding::decode(key), urlencoding::decode(value))
            {
                if !decoded_key.is_empty() {
                    result.insert(decoded_key.to_string(), decoded_value.to_string());
                }
            }
        }
        result
    }

    /// Parse query/form data with support for arrays
    /// Optimized single-pass parsing to avoid double iteration
    fn parse_query_with_arrays(query: &str) -> HashMap<String, FormValue> {
        let mut result: HashMap<String, FormValue> = HashMap::new();

        for pair in query.split('&') {
            if pair.is_empty() {
                continue;
            }

            let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
            if key.is_empty() {
                continue;
            }

            // Use safe decoding that filters malicious input
            if let (Some(decoded_key), Some(decoded_value)) =
                (urlencoding::decode(key), urlencoding::decode(value))
            {
                if decoded_key.is_empty() {
                    continue;
                }

                // Check if key ends with [] (array notation) and extract actual key
                let (actual_key, is_array) = if decoded_key.ends_with("[]") {
                    let key_len = decoded_key.len();
                    (decoded_key[..key_len - 2].to_string(), true)
                } else {
                    (decoded_key.to_string(), false)
                };

                if actual_key.is_empty() {
                    continue;
                }

                // Single-pass: directly create FormValue instead of intermediate Vec
                let decoded_value_str = decoded_value.to_string();

                match result.entry(actual_key) {
                    std::collections::hash_map::Entry::Vacant(e) => {
                        if is_array {
                            // Array notation - always create Multiple even for first value
                            e.insert(FormValue::Multiple(vec![decoded_value_str]));
                        } else {
                            // Single value
                            e.insert(FormValue::Single(decoded_value_str));
                        }
                    }
                    std::collections::hash_map::Entry::Occupied(mut e) => {
                        // Key already exists - convert to array if needed
                        match e.get_mut() {
                            FormValue::Single(existing) => {
                                // Convert single to multiple
                                let existing_value = std::mem::take(existing);
                                *e.get_mut() =
                                    FormValue::Multiple(vec![existing_value, decoded_value_str]);
                            }
                            FormValue::Multiple(vec) => {
                                // Add to existing array
                                vec.push(decoded_value_str);
                            }
                        }
                    }
                }
            }
            // Skip pairs with invalid encoding
        }

        result
    }

    // Client information helper methods

    /// Get client IP address (supports X-Forwarded-For and X-Real-IP)
    pub fn client_ip(&self) -> String {
        if self.should_trust_forwarded_headers() {
            if let Some(forwarded) = self.headers.get("x-forwarded-for") {
                let forwarded_ips: Vec<IpAddr> = forwarded
                    .split(',')
                    .filter_map(|ip| ip.trim().parse::<IpAddr>().ok())
                    .collect();
                if !forwarded_ips.is_empty() {
                    if let Some(ip) = forwarded_ips
                        .iter()
                        .rev()
                        .find(|ip| !self.is_trusted_proxy_ip(**ip))
                    {
                        return ip.to_string();
                    }

                    return forwarded_ips[0].to_string();
                }
            }

            if let Some(real_ip) = self.headers.get("x-real-ip") {
                if let Ok(real_ip) = real_ip.parse::<IpAddr>() {
                    return real_ip.to_string();
                }
            }
        }

        self.peer_addr
            .map(|addr| addr.ip().to_string())
            .unwrap_or_else(|| "127.0.0.1".to_string())
    }

    /// Get user agent string
    pub fn user_agent(&self) -> Option<&str> {
        self.headers.get("user-agent").map(|s| s.as_str())
    }

    /// Detect if request is from mobile device
    pub fn is_mobile(&self) -> bool {
        if let Some(ua) = self.user_agent() {
            let ua_lower = ua.to_lowercase();
            ua_lower.contains("mobile")
                || ua_lower.contains("android")
                || ua_lower.contains("iphone")
                || ua_lower.contains("ipad")
                || ua_lower.contains("blackberry")
                || ua_lower.contains("windows phone")
        } else {
            false
        }
    }

    /// Detect if request is from a bot/crawler
    pub fn is_robot(&self) -> bool {
        if let Some(ua) = self.user_agent() {
            let ua_lower = ua.to_lowercase();
            ua_lower.contains("bot")
                || ua_lower.contains("crawler")
                || ua_lower.contains("spider")
                || ua_lower.contains("scraper")
                || ua_lower.contains("googlebot")
                || ua_lower.contains("bingbot")
                || ua_lower.contains("facebookexternalhit")
                || ua_lower.contains("twitterbot")
        } else {
            false
        }
    }

    /// Check if request is HTTPS (via X-Forwarded-Proto or URI scheme)
    pub fn is_secure(&self) -> bool {
        if self.should_trust_forwarded_headers() {
            if let Some(proto) = self.headers.get("x-forwarded-proto") {
                return proto
                    .split(',')
                    .next()
                    .map(|value| value.trim().eq_ignore_ascii_case("https"))
                    .unwrap_or(false);
            }
        }

        // Check URI scheme
        self.uri.starts_with("https://")
    }

    /// Is this request a WebSocket handshake?
    ///
    /// True when the request is a `GET` with `Upgrade: websocket` and
    /// `Connection: Upgrade`. Says nothing about whether the handshake is
    /// *valid* — `Sec-WebSocket-Key` and `Sec-WebSocket-Version` are checked
    /// later, so that a broken handshake gets a `400` explaining what is wrong
    /// rather than a `426` telling it to do what it already tried to do.
    pub fn is_websocket_upgrade(&self) -> bool {
        is_websocket_upgrade_headers(&self.method, &self.headers)
    }

    /// Did a singleton WebSocket handshake header arrive more than once?
    ///
    /// See [`Request::is_websocket_upgrade`]; a handshake for which this is
    /// true is refused with `400`.
    pub fn has_duplicate_handshake_header(&self) -> bool {
        self.duplicate_handshake_header
    }

    /// Take the pending upgrade handle, leaving `None` behind.
    ///
    /// `Some` only for a WebSocket handshake that arrived over a real server
    /// connection. Requests built by hand (`Request::new`, benches, unit
    /// tests) always yield `None`, as do handshakes that hyper could not
    /// upgrade. Consumed once, by the task that performs the upgrade.
    pub(crate) fn take_upgrade(&mut self) -> Option<hyper::upgrade::OnUpgrade> {
        self.upgrade.take()
    }

    /// Is an upgrade handle still available on this request?
    ///
    /// Distinct from [`Request::is_websocket_upgrade`], which only reads
    /// headers: this reports whether the connection can actually be upgraded.
    /// Test-only — production code takes the handle rather than asking.
    #[cfg(test)]
    pub(crate) fn has_upgrade(&self) -> bool {
        self.upgrade.is_some()
    }

    /// Check if request is AJAX/XHR (supports traditional XHR and htmx)
    pub fn is_xhr(&self) -> bool {
        // Check for traditional XHR header (jQuery, Axios, etc.)
        if let Some(xhr_header) = self.headers.get("x-requested-with") {
            if xhr_header.to_lowercase() == "xmlhttprequest" {
                return true;
            }
        }

        // Check for htmx request header
        if let Some(hx_request) = self.headers.get("hx-request") {
            if hx_request.to_lowercase() == "true" {
                return true;
            }
        }

        false
    }

    /// Whether the client would rather have JSON than HTML.
    ///
    /// True when the `Accept` header ranks a JSON type (`application/json` or
    /// any `+json` such as `application/problem+json`) at least as high as
    /// `text/html`. When `Accept` names neither (`*/*`, or no header at all),
    /// a classic XHR (`X-Requested-With: XMLHttpRequest`) still counts as a
    /// JSON request; anything else gets plain text, the safer default for a
    /// curl or a health probe. htmx is deliberately not treated as JSON.
    pub fn wants_json(&self) -> bool {
        // htmx swaps the response into the page, so it wants HTML or text,
        // never JSON; only the `Accept` header can say otherwise for it —
        // even when a shared interceptor also adds `X-Requested-With`.
        let htmx = self
            .headers
            .get("hx-request")
            .is_some_and(|value| value.eq_ignore_ascii_case("true"));
        let classic_xhr = !htmx
            && self
                .headers
                .get("x-requested-with")
                .is_some_and(|value| value.eq_ignore_ascii_case("xmlhttprequest"));

        let Some(accept) = self.headers.get("accept") else {
            return classic_xhr;
        };

        let mut json_q = 0.0f32;
        let mut html_q = 0.0f32;
        let mut named_json_or_html = false;

        for entry in accept.split(',') {
            let mut fields = entry.split(';');
            let Some(media) = fields.next() else {
                continue;
            };
            let media = media.trim().to_ascii_lowercase();

            // A malformed or out-of-range q is treated as absent (q=1), which
            // is what a lenient parser should do with a header it cannot fix.
            let mut quality = 1.0f32;
            for param in fields {
                let param = param.trim().to_ascii_lowercase();
                if let Some(value) = param.strip_prefix("q=") {
                    if let Ok(parsed) = value.trim().parse::<f32>() {
                        if (0.0..=1.0).contains(&parsed) {
                            quality = parsed;
                        }
                    }
                }
            }

            // Any structured-syntax `+json` suffix (RFC 6839), whatever the
            // top-level type: `application/problem+json`, `model/gltf+json`.
            let is_json = media == "application/json" || media.ends_with("+json");
            if is_json {
                json_q = json_q.max(quality);
                named_json_or_html = true;
            } else if media == "text/html" || media == "application/xhtml+xml" {
                html_q = html_q.max(quality);
                named_json_or_html = true;
            }
        }

        if !named_json_or_html {
            return classic_xhr;
        }
        json_q > 0.0 && json_q >= html_q
    }

    /// Get preferred language from Accept-Language header
    pub fn language(&self) -> Option<&str> {
        if let Some(accept_lang) = self.headers.get("accept-language") {
            // Parse "en-US,en;q=0.9,fr;q=0.8" and return first language
            accept_lang
                .split(',')
                .next()
                .and_then(|lang| lang.split(';').next())
                .map(|lang| lang.trim())
        } else {
            None
        }
    }

    /// Get HTTP referrer
    pub fn referrer(&self) -> Option<&str> {
        self.headers.get("referer").map(|s| s.as_str())
    }

    // File upload handling methods

    /// Get uploaded files (Total.js: controller.files)
    pub fn files(&mut self) -> Result<&FileCollection> {
        if self.files.is_none() {
            self.parse_files()?;
        }
        Ok(self.files.as_ref().unwrap())
    }

    /// Get a specific uploaded file by field name
    pub fn file(&mut self, field_name: &str) -> Result<Option<&crate::http::files::UploadedFile>> {
        Ok(self.files()?.get(field_name))
    }

    /// Parse multipart form data to extract files
    /// Also caches form data to avoid re-parsing
    fn parse_files(&mut self) -> Result<()> {
        // Check if this is a multipart form
        if let Some(content_type) = self.headers.get("content-type") {
            if content_type.starts_with("multipart/form-data") {
                // Extract boundary
                if let Some(boundary) = self.extract_boundary(content_type) {
                    let (files, form_data) = MultipartParser::parse(&self.body_bytes, &boundary)?;

                    // Cache form data to avoid re-parsing in body_as_form_data
                    self.multipart_form_data = Some(form_data);
                    self.files = Some(files);
                    return Ok(());
                }

                return Err(Error::InvalidInput(
                    "Invalid multipart/form-data Content-Type: missing or malformed boundary"
                        .to_string(),
                ));
            }
        }

        // Not multipart, create empty file collection
        self.files = Some(FileCollection::new());
        self.multipart_form_data = None;
        Ok(())
    }

    /// Extract boundary from Content-Type header
    fn extract_boundary(&self, content_type: &str) -> Option<String> {
        // Parse: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
        for part in content_type.split(';').skip(1) {
            let part = part.trim();
            if let Some((name, value)) = part.split_once('=') {
                if name.trim().eq_ignore_ascii_case("boundary") {
                    let boundary = value.trim().trim_matches('"');
                    if !boundary.is_empty()
                        && !boundary
                            .chars()
                            .any(|ch| ch.is_control() || ch.is_whitespace())
                    {
                        return Some(boundary.to_string());
                    }
                }
            }
        }
        None
    }

    // Total.js compatibility methods - Phase 1: High Priority Features

    /// Get cookie value by name (Total.js: request.cookie(name)).
    ///
    /// Parses the `Cookie` header once per request and caches the result, so
    /// session + flash + CSRF middleware reading different cookies on the
    /// same request all share one parse.
    pub fn cookie(&self, name: &str) -> Option<String> {
        self.cookies().get(name).cloned()
    }

    /// All cookies on this request, parsed lazily on first access and cached.
    pub fn cookies(&self) -> &HashMap<String, String> {
        self.cookies_cache.get_or_init(|| {
            self.headers
                .get("cookie")
                .map(|h| Self::parse_cookies(h))
                .unwrap_or_default()
        })
    }

    /// Get host from Host header (Total.js: request.host)
    pub fn host(&self) -> Option<&str> {
        self.headers.get("host").map(|s| s.as_str())
    }

    /// Get hostname with optional path (Total.js: request.hostname([path]))
    pub fn hostname(&self, path: Option<&str>) -> String {
        let origin = self
            .request_origin()
            .or_else(|| self.configured_origin())
            .unwrap_or_else(|| "http://localhost".to_string());

        if let Some(path) = path {
            let path = if path.starts_with('/') {
                path
            } else {
                &format!("/{}", path)
            };
            format!("{}{}", origin.trim_end_matches('/'), path)
        } else {
            origin
        }
    }

    fn request_origin(&self) -> Option<String> {
        let host = if self.should_trust_forwarded_headers() {
            self.headers
                .get("x-forwarded-host")
                .map(|value| value.split(',').next().unwrap_or(value).trim())
                .filter(|value| !value.is_empty())
                .or_else(|| {
                    self.headers.get("forwarded").and_then(|value| {
                        value.split(';').find_map(|part| {
                            let part = part.trim();
                            part.strip_prefix("host=")
                                .map(|host| host.trim_matches('"').trim())
                                .filter(|host| !host.is_empty())
                        })
                    })
                })
                .or_else(|| self.host())
        } else {
            self.host()
        }?;

        let scheme = if self.is_secure() { "https" } else { "http" };
        Some(format!("{}://{}", scheme, host))
    }

    fn configured_origin(&self) -> Option<String> {
        if let Some(public_url) = crate::configuration::CONF::get_string("server.public_url") {
            if let Some(origin) = Self::normalize_origin(&public_url) {
                return Some(origin);
            }
        }

        let host = crate::configuration::CONF::get_string("server.host")?;
        let port = crate::configuration::CONF::get::<u16>("server.port")
            .unwrap_or(if self.is_secure() { 443 } else { 80 });
        let scheme = if self.is_secure()
            || crate::configuration::CONF::get_bool("server.ssl_enabled").unwrap_or(false)
        {
            "https"
        } else {
            "http"
        };

        let default_port = match scheme {
            "https" => 443,
            _ => 80,
        };
        let port_suffix = if port == default_port {
            String::new()
        } else {
            format!(":{}", port)
        };

        Some(format!("{}://{}{}", scheme, host, port_suffix))
    }

    /// Get request path from URI (Total.js: request.path)
    pub fn path(&self) -> &str {
        // Extract path from URI, handling both full URLs and paths
        if let Some(path_start) = self.uri.find("://") {
            // Full URL: extract path after domain
            let after_scheme = &self.uri[path_start + 3..];
            if let Some(path_start) = after_scheme.find('/') {
                let path_with_query = &after_scheme[path_start..];
                // Remove query string if present
                if let Some(query_start) = path_with_query.find('?') {
                    &path_with_query[..query_start]
                } else {
                    path_with_query
                }
            } else {
                "/"
            }
        } else {
            // Relative path: remove query string if present
            if let Some(query_start) = self.uri.find('?') {
                &self.uri[..query_start]
            } else {
                &self.uri
            }
        }
    }

    /// Get file extension from path (Total.js: request.extension)
    pub fn extension(&self) -> Option<&str> {
        let path = self.path();
        Path::new(path).extension().and_then(|ext| ext.to_str())
    }

    /// Check if request is authorized (Total.js: request.isAuthorized)
    pub fn is_authorized(&self) -> bool {
        self.headers.get("authorization").is_some()
    }

    /// Get authorization header (Total.js: request.authorization())
    pub fn authorization(&self) -> Option<&str> {
        self.headers.get("authorization").map(|s| s.as_str())
    }

    // Phase 2: Medium Priority Features

    /// Check if request is from a proxy (Total.js: request.isProxy)
    pub fn is_proxy(&self) -> bool {
        self.should_trust_forwarded_headers()
            && (self.headers.contains_key("x-forwarded-for")
                || self.headers.contains_key("x-real-ip")
                || self.headers.contains_key("x-forwarded-proto")
                || self.headers.contains_key("x-forwarded-host")
                || self.headers.contains_key("forwarded"))
    }

    /// Check if request is for a static file (Total.js: request.isStaticFile)
    pub fn is_static_file(&self) -> bool {
        if let Some(ext) = self.extension() {
            // Common static file extensions
            matches!(
                ext.to_lowercase().as_str(),
                "css"
                    | "js"
                    | "jpg"
                    | "jpeg"
                    | "png"
                    | "gif"
                    | "svg"
                    | "webp"
                    | "ico"
                    | "woff"
                    | "woff2"
                    | "ttf"
                    | "eot"
                    | "pdf"
                    | "zip"
                    | "txt"
                    | "xml"
                    | "json"
                    | "csv"
                    | "mp3"
                    | "mp4"
                    | "webm"
                    | "html"
                    | "htm"
                    | "map"
            )
        } else {
            false
        }
    }

    /// Get subdomain from host (Total.js: request.subdomain)
    pub fn subdomain(&self) -> Option<String> {
        if let Some(host) = self.host() {
            // Remove port if present
            let host = if let Some(port_pos) = host.find(':') {
                &host[..port_pos]
            } else {
                host
            };

            let parts: Vec<&str> = host.split('.').collect();
            if parts.len() > 2 {
                // Return everything before the last two parts (domain.tld)
                let subdomain_parts = &parts[..parts.len() - 2];
                if !subdomain_parts.is_empty() {
                    Some(subdomain_parts.join("."))
                } else {
                    None
                }
            } else {
                None
            }
        } else {
            None
        }
    }

    /// Get path segments as array (Total.js: request.split)
    pub fn split(&self) -> Vec<&str> {
        self.path()
            .trim_start_matches('/')
            .trim_end_matches('/')
            .split('/')
            .filter(|s| !s.is_empty())
            .collect()
    }

    /// Generate a cryptographically secure CSRF token
    pub(crate) fn generate_csrf_token() -> String {
        use rand::{thread_rng, Rng};

        // Generate 32-byte random token and encode as base64
        let token_bytes: Vec<u8> = (0..32).map(|_| thread_rng().gen::<u8>()).collect();

        Self::base64_encode(&token_bytes)
    }

    // Helper methods

    /// Parse cookies from Cookie header
    fn parse_cookies(cookie_header: &str) -> HashMap<String, String> {
        let mut cookies = HashMap::new();

        for cookie_pair in cookie_header.split(';') {
            let cookie_pair = cookie_pair.trim();
            if let Some((name, value)) = cookie_pair.split_once('=') {
                let name = name.trim().to_string();
                let value = value.trim().to_string();
                cookies.insert(name, value);
            }
        }

        cookies
    }

    fn should_trust_forwarded_headers(&self) -> bool {
        self.peer_addr
            .map(|addr| self.is_trusted_proxy_ip(addr.ip()))
            .unwrap_or(false)
    }

    fn is_trusted_proxy_ip(&self, ip: IpAddr) -> bool {
        self.trusted_proxies
            .iter()
            .any(|network| network.contains(ip))
    }

    fn normalize_origin(input: &str) -> Option<String> {
        let parsed = Url::parse(input).ok()?;
        let scheme = parsed.scheme();
        let host = parsed.host_str()?;
        let default_port = match scheme {
            "http" => Some(80),
            "https" => Some(443),
            _ => None,
        };
        let port_suffix = match parsed.port() {
            Some(port) if Some(port) != default_port => format!(":{}", port),
            _ => String::new(),
        };

        Some(format!("{}://{}{}", scheme, host, port_suffix))
    }

    /// Simple base64 encoding without external dependencies
    fn base64_encode(input: &[u8]) -> String {
        const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        let mut result = String::new();

        for chunk in input.chunks(3) {
            let b1 = chunk[0] as u32;
            let b2 = chunk.get(1).copied().unwrap_or(0) as u32;
            let b3 = chunk.get(2).copied().unwrap_or(0) as u32;

            let combined = (b1 << 16) | (b2 << 8) | b3;

            result.push(CHARS[((combined >> 18) & 63) as usize] as char);
            result.push(CHARS[((combined >> 12) & 63) as usize] as char);
            result.push(if chunk.len() > 1 {
                CHARS[((combined >> 6) & 63) as usize] as char
            } else {
                '='
            });
            result.push(if chunk.len() > 2 {
                CHARS[(combined & 63) as usize] as char
            } else {
                '='
            });
        }

        result
    }

    /// Reset Request state for pool reuse
    ///
    /// Clears all fields without deallocating underlying storage
    /// to maximize reuse efficiency.
    pub fn reset(&mut self) {
        self.method.clear();
        self.uri.clear();
        self.headers.clear();
        self.params.clear();
        self.query.clear();
        self.body_bytes.clear();
        self.files = None;
        self.multipart_form_data = None;
        self.cookies_cache = once_cell::sync::OnceCell::new();

        // Shrink collections if they've grown too large
        // This prevents memory bloat from requests with large payloads
        const MAX_CAPACITY: usize = 1024;

        if self.headers.capacity() > MAX_CAPACITY {
            self.headers = HashMap::new();
        }
        if self.params.capacity() > MAX_CAPACITY {
            self.params = HashMap::new();
        }
        if self.query.capacity() > MAX_CAPACITY {
            self.query = HashMap::new();
        }
        if self.body_bytes.capacity() > MAX_CAPACITY * 1024 {
            // 1MB
            self.body_bytes = Vec::new();
        }
    }
}

// Secure URL encoding/decoding implementation
mod urlencoding {
    use std::borrow::Cow;

    /// Securely decode URL-encoded strings with validation
    pub fn decode(s: &str) -> Option<Cow<'_, str>> {
        decode_safe(s).ok()
    }

    /// Safe URL decoding with comprehensive validation
    pub fn decode_safe(input: &str) -> Result<Cow<'_, str>, UrlDecodeError> {
        // Input validation
        if input.len() > MAX_URL_LENGTH {
            return Err(UrlDecodeError::TooLong);
        }

        let mut result = Vec::new();
        let mut chars = input.char_indices();

        while let Some((i, ch)) = chars.next() {
            match ch {
                '%' => {
                    // Ensure we have at least 2 more characters
                    if i + 2 >= input.len() {
                        return Err(UrlDecodeError::InvalidEncoding);
                    }

                    // Get the next two characters
                    let hex_str = &input[i + 1..i + 3];

                    // Validate hex characters
                    if !hex_str.chars().all(|c| c.is_ascii_hexdigit()) {
                        return Err(UrlDecodeError::InvalidHex);
                    }

                    // Parse hex value
                    let hex_value =
                        u8::from_str_radix(hex_str, 16).map_err(|_| UrlDecodeError::InvalidHex)?;

                    result.push(hex_value);

                    // Skip the next two characters
                    chars.next();
                    chars.next();
                }
                '+' => {
                    // Convert + to space (application/x-www-form-urlencoded)
                    result.push(b' ');
                }
                c if c.is_ascii() && is_safe_url_char(c) => {
                    result.push(c as u8);
                }
                _ => {
                    // Invalid or unsafe character
                    return Err(UrlDecodeError::InvalidCharacter);
                }
            }
        }

        // Convert bytes to string, validating UTF-8
        match String::from_utf8(result) {
            Ok(decoded) => {
                if decoded
                    .chars()
                    .any(|c| c == '\0' || (c.is_control() && !matches!(c, '\n' | '\r' | '\t')))
                {
                    Err(UrlDecodeError::UnsafeByte)
                } else if decoded == input {
                    Ok(Cow::Borrowed(input))
                } else {
                    Ok(Cow::Owned(decoded))
                }
            }
            Err(_) => Err(UrlDecodeError::InvalidUtf8),
        }
    }

    const MAX_URL_LENGTH: usize = 8192; // 8KB limit

    #[derive(Debug)]
    pub enum UrlDecodeError {
        TooLong,
        InvalidEncoding,
        InvalidHex,
        UnsafeByte,
        InvalidCharacter,
        InvalidUtf8,
    }

    /// Check if a URL character is safe to include
    fn is_safe_url_char(c: char) -> bool {
        match c {
            // Unreserved characters
            'A'..='Z' | 'a'..='z' | '0'..='9' | '-' | '.' | '_' | '~' => true,
            // Reserved characters that are safe in query strings
            ':' | '/' | '?' | '#' | '[' | ']' | '@' => true,
            // Sub-delims
            '!' | '$' | '&' | '\'' | '(' | ')' | '*' | '+' | ',' | ';' | '=' => true,
            _ => false,
        }
    }
}

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

    /// Build a GET request carrying one header.
    fn with_header(name: &str, value: &str) -> Request {
        let mut request = Request::new("GET", "/", "HTTP/1.1");
        request.headers.insert(name.to_string(), value.to_string());
        request
    }

    #[test]
    fn test_wants_json_ranks_json_against_html() {
        // No Accept at all, and the wildcard curl sends: neither asks for JSON.
        assert!(!Request::new("GET", "/", "HTTP/1.1").wants_json());
        assert!(!with_header("accept", "*/*").wants_json());

        // A plain API client.
        assert!(with_header("accept", "application/json").wants_json());
        assert!(with_header("accept", "APPLICATION/JSON").wants_json());

        // A browser: text/html is present, application/json is not.
        assert!(!with_header(
            "accept",
            "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
        )
        .wants_json());

        // Both present — q decides, and a tie goes to JSON.
        assert!(with_header("accept", "text/html;q=0.8, application/json;q=0.9").wants_json());
        assert!(!with_header("accept", "text/html;q=0.9, application/json;q=0.8").wants_json());
        assert!(with_header("accept", "text/html, application/json").wants_json());

        // A malformed or out-of-range q is treated as absent (q=1).
        assert!(with_header("accept", "application/json;q=banana, text/html;q=0.9").wants_json());
        assert!(with_header("accept", "application/json;q=7, text/html;q=0.9").wants_json());

        // Real client defaults: axios lists JSON before a wildcard; fetch sends
        // only the wildcard.
        assert!(with_header("accept", "application/json, text/plain, */*").wants_json());
        assert!(!with_header("accept", "*/*").wants_json());

        // Structured `+json` types count as JSON, any of them.
        assert!(with_header("accept", "application/problem+json").wants_json());
        assert!(with_header("accept", "application/x-made-up+json").wants_json());
        assert!(with_header("accept", "model/gltf+json").wants_json());
        assert!(with_header("accept", "application/vnd.api+json, text/html;q=0.5").wants_json());

        // A classic XHR is JSON when Accept does not decide...
        assert!(
            with_header("x-requested-with", "XMLHttpRequest").wants_json(),
            "an XHR asks for JSON even without an Accept header"
        );
        let mut xhr_wildcard = with_header("x-requested-with", "XMLHttpRequest");
        xhr_wildcard
            .headers
            .insert("accept".to_string(), "*/*".to_string());
        assert!(xhr_wildcard.wants_json());

        // ...but an XHR that explicitly asks for HTML gets it.
        let mut xhr_html = with_header("x-requested-with", "XMLHttpRequest");
        xhr_html
            .headers
            .insert("accept".to_string(), "text/html".to_string());
        assert!(!xhr_html.wants_json());

        // htmx swaps the body into the page: never JSON on its own say-so.
        assert!(!with_header("hx-request", "true").wants_json());
        let mut htmx_html = with_header("hx-request", "true");
        htmx_html
            .headers
            .insert("accept".to_string(), "text/html".to_string());
        assert!(!htmx_html.wants_json());
        let mut htmx_json = with_header("hx-request", "true");
        htmx_json
            .headers
            .insert("accept".to_string(), "application/json".to_string());
        assert!(
            htmx_json.wants_json(),
            "an explicit Accept still wins for htmx"
        );
        // htmx plus an interceptor-added X-Requested-With is still htmx.
        let mut htmx_xhr = with_header("hx-request", "true");
        htmx_xhr
            .headers
            .insert("x-requested-with".to_string(), "XMLHttpRequest".to_string());
        htmx_xhr
            .headers
            .insert("accept".to_string(), "*/*".to_string());
        assert!(!htmx_xhr.wants_json());
    }

    #[test]
    fn test_path_normalizes_origin_and_absolute_forms() {
        // HTTP/1 origin-form
        let h1 = Request::new("GET", "/api/status?x=1", "HTTP/1.1");
        assert_eq!(h1.path(), "/api/status");

        // HTTP/2 absolute-form (scheme + authority) — must yield the same path
        // so the router matches identically over h2 (regression: was 404 over h2).
        let h2 = Request::new("GET", "http://127.0.0.1:8000/api/status?x=1", "HTTP/2");
        assert_eq!(h2.path(), "/api/status");

        // absolute-form, no query, root path
        let root = Request::new("GET", "http://example.com/", "HTTP/2");
        assert_eq!(root.path(), "/");
    }

    #[test]
    fn test_secure_url_decoding() {
        use super::urlencoding::decode;

        // Test basic decoding
        assert_eq!(decode("hello%20world").unwrap(), "hello world");
        assert_eq!(decode("test+string").unwrap(), "test string");
        assert_eq!(decode("normal_string").unwrap(), "normal_string");
        assert_eq!(decode("caf%C3%A9").unwrap(), "café");

        // Decoding should be syntax-focused, not content-blocking.
        assert_eq!(decode("../etc/passwd").unwrap(), "../etc/passwd");
        assert_eq!(decode("%2e%2e%2fpasswd").unwrap(), "../passwd");
        assert_eq!(decode("%3cscript%3e").unwrap(), "<script>");

        // Null and control characters remain invalid.
        assert!(decode("%00null").is_none());

        // Test length limits
        let long_string = "a".repeat(10000);
        assert!(decode(&long_string).is_none());

        // Test invalid encoding
        assert!(decode("invalid%GG").is_none());
        assert!(decode("incomplete%2").is_none());

        // Test control character filtering
        assert!(decode("%01%02%03").is_none());
    }

    #[test]
    fn test_url_decode_error_types() {
        use super::urlencoding::{decode_safe, UrlDecodeError};

        // Test specific error types
        let long_input = "a".repeat(10000);
        assert!(matches!(
            decode_safe(&long_input),
            Err(UrlDecodeError::TooLong)
        ));

        assert!(matches!(
            decode_safe("caf%C3%A9"),
            Ok(value) if value.as_ref() == "café"
        ));
        assert!(matches!(
            decode_safe("invalid%GG"),
            Err(UrlDecodeError::InvalidHex)
        ));
        assert!(matches!(
            decode_safe("incomplete%2"),
            Err(UrlDecodeError::InvalidEncoding)
        ));

        assert!(matches!(
            decode_safe("%00test"),
            Err(UrlDecodeError::UnsafeByte)
        ));

        // Test unsafe byte with a different control character that's not in malicious patterns
        assert!(matches!(
            decode_safe("%01test"),
            Err(UrlDecodeError::UnsafeByte)
        ));
    }

    #[test]
    fn test_safe_query_parsing() {
        // Syntax-invalid values are skipped; content is preserved for later layers.
        let malicious_query = "key1=../passwd&key2=%00null&key3=normal";
        let parsed = Request::parse_query(malicious_query);

        assert_eq!(parsed.get("key1"), Some(&"../passwd".to_string()));
        assert_eq!(parsed.get("key3"), Some(&"normal".to_string()));
        assert!(!parsed.contains_key("key2"));
    }

    #[test]
    fn test_parse_query_function() {
        let query = Request::parse_query("param=value&other=test&flag");

        assert_eq!(query.get("param"), Some(&"value".to_string()));
        assert_eq!(query.get("other"), Some(&"test".to_string()));
        assert_eq!(query.get("flag"), Some(&"".to_string()));
    }

    #[test]
    fn test_parse_query_skips_invalid_or_empty_keys() {
        let query = Request::parse_query("=bad&%00evil=value&ok=1");

        assert_eq!(query.get("ok"), Some(&"1".to_string()));
        assert!(!query.contains_key(""));
        assert_eq!(query.len(), 1);
    }

    #[test]
    fn test_form_data_getters() {
        let mut map = HashMap::new();
        map.insert("name".to_string(), FormValue::Single("Alice".to_string()));
        map.insert("age".to_string(), FormValue::Single("30".to_string()));
        map.insert("active".to_string(), FormValue::Single("true".to_string()));
        map.insert("empty".to_string(), FormValue::Single("".to_string()));
        map.insert("price".to_string(), FormValue::Single("19.99".to_string()));
        map.insert(
            "tags".to_string(),
            FormValue::Multiple(vec!["rust".to_string(), "web".to_string()]),
        );
        let form = FormData::new(map);

        assert_eq!(form.get_str("name").unwrap(), "Alice");
        assert_eq!(form.get_int("age").unwrap(), 30);
        assert!(form.get_bool("active").unwrap());
        assert_eq!(form.get_as::<f64>("price").unwrap(), 19.99);

        assert!(form.get_str("missing").is_err());
        assert!(form.get_str("empty").is_err());
        assert!(form.get_int("name").is_err());

        assert_eq!(form.get_str_or("name", "default"), "Alice");
        assert_eq!(form.get_str_or("missing", "default"), "default");
        assert_eq!(form.get_str_or("empty", "default"), "default");
        assert_eq!(form.get_int_or("age", 0), 30);
        assert_eq!(form.get_int_or("missing", 42), 42);
        assert!(form.get_bool_or("active", false));
        assert!(form.get_bool_or("missing", true));
        assert_eq!(form.get_as_or::<f64>("missing", 1.5), 1.5);
    }

    #[test]
    fn test_form_data_keeps_every_value_of_a_multi_value_field() {
        let mut map = HashMap::new();
        map.insert("k".to_string(), FormValue::Single("v".to_string()));
        map.insert(
            "tags".to_string(),
            FormValue::Multiple(vec!["rust".to_string(), "web".to_string()]),
        );
        map.insert(
            "ids".to_string(),
            FormValue::Multiple(vec!["1".to_string(), "2".to_string()]),
        );
        let form = FormData::new(map);

        assert_eq!(form.get("k"), Some("v"));
        assert_eq!(form.get_all("k"), vec!["v"]);
        // The lossy behaviour this replaced returned only one of the two.
        assert_eq!(form.get_all("tags"), vec!["rust", "web"]);
        // Reading a multi-value field as a scalar takes the first value.
        assert_eq!(form.get("tags"), Some("rust"));
        assert_eq!(form.get_all_as::<i32>("ids").unwrap(), vec![1, 2]);
        assert!(form.get_all_as::<i32>("tags").is_err());
        assert_eq!(form.get_all("missing"), Vec::<&str>::new());
        assert!(form.contains_key("k"));
        assert!(!form.contains_key("missing"));
        assert_eq!(form.len(), 3);
    }

    #[test]
    fn test_form_data_default() {
        let form = FormData::default();
        assert!(form.is_empty());
    }

    #[test]
    fn test_form_arrays() {
        // Test array notation with []
        let query = Request::parse_query_with_arrays("tags[]=rust&tags[]=web&tags[]=framework");

        assert_eq!(query.len(), 1);
        let tags_value = query.get("tags").unwrap();
        assert!(tags_value.is_array());
        assert_eq!(tags_value.as_array(), vec!["rust", "web", "framework"]);

        // Test mixed array and single values
        let query =
            Request::parse_query_with_arrays("name=John&hobbies[]=coding&hobbies[]=reading&age=30");

        assert_eq!(query.len(), 3);

        let name = query.get("name").unwrap();
        assert!(!name.is_array());
        assert_eq!(name.as_string(), "John");

        let hobbies = query.get("hobbies").unwrap();
        assert!(hobbies.is_array());
        assert_eq!(hobbies.as_array(), vec!["coding", "reading"]);

        let age = query.get("age").unwrap();
        assert!(!age.is_array());
        assert_eq!(age.as_string(), "30");
    }

    #[test]
    fn test_form_value_conversions() {
        // Test single value
        let single = FormValue::Single("test".to_string());
        assert_eq!(single.as_string(), "test");
        assert_eq!(single.as_array(), vec!["test"]);
        assert!(!single.is_array());

        // Test multiple values
        let multiple = FormValue::Multiple(vec![
            "one".to_string(),
            "two".to_string(),
            "three".to_string(),
        ]);
        assert_eq!(multiple.as_string(), "one"); // Gets first element
        assert_eq!(multiple.as_array(), vec!["one", "two", "three"]);
        assert!(multiple.is_array());

        // Test empty array
        let empty_multiple = FormValue::Multiple(vec![]);
        assert_eq!(empty_multiple.as_string(), "");
        assert_eq!(empty_multiple.as_array(), Vec::<&str>::new());
        assert!(empty_multiple.is_array());
    }

    #[test]
    fn test_form_parsing_with_encoding() {
        // Test URL encoded values
        let query = Request::parse_query_with_arrays(
            "message=Hello%20World&tags[]=rust%2Blang&tags[]=web%20dev",
        );

        let message = query.get("message").unwrap();
        assert_eq!(message.as_string(), "Hello World");

        let tags = query.get("tags").unwrap();
        assert_eq!(tags.as_array(), vec!["rust+lang", "web dev"]);
    }

    #[test]
    fn test_multipart_form_data_uses_cached_fields() {
        let mut request = Request::default();
        request.headers.insert(
            "content-type".to_string(),
            "multipart/form-data; boundary=boundary123".to_string(),
        );
        request.set_body(
            b"--boundary123\r\n\
Content-Disposition: form-data; name=\"title\"\r\n\r\n\
Hello multipart\r\n\
--boundary123\r\n\
Content-Disposition: form-data; name=\"upload\"; filename=\"test.txt\"\r\n\
Content-Type: text/plain\r\n\r\n\
file contents\r\n\
--boundary123--\r\n"
                .to_vec(),
        );

        let form = request.body_as_form_data().unwrap();
        assert_eq!(
            form.get("title").map(FormValue::as_string),
            Some("Hello multipart")
        );
        assert!(form.get("upload").is_none());
    }

    #[test]
    fn test_extract_boundary_supports_quoted_values() {
        let request = Request::default();
        let boundary = request.extract_boundary("multipart/form-data; boundary=\"abc123\"");

        assert_eq!(boundary.as_deref(), Some("abc123"));
    }

    #[test]
    fn test_parse_files_errors_on_missing_boundary() {
        let mut request = Request::default();
        request.headers.insert(
            "content-type".to_string(),
            "multipart/form-data".to_string(),
        );
        request.set_body(b"--ignored--".to_vec());

        let err = request.files().unwrap_err();
        assert!(matches!(err, Error::InvalidInput(_)));
    }

    #[test]
    fn test_form_parsing_malicious_input() {
        // Query parsing preserves content and only rejects invalid encodings/control chars.
        let query = Request::parse_query("safe=value&bad=../etc/passwd&normal=test");

        assert_eq!(query.get("safe"), Some(&"value".to_string()));
        assert_eq!(query.get("bad"), Some(&"../etc/passwd".to_string()));
        assert_eq!(query.get("normal"), Some(&"test".to_string()));
    }

    #[test]
    fn test_form_arrays_edge_cases() {
        // Test single value that becomes array when more values added
        let query = Request::parse_query_with_arrays("item=first&item=second&item=third");

        let items = query.get("item").unwrap();
        assert!(items.is_array());
        assert_eq!(items.as_array(), vec!["first", "second", "third"]);

        // Test empty brackets
        let query = Request::parse_query_with_arrays("empty[]=&empty[]=&filled[]=value");

        let empty = query.get("empty").unwrap();
        assert!(empty.is_array());
        assert_eq!(empty.as_array(), vec!["", ""]);

        let filled = query.get("filled").unwrap();
        assert_eq!(filled.as_string(), "value");
    }

    // Tests for new Total.js compatibility features

    #[test]
    fn test_cookie_parsing() {
        let mut request = Request::default();
        request.headers.insert(
            "cookie".to_string(),
            "session=abc123; user=john; theme=dark".to_string(),
        );

        assert_eq!(request.cookie("session"), Some("abc123".to_string()));
        assert_eq!(request.cookie("user"), Some("john".to_string()));
        assert_eq!(request.cookie("theme"), Some("dark".to_string()));
        assert_eq!(request.cookie("nonexistent"), None);

        // Test with no cookies
        let empty_request = Request::default();
        assert_eq!(empty_request.cookie("any"), None);
    }

    #[test]
    fn test_cookies_cache_returns_stable_reference() {
        // Two calls to cookies() must return the exact same HashMap —
        // proves the lazy cache isn't re-parsing per call.
        let mut request = Request::default();
        request
            .headers
            .insert("cookie".to_string(), "a=1; b=2; c=3".to_string());

        let first = request.cookies() as *const _;
        let second = request.cookies() as *const _;
        assert_eq!(
            first, second,
            "cookies() must cache — got different HashMap pointers"
        );

        // And multiple cookie(name) calls go through the same cache.
        assert_eq!(request.cookie("a"), Some("1".to_string()));
        assert_eq!(request.cookie("b"), Some("2".to_string()));
        assert_eq!(request.cookie("c"), Some("3".to_string()));
        let third = request.cookies() as *const _;
        assert_eq!(first, third);
    }

    #[test]
    fn test_reset_clears_cookie_cache() {
        let mut request = Request::default();
        request
            .headers
            .insert("cookie".to_string(), "session=first".to_string());
        assert_eq!(request.cookie("session"), Some("first".to_string()));

        request.reset();
        request
            .headers
            .insert("cookie".to_string(), "session=second".to_string());

        assert_eq!(request.cookie("session"), Some("second".to_string()));
    }

    #[test]
    fn test_host_and_hostname() {
        let mut request = Request::default();
        request
            .headers
            .insert("host".to_string(), "example.com:8080".to_string());

        assert_eq!(request.host(), Some("example.com:8080"));
        assert_eq!(request.hostname(None), "http://example.com:8080");
        assert_eq!(
            request.hostname(Some("/api/users")),
            "http://example.com:8080/api/users"
        );
        assert_eq!(
            request.hostname(Some("api/users")),
            "http://example.com:8080/api/users"
        );

        // Test HTTPS detection
        request.peer_addr = Some("10.0.0.5:8080".parse().unwrap());
        request.trusted_proxies = Arc::new(vec!["10.0.0.0/8".parse().unwrap()]);
        request
            .headers
            .insert("x-forwarded-proto".to_string(), "https".to_string());
        assert_eq!(request.hostname(None), "https://example.com:8080");

        // Test with no host
        let empty_request = Request::default();
        assert_eq!(empty_request.host(), None);
        assert!(
            empty_request.hostname(None).starts_with("http://localhost"),
            "fallback hostname should default to localhost when no request host is available"
        );
    }

    #[test]
    fn test_path_and_extension() {
        let mut request = Request::default();

        // Test simple path
        request.uri = "/api/users.json".to_string();
        assert_eq!(request.path(), "/api/users.json");
        assert_eq!(request.extension(), Some("json"));

        // Test path with query parameters
        request.uri = "/api/users.json?limit=10&offset=0".to_string();
        assert_eq!(request.path(), "/api/users.json");
        assert_eq!(request.extension(), Some("json"));

        // Test full URL
        request.uri = "https://example.com:8080/api/users.html?param=value".to_string();
        assert_eq!(request.path(), "/api/users.html");
        assert_eq!(request.extension(), Some("html"));

        // Test root path
        request.uri = "/".to_string();
        assert_eq!(request.path(), "/");
        assert_eq!(request.extension(), None);

        // Test path without extension
        request.uri = "/api/users".to_string();
        assert_eq!(request.path(), "/api/users");
        assert_eq!(request.extension(), None);

        // Test full URL without path
        request.uri = "https://example.com".to_string();
        assert_eq!(request.path(), "/");
        assert_eq!(request.extension(), None);
    }

    #[test]
    fn test_authorization() {
        let mut request = Request::default();

        // Test with no authorization
        assert!(!request.is_authorized());
        assert_eq!(request.authorization(), None);

        // Test with authorization header
        request
            .headers
            .insert("authorization".to_string(), "Bearer token123".to_string());
        assert!(request.is_authorized());
        assert_eq!(request.authorization(), Some("Bearer token123"));

        // Test with basic auth
        request.headers.insert(
            "authorization".to_string(),
            "Basic dXNlcjpwYXNz".to_string(),
        );
        assert!(request.is_authorized());
        assert_eq!(request.authorization(), Some("Basic dXNlcjpwYXNz"));
    }

    #[test]
    fn test_proxy_detection() {
        let mut request = Request::default();

        // Test with no proxy headers
        assert!(!request.is_proxy());

        // Untrusted proxy headers do not make the request proxied.
        request
            .headers
            .insert("x-forwarded-for".to_string(), "192.168.1.1".to_string());
        assert!(!request.is_proxy());

        // Trusted peer with forwarded headers is treated as proxied.
        request = Request::default();
        request.peer_addr = Some("10.0.0.5:8080".parse().unwrap());
        request.trusted_proxies = Arc::new(vec!["10.0.0.0/8".parse().unwrap()]);
        request
            .headers
            .insert("x-real-ip".to_string(), "10.0.0.1".to_string());
        assert!(request.is_proxy());

        // Trusted proxy via X-Forwarded-Proto
        request = Request::default();
        request.peer_addr = Some("10.0.0.5:8080".parse().unwrap());
        request.trusted_proxies = Arc::new(vec!["10.0.0.0/8".parse().unwrap()]);
        request
            .headers
            .insert("x-forwarded-proto".to_string(), "https".to_string());
        assert!(request.is_proxy());

        // Trusted proxy via Forwarded header
        request = Request::default();
        request.peer_addr = Some("10.0.0.5:8080".parse().unwrap());
        request.trusted_proxies = Arc::new(vec!["10.0.0.0/8".parse().unwrap()]);
        request.headers.insert(
            "forwarded".to_string(),
            "for=192.0.2.60;proto=http".to_string(),
        );
        assert!(request.is_proxy());
    }

    #[test]
    fn test_client_ip_ignores_forwarded_headers_from_untrusted_peer() {
        let mut request = Request::default();
        request.peer_addr = Some("10.0.0.5:8080".parse().unwrap());
        request.headers.insert(
            "x-forwarded-for".to_string(),
            "203.0.113.10, 10.0.0.5".to_string(),
        );
        request
            .headers
            .insert("x-real-ip".to_string(), "203.0.113.20".to_string());

        assert_eq!(request.client_ip(), "10.0.0.5");
    }

    #[test]
    fn test_client_ip_uses_forwarded_headers_from_trusted_peer() {
        let mut request = Request::default();
        request.peer_addr = Some("10.0.0.5:8080".parse().unwrap());
        request.trusted_proxies = Arc::new(vec!["10.0.0.0/8".parse().unwrap()]);
        request.headers.insert(
            "x-forwarded-for".to_string(),
            "203.0.113.10, 10.1.1.1".to_string(),
        );

        assert_eq!(request.client_ip(), "203.0.113.10");
    }

    #[test]
    fn test_is_secure_ignores_forwarded_proto_from_untrusted_peer() {
        let mut request = Request::default();
        request.peer_addr = Some("10.0.0.5:8080".parse().unwrap());
        request
            .headers
            .insert("x-forwarded-proto".to_string(), "https".to_string());

        assert!(!request.is_secure());
    }

    #[test]
    fn test_is_secure_uses_forwarded_proto_from_trusted_peer() {
        let mut request = Request::default();
        request.peer_addr = Some("10.0.0.5:8080".parse().unwrap());
        request.trusted_proxies = Arc::new(vec!["10.0.0.0/8".parse().unwrap()]);
        request
            .headers
            .insert("x-forwarded-proto".to_string(), "https".to_string());

        assert!(request.is_secure());
    }

    #[test]
    fn test_static_file_detection() {
        let mut request = Request::default();

        // Test static file extensions
        let static_files = [
            "/assets/style.css",
            "/js/app.js",
            "/images/logo.png",
            "/favicon.ico",
            "/font.woff2",
            "/document.pdf",
            "/data.json",
            "/video.mp4",
            "/map.xml",
        ];

        for file_path in static_files {
            request.uri = file_path.to_string();
            assert!(
                request.is_static_file(),
                "Should detect {} as static file",
                file_path
            );
        }

        // Test non-static paths
        let dynamic_paths = ["/api/users", "/", "/users/123", "/admin/login"];

        for path in dynamic_paths {
            request.uri = path.to_string();
            assert!(
                !request.is_static_file(),
                "Should not detect {} as static file",
                path
            );
        }
    }

    #[test]
    fn test_subdomain_extraction() {
        let mut request = Request::default();

        // Test with subdomain
        request
            .headers
            .insert("host".to_string(), "api.example.com".to_string());
        assert_eq!(request.subdomain(), Some("api".to_string()));

        // Test with multiple subdomains
        request
            .headers
            .insert("host".to_string(), "v1.api.example.com".to_string());
        assert_eq!(request.subdomain(), Some("v1.api".to_string()));

        // Test with no subdomain
        request
            .headers
            .insert("host".to_string(), "example.com".to_string());
        assert_eq!(request.subdomain(), None);

        // Test with port
        request
            .headers
            .insert("host".to_string(), "api.example.com:8080".to_string());
        assert_eq!(request.subdomain(), Some("api".to_string()));

        // Test with www
        request
            .headers
            .insert("host".to_string(), "www.example.com".to_string());
        assert_eq!(request.subdomain(), Some("www".to_string()));

        // Test with no host
        request.headers.clear();
        assert_eq!(request.subdomain(), None);
    }

    #[test]
    fn test_path_split() {
        let mut request = Request::default();

        // Test normal path
        request.uri = "/api/v1/users/123".to_string();
        assert_eq!(request.split(), vec!["api", "v1", "users", "123"]);

        // Test root path
        request.uri = "/".to_string();
        assert_eq!(request.split(), Vec::<&str>::new());

        // Test path with trailing slash
        request.uri = "/api/users/".to_string();
        assert_eq!(request.split(), vec!["api", "users"]);

        // Test path with query parameters
        request.uri = "/api/users?limit=10".to_string();
        assert_eq!(request.split(), vec!["api", "users"]);

        // Test single segment
        request.uri = "/dashboard".to_string();
        assert_eq!(request.split(), vec!["dashboard"]);
    }

    #[test]
    fn test_base64_encode() {
        // Test base64 encoding function
        let input1 = b"hello";
        let encoded1 = Request::base64_encode(input1);
        assert_eq!(encoded1, "aGVsbG8=");

        let input2 = b"hello world";
        let encoded2 = Request::base64_encode(input2);
        assert_eq!(encoded2, "aGVsbG8gd29ybGQ=");

        // Test empty input
        let input3 = b"";
        let encoded3 = Request::base64_encode(input3);
        assert_eq!(encoded3, "");
    }
}

#[cfg(test)]
mod websocket_upgrade_tests {
    use super::*;
    use http_body_util::Full;
    use hyper::body::Bytes;
    use std::sync::Arc;

    fn handshake_headers() -> HashMap<String, String> {
        let mut headers = HashMap::new();
        headers.insert("upgrade".into(), "websocket".into());
        headers.insert("connection".into(), "Upgrade".into());
        headers
    }

    #[test]
    fn detects_a_plain_handshake() {
        assert!(is_websocket_upgrade_headers("GET", &handshake_headers()));
    }

    #[test]
    fn header_tokens_are_case_insensitive() {
        let mut headers = HashMap::new();
        headers.insert("upgrade".into(), "WebSocket".into());
        headers.insert("connection".into(), "UPGRADE".into());
        assert!(is_websocket_upgrade_headers("get", &headers));
    }

    #[test]
    fn connection_token_is_found_inside_a_list() {
        // Proxies routinely rewrite this to `keep-alive, Upgrade`.
        let mut headers = handshake_headers();
        headers.insert("connection".into(), "keep-alive, Upgrade".into());
        assert!(is_websocket_upgrade_headers("GET", &headers));

        headers.insert("upgrade".into(), "h2c, websocket".into());
        assert!(is_websocket_upgrade_headers("GET", &headers));
    }

    #[test]
    fn a_substring_is_not_a_token() {
        // `upgrade-insecure-requests` contains "upgrade" but is not the token.
        let mut headers = handshake_headers();
        headers.insert("connection".into(), "upgrade-insecure-requests".into());
        assert!(!is_websocket_upgrade_headers("GET", &headers));
    }

    #[test]
    fn rejects_non_get_and_missing_headers() {
        assert!(
            !is_websocket_upgrade_headers("POST", &handshake_headers()),
            "a handshake is a GET"
        );

        let mut only_upgrade = HashMap::new();
        only_upgrade.insert("upgrade".into(), "websocket".into());
        assert!(!is_websocket_upgrade_headers("GET", &only_upgrade));

        let mut only_connection = HashMap::new();
        only_connection.insert("connection".into(), "Upgrade".into());
        assert!(!is_websocket_upgrade_headers("GET", &only_connection));

        let mut other_protocol = handshake_headers();
        other_protocol.insert("upgrade".into(), "h2c".into());
        assert!(!is_websocket_upgrade_headers("GET", &other_protocol));

        assert!(!is_websocket_upgrade_headers("GET", &HashMap::new()));
    }

    #[tokio::test]
    async fn is_websocket_upgrade_reads_the_built_request() {
        let hyper_req = hyper::Request::builder()
            .method("GET")
            .uri("/chat")
            .header("upgrade", "websocket")
            .header("connection", "Upgrade")
            .header("sec-websocket-version", "13")
            .body(Full::new(Bytes::new()))
            .unwrap();

        let request = Request::from_hyper_with_connection(hyper_req, None, Arc::new(Vec::new()))
            .await
            .unwrap();

        assert!(request.is_websocket_upgrade());
    }

    #[tokio::test]
    async fn no_upgrade_handle_without_a_real_connection() {
        // A hand-built request carries no `OnUpgrade` extension, so there is
        // nothing to upgrade even though the headers ask for it. The handle
        // must stay `None` rather than become one that never resolves.
        let hyper_req = hyper::Request::builder()
            .method("GET")
            .uri("/chat")
            .header("upgrade", "websocket")
            .header("connection", "Upgrade")
            .body(Full::new(Bytes::new()))
            .unwrap();

        let mut request =
            Request::from_hyper_with_connection(hyper_req, None, Arc::new(Vec::new()))
                .await
                .unwrap();

        assert!(request.is_websocket_upgrade());
        assert!(!request.has_upgrade());
        assert!(request.take_upgrade().is_none());
    }

    #[tokio::test]
    async fn ordinary_requests_carry_no_upgrade_handle() {
        let hyper_req = hyper::Request::builder()
            .method("GET")
            .uri("/chat")
            .body(Full::new(Bytes::new()))
            .unwrap();

        let request = Request::from_hyper_with_connection(hyper_req, None, Arc::new(Vec::new()))
            .await
            .unwrap();

        assert!(!request.is_websocket_upgrade());
        assert!(!request.has_upgrade());
    }

    #[test]
    fn hand_built_requests_default_to_no_upgrade() {
        let request = Request::new("GET", "/chat", "HTTP/1.1");
        assert!(!request.has_upgrade());
        assert!(!Request::default().has_upgrade());
    }
}