autumn-web 0.6.0

An opinionated, convention-over-configuration web framework for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
//! CSRF (Cross-Site Request Forgery) protection middleware.
//!
//! Protects against CSRF attacks by requiring a token on mutating
//! HTTP methods (POST, PUT, DELETE, PATCH). The token is stored in a
//! cookie and must be echoed back via a request header or form field.
//!
//! # How it works
//!
//! 1. On every response, a CSRF cookie is set (if not already present)
//!    containing a random UUID v4 token.
//! 2. On mutating requests, the middleware checks that the token from
//!    the cookie matches the token in the `X-CSRF-Token` header (or
//!    `_csrf` form field).
//! 3. Safe methods (GET, HEAD, OPTIONS, TRACE) are exempt.
//!
//! # Body-token scanning
//!
//! When the token is carried in a urlencoded / multipart **form body** (rather
//! than the header or query string), the layer scans only a bounded **prefix**
//! of the body — at most `security.csrf.token_scan_bytes` (2 MiB by default) —
//! to locate the `_csrf` field. The remainder of the body is **streamed
//! through unbuffered** to the handler, so a large file upload is never fully
//! copied into memory by this layer (which would otherwise be a DoS-shaped
//! memory cost and would defeat the streaming upload path).
//!
//! **Token-early constraint:** the `_csrf` token must therefore appear within
//! the first `token_scan_bytes` of the body. Scaffolded forms emit the hidden
//! `_csrf` field *before* any file field, so they are always safe. Hand-written
//! forms that place large fields ahead of `_csrf` should move the token earlier
//! or raise the cap. A body whose token sits beyond the prefix is treated as a
//! missing token (403); a genuinely oversized upload is rejected downstream by
//! the real body / upload limits (the natural `413`), which is where that
//! belongs.
//!
//! # Configuration
//!
//! See [`CsrfConfig`] for available settings.
//!
//! # Examples
//!
//! ## Template integration (Maud)
//!
//! ```rust,ignore
//! use autumn_web::prelude::*;
//! use autumn_web::security::CsrfToken;
//!
//! #[get("/form")]
//! async fn form(csrf: CsrfToken) -> Markup {
//!     html! {
//!         form method="POST" action="/submit" {
//!             input type="hidden" name="_csrf" value=(csrf.token());
//!             input type="text" name="title";
//!             button { "Submit" }
//!         }
//!     }
//! }
//! ```
//!
//! ## JavaScript / htmx
//!
//! Read the CSRF token from the `autumn-csrf` cookie and send it
//! as an `X-CSRF-Token` header with every mutating request.

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use axum::body::{Body, Bytes};
use axum::extract::{FromRequestParts, OptionalFromRequestParts};
use axum::http::{Request, Response, StatusCode};
use futures::StreamExt as _;
use http::header::HeaderName;

use tower::{Layer, Service};
use uuid::Uuid;

use super::config::CsrfConfig;

/// Error body returned with a `403 Forbidden` when CSRF validation fails.
const CSRF_FORBIDDEN_MESSAGE: &str = "CSRF token missing or invalid";

/// Outcome of CSRF verification for a mutating request.
enum CsrfVerdict {
    /// A matching token was found — allow the request through.
    Valid,
    /// No valid token was presented — reject with `403 Forbidden`.
    ///
    /// This also covers the case where a form-body token exists but sits beyond
    /// the scanned prefix (`max_scan_bytes`): the token is simply not observed,
    /// so the request is rejected like any other missing token. A genuinely
    /// oversized body streams through and is bounded downstream by the real
    /// body / upload limits.
    Missing,
}

/// The configured CSRF form field name, placed in request extensions by [`CsrfLayer`].
///
/// [`ChangesetForm`](crate::form::ChangesetForm) reads this so `form_tag` emits the
/// hidden input under the correct field name even when `security.csrf.form_field` has
/// been customised from its default `"_csrf"`.
#[derive(Clone, Debug)]
pub struct CsrfFormField(pub String);

/// The configured CSRF token header name, placed in request extensions by [`CsrfLayer`].
///
/// Templates can read this to emit the correct `data-header` attribute on the
/// `<meta name="csrf-token">` tag so JavaScript CSRF helpers (e.g. the admin panel
/// multipart submit handler) use the configured header name rather than defaulting
/// to `X-CSRF-Token`.
#[derive(Clone, Debug)]
pub struct CsrfTokenHeader(pub String);

/// A CSRF token extracted from the request.
///
/// Use this as a handler parameter to access the CSRF token for embedding
/// in HTML forms. The token is generated per-request and stored in
/// request extensions by the [`CsrfLayer`].
///
/// ## Examples
///
/// ```rust,ignore
/// use autumn_web::prelude::*;
/// use autumn_web::security::CsrfToken;
///
/// #[get("/edit")]
/// async fn edit_form(csrf: CsrfToken) -> Markup {
///     html! {
///         form method="POST" {
///             input type="hidden" name="_csrf" value=(csrf.token());
///             // ...
///         }
///     }
/// }
/// ```
#[derive(Clone, Debug)]
pub struct CsrfToken(String);

impl CsrfToken {
    /// Returns the CSRF token value for embedding in forms or headers.
    #[must_use]
    pub fn token(&self) -> &str {
        &self.0
    }

    #[cfg(test)]
    pub(crate) const fn new(token: String) -> Self {
        Self(token)
    }
}

impl std::fmt::Display for CsrfToken {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl<S> FromRequestParts<S> for CsrfToken
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, &'static str);

    async fn from_request_parts(
        parts: &mut axum::http::request::Parts,
        _state: &S,
    ) -> Result<Self, Self::Rejection> {
        parts.extensions.get::<Self>().cloned().ok_or((
            StatusCode::INTERNAL_SERVER_ERROR,
            "CSRF token not found in request extensions. Is CsrfLayer enabled?",
        ))
    }
}

impl<S> OptionalFromRequestParts<S> for CsrfToken
where
    S: Send + Sync,
{
    type Rejection = std::convert::Infallible;

    async fn from_request_parts(
        parts: &mut axum::http::request::Parts,
        _state: &S,
    ) -> Result<Option<Self>, Self::Rejection> {
        Ok(parts.extensions.get::<Self>().cloned())
    }
}

impl<S> FromRequestParts<S> for CsrfFormField
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, &'static str);

    async fn from_request_parts(
        parts: &mut axum::http::request::Parts,
        _state: &S,
    ) -> Result<Self, Self::Rejection> {
        parts.extensions.get::<Self>().cloned().ok_or((
            StatusCode::INTERNAL_SERVER_ERROR,
            "CSRF form field not found in request extensions. Is CsrfLayer enabled?",
        ))
    }
}

impl<S> OptionalFromRequestParts<S> for CsrfFormField
where
    S: Send + Sync,
{
    type Rejection = std::convert::Infallible;

    async fn from_request_parts(
        parts: &mut axum::http::request::Parts,
        _state: &S,
    ) -> Result<Option<Self>, Self::Rejection> {
        Ok(parts.extensions.get::<Self>().cloned())
    }
}

impl<S> FromRequestParts<S> for CsrfTokenHeader
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, &'static str);

    async fn from_request_parts(
        parts: &mut axum::http::request::Parts,
        _state: &S,
    ) -> Result<Self, Self::Rejection> {
        parts.extensions.get::<Self>().cloned().ok_or((
            StatusCode::INTERNAL_SERVER_ERROR,
            "CSRF token header not found in request extensions. Is CsrfLayer enabled?",
        ))
    }
}

impl<S> OptionalFromRequestParts<S> for CsrfTokenHeader
where
    S: Send + Sync,
{
    type Rejection = std::convert::Infallible;

    async fn from_request_parts(
        parts: &mut axum::http::request::Parts,
        _state: &S,
    ) -> Result<Option<Self>, Self::Rejection> {
        Ok(parts.extensions.get::<Self>().cloned())
    }
}

/// Shared CSRF configuration.
#[derive(Debug, Clone)]
struct CsrfSettings {
    cookie_name: String,
    token_header: HeaderName,
    form_field: String,
    safe_methods: Vec<http::Method>,
    exempt_paths: Vec<String>,
    signing_keys: Option<Arc<crate::security::config::ResolvedSigningKeys>>,
    max_scan_bytes: usize,
}

/// Tower [`Layer`] that applies CSRF protection.
///
/// Applied automatically when `security.csrf.enabled = true` in config.
#[derive(Clone, Debug)]
pub struct CsrfLayer {
    settings: Arc<CsrfSettings>,
}

impl CsrfLayer {
    /// Create a new CSRF layer from configuration.
    #[must_use]
    pub fn from_config(config: &CsrfConfig) -> Self {
        let safe_methods = config
            .safe_methods
            .iter()
            .filter_map(|m| m.parse::<http::Method>().ok())
            .collect();

        let token_header = config
            .token_header
            .parse::<HeaderName>()
            .unwrap_or_else(|_| HeaderName::from_static("x-csrf-token"));

        Self {
            settings: Arc::new(CsrfSettings {
                cookie_name: config.cookie_name.clone(),
                token_header,
                form_field: config.form_field.clone(),
                safe_methods,
                exempt_paths: config.exempt_paths.clone(),
                signing_keys: None,
                max_scan_bytes: config.token_scan_bytes,
            }),
        }
    }

    /// Attach signing keys so CSRF tokens are HMAC-signed.
    ///
    /// When set, tokens are in `{uuid}.{hmac_hex}` format. Unsigned tokens are
    /// rejected. Previous keys (see `ResolvedSigningKeys`) allow tokens signed
    /// with an old key to remain valid during a rotation grace window.
    #[must_use]
    pub fn with_signing_keys(
        mut self,
        keys: Arc<crate::security::config::ResolvedSigningKeys>,
    ) -> Self {
        Arc::make_mut(&mut self.settings).signing_keys = Some(keys);
        self
    }

    /// Add a path prefix that is exempt from CSRF validation.
    #[must_use]
    pub fn with_exempt_path(mut self, path: impl Into<String>) -> Self {
        Arc::make_mut(&mut self.settings)
            .exempt_paths
            .push(path.into());
        self
    }

    /// Override the effective body-token scan cap (`max_scan_bytes`).
    ///
    /// The primary bound stays the small `security.csrf.token_scan_bytes`
    /// prefix (2 MiB by default). The router uses this to *clamp* that prefix to
    /// `min(token_scan_bytes, upload.max_request_size_bytes)` so the CSRF scan
    /// never buffers more than the global body limit when an operator lowers
    /// that limit below the prefix cap. See the call site in `router.rs`.
    #[must_use]
    pub fn with_max_scan_bytes(mut self, max_scan_bytes: usize) -> Self {
        Arc::make_mut(&mut self.settings).max_scan_bytes = max_scan_bytes;
        self
    }
}

impl<S> Layer<S> for CsrfLayer {
    type Service = CsrfService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        CsrfService {
            inner,
            settings: Arc::clone(&self.settings),
        }
    }
}

/// Tower [`Service`] produced by [`CsrfLayer`].
#[derive(Clone, Debug)]
pub struct CsrfService<S> {
    inner: S,
    settings: Arc<CsrfSettings>,
}

use subtle::{Choice, ConstantTimeEq};

/// Constant-time string comparison to prevent timing attacks when verifying CSRF tokens.
///
/// The comparison always processes exactly `b.len()` bytes so that execution
/// time is independent of the length of the submitted token `a`.  Neither a
/// length mismatch nor a short input causes an early exit.
#[inline(never)]
fn constant_time_eq(a: &str, b: &str) -> bool {
    let a = a.as_bytes();
    let b = b.as_bytes();

    // Constant-time length check — no early exit.
    let len_eq = a.len().ct_eq(&b.len());

    // Iterate over `a` (the trusted stored token) so the loop count is fixed
    // at the server-side token length, regardless of what the caller submits
    // as `b`.  Callers pass the attacker-controlled value as `b`, so iterating
    // over `a` ensures every submission — short or long — executes the same
    // amount of work.  Out-of-range positions in `b` use the sentinel 0xFF,
    // which can never match a valid ASCII/UTF-8 token byte.
    let mut bytes_eq = Choice::from(1u8);
    for (i, &a_byte) in a.iter().enumerate() {
        let b_byte = *b.get(i).unwrap_or(&0xFF);
        bytes_eq &= a_byte.ct_eq(&b_byte);
    }

    (len_eq & bytes_eq).into()
}

/// Extract the CSRF cookie value from the Cookie header.
fn extract_cookie_token(req_headers: &http::HeaderMap, cookie_name: &str) -> Option<String> {
    let mut found_token = None;

    for cookie_header in &req_headers.get_all(http::header::COOKIE) {
        let Ok(cookie_str) = cookie_header.to_str() else {
            continue;
        };

        for pair in cookie_str.split(';') {
            let pair = pair.trim();
            let Some((name, value)) = pair.split_once('=') else {
                continue;
            };

            if name.trim() != cookie_name {
                continue;
            }

            if found_token.is_some() {
                // Multiple cookies with the same name found.
                // This indicates a potential Cookie Tossing attack!
                // Reject by returning None.
                return None;
            }

            found_token = Some(value.trim().to_owned());
        }
    }

    found_token
}

impl<S, ResBody> Service<Request<axum::body::Body>> for CsrfService<S>
where
    S: Service<Request<axum::body::Body>, Response = Response<ResBody>> + Clone + Send + 'static,
    S::Future: Send + 'static,
    S::Error: Send + 'static,
    ResBody: From<&'static str> + From<String> + Default + Send + 'static,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, mut req: Request<axum::body::Body>) -> Self::Future {
        // Match exemptions against the normalized path so dot-segment tricks
        // like `/api/../submit` (or percent-encoded `%2e%2e` variants) cannot
        // satisfy an `/api/` exemption prefix while targeting another route.
        let clean = crate::security::path::clean_path(req.uri().path());
        let path = clean.as_str();
        let is_exempt = self.settings.exempt_paths.iter().any(|prefix| {
            if path == prefix {
                true
            } else if let Some(stripped) = path.strip_prefix(prefix) {
                prefix.ends_with('/') || stripped.starts_with('/')
            } else {
                false
            }
        });
        let is_safe = is_exempt || self.settings.safe_methods.contains(req.method());
        let raw_cookie_token = extract_cookie_token(req.headers(), &self.settings.cookie_name);

        // When signing is active, discard any cookie that fails HMAC verification
        // (unsigned pre-upgrade cookies, removed-key cookies, etc.) so a fresh signed
        // token is minted and the Set-Cookie header refreshes the browser value.
        let cookie_token = match (&raw_cookie_token, &self.settings.signing_keys) {
            (Some(tok), Some(_)) if !validate_cookie_token_hmac(tok, &self.settings) => None,
            _ => raw_cookie_token.clone(),
        };

        // Generate a new token if none exists in the cookie.
        // When signing keys are active, the token is {uuid}.{hmac_hex}.
        let token = cookie_token.clone().unwrap_or_else(|| {
            let raw = Uuid::new_v4().to_string();
            if let Some(keys) = &self.settings.signing_keys {
                let sig = keys.sign(raw.as_bytes());
                format!("{raw}.{sig}")
            } else {
                raw
            }
        });

        // Insert CsrfToken, the configured form field name, and the configured
        // token header name into request extensions.
        req.extensions_mut().insert(CsrfToken(token.clone()));
        req.extensions_mut()
            .insert(CsrfFormField(self.settings.form_field.clone()));
        req.extensions_mut().insert(CsrfTokenHeader(
            self.settings.token_header.as_str().to_owned(),
        ));

        // Check if we need to set a cookie
        let set_cookie = if cookie_token.is_none() {
            Some(format!(
                "{}={}; Path=/; SameSite=Lax; HttpOnly",
                self.settings.cookie_name, token
            ))
        } else {
            None
        };

        let settings = Arc::clone(&self.settings);
        let mut inner = self.inner.clone();

        // Swap to ensure correct poll_ready semantics
        std::mem::swap(&mut self.inner, &mut inner);

        Box::pin(async move {
            if !is_safe {
                let verdict = verify_csrf_token(&mut req, &settings, cookie_token.as_deref()).await;
                if !matches!(verdict, CsrfVerdict::Valid) {
                    let request_id = req
                        .extensions()
                        .get::<crate::middleware::RequestId>()
                        .map(std::string::ToString::to_string);
                    let instance = Some(req.uri().path().to_owned());
                    let prefers_problem = wants_problem_details(req.headers());

                    // Missing/invalid token (including a token beyond the scanned
                    // prefix) → 403. Genuinely oversized bodies stream through and
                    // are rejected downstream by the real body / upload limits.
                    let message = CSRF_FORBIDDEN_MESSAGE;

                    if prefers_problem {
                        return Ok(csrf_problem_response(message, request_id, instance));
                    }

                    let mut response = Response::new(ResBody::from(message));
                    *response.status_mut() = StatusCode::FORBIDDEN;
                    response.headers_mut().insert(
                        http::header::CONTENT_TYPE,
                        http::HeaderValue::from_static("text/plain; charset=utf-8"),
                    );
                    return Ok(response);
                }
            }

            // Validation passed (or method is safe)
            let mut response = inner.call(req).await?;

            if let Some(cookie) = set_cookie
                && let Ok(val) = http::header::HeaderValue::from_str(&cookie)
            {
                response.headers_mut().append(http::header::SET_COOKIE, val);
            }

            Ok(response)
        })
    }
}

fn wants_problem_details(headers: &http::HeaderMap) -> bool {
    !crate::middleware::error_page_filter::accept_prefers_html(headers)
}

fn csrf_problem_response<ResBody: From<String> + Default>(
    message: &str,
    request_id: Option<String>,
    instance: Option<String>,
) -> Response<ResBody> {
    let mut problem = crate::error::problem_details(
        StatusCode::FORBIDDEN,
        message.to_owned(),
        None,
        Some("https://autumn.dev/problems/csrf"),
        request_id,
        instance,
        true,
    );
    "autumn.csrf".clone_into(&mut problem.code);
    let body = crate::error::problem_details_to_json_string(&problem);

    Response::builder()
        .status(StatusCode::FORBIDDEN)
        .header(http::header::CONTENT_TYPE, "application/problem+json")
        .body(ResBody::from(body))
        .unwrap_or_default()
}

/// Validate a CSRF cookie token's HMAC when signing is active.
///
/// Returns `false` when signing keys are set but the token is unsigned or carries
/// an invalid HMAC (catches tampered or pre-rotation unsigned tokens).
fn validate_cookie_token_hmac(cookie_token: &str, settings: &CsrfSettings) -> bool {
    let Some(keys) = &settings.signing_keys else {
        return true; // signing not active — accept raw token
    };
    // Signed format: "{uuid}.{hmac_hex}"
    let Some((uuid_part, sig)) = cookie_token.split_once('.') else {
        return false; // unsigned token rejected when signing is required
    };
    keys.verify(uuid_part.as_bytes(), sig)
}

/// Return the byte position of the first occurrence of `needle` in `haystack`.
fn find_bytes(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    if needle.is_empty() {
        return Some(0);
    }
    haystack.windows(needle.len()).position(|w| w == needle)
}

/// Scan a buffered `multipart/form-data` body for a named text field.
///
/// Returns the field value as a `&str` slice into `bytes`, or `None` when the
/// field is absent or the body is malformed / truncated.  Callers pre-limit the
/// buffer via `max_scan_bytes` so we never allocate more than that.
fn scan_multipart_field<'a>(bytes: &'a [u8], boundary: &str, field_name: &str) -> Option<&'a str> {
    let delimiter = format!("--{boundary}");
    let delim = delimiter.as_bytes();
    let end_marker = format!("\r\n{delimiter}");
    let end_bytes = end_marker.as_bytes();
    let mut pos = 0;

    loop {
        let rel = find_bytes(&bytes[pos..], delim)?;
        pos += rel + delim.len();

        // After the boundary: \r\n begins a part; anything else ends the multipart.
        match bytes.get(pos..pos + 2) {
            Some(b"\r\n") => pos += 2,
            _ => break, // final boundary (--), truncated, or malformed
        }

        let header_end = find_bytes(&bytes[pos..], b"\r\n\r\n")?;
        let headers = std::str::from_utf8(&bytes[pos..pos + header_end]).ok()?;
        let value_start = pos + header_end + 4;

        let is_match = headers.lines().any(|line| {
            if !line
                .to_ascii_lowercase()
                .starts_with("content-disposition:")
            {
                return false;
            }
            line.split(';').skip(1).any(|attr| {
                attr.trim()
                    .strip_prefix("name=")
                    .map(|v| v.trim_matches('"'))
                    == Some(field_name)
            })
        });

        if is_match {
            let end = find_bytes(&bytes[value_start..], end_bytes)
                .map_or(bytes.len(), |i| value_start + i);
            return std::str::from_utf8(&bytes[value_start..end]).ok();
        }

        let next = find_bytes(&bytes[value_start..], end_bytes)?;
        // Advance to the start of the boundary delimiter (skip only the leading
        // \r\n of end_bytes so the next loop iteration finds --boundary at
        // rel=0 and processes it normally).
        pos = value_start + next + 2;
    }

    None
}

async fn verify_csrf_token(
    req: &mut Request<axum::body::Body>,
    settings: &CsrfSettings,
    cookie_token: Option<&str>,
) -> CsrfVerdict {
    let mut token_found = false;

    // 1. Check header
    let header_token = req
        .headers()
        .get(&settings.token_header)
        .and_then(|v| v.to_str().ok());

    if let (Some(c), Some(h)) = (cookie_token, header_token)
        && !c.is_empty()
        && !h.is_empty()
        && validate_cookie_token_hmac(c, settings)
        && constant_time_eq(c, h)
    {
        token_found = true;
    }

    if token_found {
        return CsrfVerdict::Valid;
    }

    // 1b. Check query parameter (e.g. `_csrf`) before falling back to body
    let query_token = req.uri().query().and_then(|q| {
        url::form_urlencoded::parse(q.as_bytes())
            .find(|(key, _)| key == "_csrf" || key == settings.form_field.as_str())
            .map(|(_, val)| val.into_owned())
    });

    if let (Some(c), Some(q)) = (cookie_token, &query_token)
        && !c.is_empty()
        && !q.is_empty()
        && validate_cookie_token_hmac(c, settings)
        && constant_time_eq(c, q)
    {
        token_found = true;
    }

    if token_found {
        return CsrfVerdict::Valid;
    }

    // 2. Check form field (if not found in header)
    let content_type = req
        .headers()
        .get(http::header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .unwrap_or_default();

    // Media types are case-insensitive (RFC 9110 8.3.1) and the header may carry
    // leading whitespace; normalize the type token for the urlencoded check.
    let is_urlencoded = content_type
        .trim_start()
        .to_ascii_lowercase()
        .starts_with("application/x-www-form-urlencoded");
    // Parse the boundary with `multer::parse_boundary` — the exact parser
    // `axum::extract::Multipart` uses downstream (via `mime`) — so this CSRF
    // guard and the extractor can never disagree about the boundary, and it
    // matches the sibling `submit_token` replay guard. A hand-rolled
    // `split(';')` diverges on quoted values: `mime` permits a `;` inside a
    // quoted parameter value, so `boundary="x;y"` parses to the boundary `x;y`
    // in the real extractor while a split truncates it to `x`, so the `_csrf`
    // field is never located and a legitimate form is wrongly rejected (403).
    // `parse_boundary` is case-insensitive on the media type / `boundary` param
    // NAME and preserves the boundary VALUE's case (RFC 2046); it returns `Err`
    // for a non-multipart type, so `.ok()` yields `None`.
    let multipart_boundary = multer::parse_boundary(content_type).ok();
    // NLL: content_type borrow ends here; req.body_mut() is safe to call below.

    if !is_urlencoded && multipart_boundary.is_none() {
        return CsrfVerdict::Missing;
    }

    // Take the body, buffer at most `max_scan_bytes` of it into a scan prefix,
    // and reconstruct the full, unmodified body so downstream handlers still
    // receive every byte. When the body is larger than the cap, the tail is
    // *streamed* through rather than buffered — the CSRF layer never forces a
    // large upload into memory.
    let body = std::mem::replace(req.body_mut(), axum::body::Body::empty());

    let (prefix, rebuilt) = match collect_body_prefix(body, settings.max_scan_bytes).await {
        CollectedBody::Full(bytes) => {
            let rebuilt = Body::from(bytes.clone());
            (bytes, rebuilt)
        }
        CollectedBody::Oversized { prefix, body } => (prefix, body),
        CollectedBody::Errored(err) => {
            // The body stream errored mid-read (e.g. a client disconnect). We
            // cannot losslessly reconstruct it, and a token cannot be confirmed,
            // so we preserve the pre-existing behavior of treating an unreadable
            // body as a missing token (→ 403). The request is rejected and the
            // handler never runs, so the discarded body is immaterial.
            tracing::debug!(error = %err, "CSRF token scan: body read error, treating as missing token");
            return CsrfVerdict::Missing;
        }
    };

    if is_urlencoded {
        for (key, value) in url::form_urlencoded::parse(&prefix) {
            if key == settings.form_field {
                if let Some(c) = cookie_token
                    && !c.is_empty()
                    && !value.is_empty()
                    && validate_cookie_token_hmac(c, settings)
                    && constant_time_eq(c, value.as_ref())
                {
                    token_found = true;
                }
                break;
            }
        }
    } else if let Some(ref boundary) = multipart_boundary {
        #[allow(clippy::collapsible_if)]
        if let Some(value) = scan_multipart_field(&prefix, boundary, &settings.form_field) {
            if let Some(c) = cookie_token
                && !c.is_empty()
                && !value.is_empty()
                && validate_cookie_token_hmac(c, settings)
                && constant_time_eq(c, value)
            {
                token_found = true;
            }
        }
    }

    // Restore the full body so downstream handlers (e.g. the Multipart
    // extractor) read it intact — identical bytes and framing.
    *req.body_mut() = rebuilt;

    if token_found {
        CsrfVerdict::Valid
    } else {
        CsrfVerdict::Missing
    }
}

/// Body buffered up to a bounded scan prefix, plus a reconstruction of the full
/// body for downstream handlers. Mirrors the `collect_body` pattern in
/// [`submit_token`](crate::security::submit_token) so both middlewares scan a
/// bounded prefix and stream the remainder identically.
enum CollectedBody {
    /// The whole body fit within the cap and is fully buffered. The same bytes
    /// serve as both the scan prefix and the rebuilt body.
    Full(Bytes),
    /// The body exceeded the cap. `prefix` is the first `limit` bytes (the scan
    /// window); `body` replays the complete, unmodified body — the buffered
    /// prefix bytes plus the over-limit chunk and the remaining stream — so the
    /// handler receives every byte with the tail streamed rather than buffered.
    Oversized { prefix: Bytes, body: Body },
    /// The body stream errored before EOF. The bytes read so far are discarded:
    /// the caller rejects the request rather than forward a truncated body.
    Errored(axum::Error),
}

/// Buffer `body` up to `limit` bytes into a scan prefix without failing when the
/// body is larger, reconstructing the full body for pass-through.
async fn collect_body_prefix(body: Body, limit: usize) -> CollectedBody {
    let mut buf = Vec::<u8>::new();
    let mut stream = body.into_data_stream();
    loop {
        match stream.next().await {
            None => break,
            Some(Err(err)) => return CollectedBody::Errored(err),
            Some(Ok(chunk)) => {
                let remaining = limit.saturating_sub(buf.len());
                if chunk.len() > remaining {
                    // Fill the scan prefix up to `limit` with the leading bytes
                    // of the over-limit chunk, so a token at the front of the
                    // form is still found even when the FIRST chunk already
                    // exceeds the cap (e.g. an upstream middleware rebuilt the
                    // body as one `Body::from(bytes)`, leaving `buf` empty here).
                    let mut prefix_buf = buf.clone();
                    prefix_buf.extend_from_slice(&chunk[..remaining]);
                    let prefix = Bytes::from(prefix_buf);
                    // Replay the FULL body unchanged: the buffered prefix bytes
                    // followed by the *complete* over-limit chunk (not just its
                    // scanned head) and the rest of the stream. The prefix is
                    // only for locating the token; the handler must receive every
                    // byte, and the tail streams through unbuffered.
                    let mut leading = Vec::with_capacity(2);
                    if !buf.is_empty() {
                        leading.push(Ok::<Bytes, axum::Error>(Bytes::from(buf)));
                    }
                    leading.push(Ok::<Bytes, axum::Error>(chunk));
                    let body = Body::from_stream(futures::stream::iter(leading).chain(stream));
                    return CollectedBody::Oversized { prefix, body };
                }
                buf.extend_from_slice(&chunk);
            }
        }
    }
    CollectedBody::Full(Bytes::from(buf))
}

#[cfg(test)]
mod tests {
    #[tokio::test]
    async fn post_with_url_encoded_token_passes() {
        let raw_token = "abc+123/xyz=456";
        let encoded_token = "abc%2B123%2Fxyz%3D456";
        let app = Router::new()
            .route("/submit", post(|| async { "created" }))
            .layer(CsrfLayer::from_config(&default_csrf_config()));

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/submit")
                    .header("Cookie", format!("autumn-csrf={raw_token}"))
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .body(Body::from(format!("_csrf={encoded_token}")))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn post_with_query_param_token_passes() {
        let raw_token = "abc+123/xyz=456";
        let encoded_token = "abc%2B123%2Fxyz%3D456";
        let app = Router::new()
            .route("/submit", post(|| async { "created" }))
            .layer(CsrfLayer::from_config(&default_csrf_config()));

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri(format!("/submit?_csrf={encoded_token}"))
                    .header("Cookie", format!("autumn-csrf={raw_token}"))
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    use super::*;
    use axum::Router;
    use axum::body::Body;
    use axum::routing::{get, post};
    use std::fmt::Write as _;
    use tower::ServiceExt;

    fn default_csrf_config() -> CsrfConfig {
        CsrfConfig {
            enabled: true,
            ..Default::default()
        }
    }

    /// An enabled CSRF config with a custom body-token scan-prefix cap, used to
    /// exercise the bounded-prefix scan boundary without allocating multi-MiB
    /// bodies.
    fn csrf_config_with_scan_bytes(n: usize) -> CsrfConfig {
        CsrfConfig {
            enabled: true,
            token_scan_bytes: n,
            ..Default::default()
        }
    }

    #[tokio::test]
    async fn safe_method_passes_without_token() {
        let app = Router::new()
            .route("/", get(|| async { "ok" }))
            .layer(CsrfLayer::from_config(&default_csrf_config()));

        let response = app
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri("/")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn safe_method_sets_csrf_cookie() {
        let app = Router::new()
            .route("/", get(|| async { "ok" }))
            .layer(CsrfLayer::from_config(&default_csrf_config()));

        let response = app
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri("/")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        let set_cookie = response
            .headers()
            .get("set-cookie")
            .unwrap()
            .to_str()
            .unwrap();
        assert!(set_cookie.starts_with("autumn-csrf="));
        assert!(set_cookie.contains("HttpOnly"));
    }

    #[tokio::test]
    async fn post_without_token_returns_403() {
        let app = Router::new()
            .route("/submit", post(|| async { "created" }))
            .layer(CsrfLayer::from_config(&default_csrf_config()));

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/submit")
                    .header(http::header::ACCEPT, "text/html")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn forbidden_response_has_clear_error_body() {
        let app = Router::new()
            .route("/submit", post(|| async { "created" }))
            .layer(CsrfLayer::from_config(&default_csrf_config()));

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/submit")
                    .header(http::header::ACCEPT, "text/html")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::FORBIDDEN);
        assert_eq!(
            response
                .headers()
                .get(http::header::CONTENT_TYPE)
                .map(|v| v.to_str().unwrap_or_default()),
            Some("text/plain; charset=utf-8")
        );
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let text = std::str::from_utf8(&body).unwrap();
        assert!(
            text.contains("CSRF"),
            "expected CSRF error message, got: {text:?}"
        );
    }

    #[tokio::test]
    async fn exempt_path_skips_csrf_validation() {
        let config = CsrfConfig {
            enabled: true,
            exempt_paths: vec!["/api/".to_string()],
            ..Default::default()
        };
        let app = Router::new()
            .route("/api/items", post(|| async { "created" }))
            .route("/form/submit", post(|| async { "created" }))
            .layer(CsrfLayer::from_config(&config));

        // Exempt API path: POST with no token should succeed.
        let response = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/api/items")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);

        // Non-exempt form path: POST with no token should still be blocked.
        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/form/submit")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn exempt_path_exact_or_subtree_only() {
        let config = CsrfConfig {
            enabled: true,
            exempt_paths: vec!["/webhooks/stripe".to_string()],
            ..Default::default()
        };
        let app = Router::new()
            .route("/webhooks/stripe", post(|| async { "stripe" }))
            .route(
                "/webhooks/stripe/events",
                post(|| async { "stripe events" }),
            )
            .route("/webhooks/stripe-admin", post(|| async { "stripe admin" }))
            .layer(CsrfLayer::from_config(&config));

        // Exact match of exempt path should skip CSRF validation
        let response = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/webhooks/stripe")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);

        // Slash-delimited subtree of exempt path should skip CSRF validation
        let response = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/webhooks/stripe/events")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);

        // Unrelated path starting with same prefix should NOT skip CSRF validation
        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/webhooks/stripe-admin")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn post_with_valid_token_passes() {
        let token = Uuid::new_v4().to_string();
        let app = Router::new()
            .route("/submit", post(|| async { "created" }))
            .layer(CsrfLayer::from_config(&default_csrf_config()));

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/submit")
                    .header("Cookie", format!("autumn-csrf={token}"))
                    .header("X-CSRF-Token", &token)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn post_with_mismatched_token_returns_403() {
        let cookie_token = Uuid::new_v4().to_string();
        let header_token = Uuid::new_v4().to_string();
        let app = Router::new()
            .route("/submit", post(|| async { "created" }))
            .layer(CsrfLayer::from_config(&default_csrf_config()));

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/submit")
                    .header("Cookie", format!("autumn-csrf={cookie_token}"))
                    .header("X-CSRF-Token", &header_token)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn csrf_token_extractor_works() {
        async fn handler(csrf: CsrfToken) -> String {
            csrf.token().to_owned()
        }

        let app = Router::new()
            .route("/", get(handler))
            .layer(CsrfLayer::from_config(&default_csrf_config()));

        let response = app
            .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let token_str = String::from_utf8(body.to_vec()).unwrap();
        assert!(Uuid::parse_str(&token_str).is_ok());
    }

    #[test]
    fn extract_cookie_from_header() {
        let mut headers = http::HeaderMap::new();
        headers.insert(
            http::header::COOKIE,
            "autumn-csrf=abc123; other=xyz".parse().unwrap(),
        );
        assert_eq!(
            extract_cookie_token(&headers, "autumn-csrf"),
            Some("abc123".to_owned())
        );
    }

    #[test]
    fn missing_cookie_returns_none() {
        let headers = http::HeaderMap::new();
        assert_eq!(extract_cookie_token(&headers, "autumn-csrf"), None);
    }

    #[test]
    fn extract_cookie_rejects_multiple_cookies() {
        // Multiple cookies with the same name in a single header
        let mut headers = http::HeaderMap::new();
        headers.insert(
            http::header::COOKIE,
            "autumn-csrf=abc123; autumn-csrf=xyz456".parse().unwrap(),
        );
        assert_eq!(extract_cookie_token(&headers, "autumn-csrf"), None);

        // Multiple headers with the same cookie
        let mut headers2 = http::HeaderMap::new();
        headers2.append(http::header::COOKIE, "autumn-csrf=abc123".parse().unwrap());
        headers2.append(http::header::COOKIE, "autumn-csrf=xyz456".parse().unwrap());
        assert_eq!(extract_cookie_token(&headers2, "autumn-csrf"), None);
    }

    #[test]
    fn extract_cookie_ignores_malformed_cookies() {
        let mut headers = http::HeaderMap::new();
        // Missing '='
        headers.insert(http::header::COOKIE, "autumn-csrf abc123".parse().unwrap());
        assert_eq!(extract_cookie_token(&headers, "autumn-csrf"), None);

        // Multiple spaces
        headers.insert(
            http::header::COOKIE,
            "   autumn-csrf  =  abc123  ; other=xyz".parse().unwrap(),
        );
        assert_eq!(
            extract_cookie_token(&headers, "autumn-csrf"),
            Some("abc123".to_owned())
        );
    }

    #[test]
    fn test_constant_time_eq() {
        assert!(super::constant_time_eq("abc", "abc"));
        assert!(!super::constant_time_eq("abc", "ab"));
        assert!(!super::constant_time_eq("abc", "abd"));
        assert!(super::constant_time_eq("", ""));
        assert!(!super::constant_time_eq("a", "b"));
        assert!(!super::constant_time_eq("a", "A"));
    }

    #[tokio::test]
    async fn post_with_empty_cookie_but_valid_header() {
        let token = Uuid::new_v4().to_string();
        let app = Router::new()
            .route("/submit", post(|| async { "created" }))
            .layer(CsrfLayer::from_config(&default_csrf_config()));

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/submit")
                    .header("Cookie", "autumn-csrf=")
                    .header("X-CSRF-Token", &token)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn post_with_valid_cookie_but_empty_header() {
        let token = Uuid::new_v4().to_string();
        let app = Router::new()
            .route("/submit", post(|| async { "created" }))
            .layer(CsrfLayer::from_config(&default_csrf_config()));

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/submit")
                    .header("Cookie", format!("autumn-csrf={token}"))
                    .header("X-CSRF-Token", "")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn post_with_empty_cookie_but_valid_form_field() {
        let token = Uuid::new_v4().to_string();
        let app = Router::new()
            .route("/submit", post(|| async { "created" }))
            .layer(CsrfLayer::from_config(&default_csrf_config()));

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/submit")
                    .header("Cookie", "autumn-csrf=")
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .body(Body::from(format!("_csrf={token}")))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn post_with_valid_cookie_but_empty_form_field() {
        let token = Uuid::new_v4().to_string();
        let app = Router::new()
            .route("/submit", post(|| async { "created" }))
            .layer(CsrfLayer::from_config(&default_csrf_config()));

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/submit")
                    .header("Cookie", format!("autumn-csrf={token}"))
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .body(Body::from("_csrf="))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn post_with_large_urlencoded_body_token_first_streams_and_passes() {
        // A urlencoded body far larger than the scan prefix, with `_csrf` FIRST.
        // The token is located in the prefix (→ pass) and the full body still
        // reaches the handler intact — the tail streams through unbuffered.
        async fn echo_len(body: Body) -> String {
            let bytes = axum::body::to_bytes(body, usize::MAX).await.unwrap();
            bytes.len().to_string()
        }

        let token = Uuid::new_v4().to_string();
        let large_padding = "a".repeat(256 * 1024);
        let body_content = format!("_csrf={token}&pad={large_padding}");
        let full_len = body_content.len();

        // 4 KiB prefix cap: `_csrf=...` is well within it, the body is not.
        let app = Router::new()
            .route("/submit", post(echo_len))
            .layer(CsrfLayer::from_config(&csrf_config_with_scan_bytes(4096)));

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/submit")
                    .header("Cookie", format!("autumn-csrf={token}"))
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .body(Body::from(body_content))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let echoed = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let received: usize = std::str::from_utf8(&echoed).unwrap().parse().unwrap();
        assert_eq!(
            received, full_len,
            "handler must receive the full, unmodified body (tail streamed through)"
        );
    }

    #[tokio::test]
    async fn post_with_empty_tokens_returns_403() {
        let app = Router::new()
            .route("/submit", post(|| async { "created" }))
            .layer(CsrfLayer::from_config(&CsrfConfig {
                enabled: true,
                ..Default::default()
            }));

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/submit")
                    .header("Cookie", "autumn-csrf=")
                    .header("X-CSRF-Token", "")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn post_with_empty_form_tokens_returns_403() {
        let app = Router::new()
            .route("/submit", post(|| async { "created" }))
            .layer(CsrfLayer::from_config(&CsrfConfig {
                enabled: true,
                ..Default::default()
            }));

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/submit")
                    .header("Cookie", "autumn-csrf=")
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .body(Body::from("_csrf="))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::FORBIDDEN);
    }

    #[test]
    fn from_config_filters_invalid_methods() {
        let config = CsrfConfig {
            safe_methods: vec![
                "GET".to_string(),
                "INVALID METHOD".to_string(),
                "POST".to_string(),
            ],
            ..Default::default()
        };
        let layer = CsrfLayer::from_config(&config);
        assert_eq!(layer.settings.safe_methods.len(), 2);
        assert!(layer.settings.safe_methods.contains(&http::Method::GET));
        assert!(layer.settings.safe_methods.contains(&http::Method::POST));
    }

    #[test]
    fn with_max_scan_bytes_clamps_effective_scan_cap_below_prefix() {
        // Operator lowered the global body limit (64 KiB) below the CSRF prefix
        // cap (2 MiB default). The router clamps the effective scan cap to
        // min(token_scan_bytes, max_request_size_bytes) = 64 KiB, so the CSRF
        // layer never buffers more than the global body limit.
        let token_scan_bytes = default_csrf_config().token_scan_bytes; // 2 MiB
        let max_request_size_bytes = 64 * 1024; // 64 KiB
        let effective = token_scan_bytes.min(max_request_size_bytes);

        let layer = CsrfLayer::from_config(&default_csrf_config()).with_max_scan_bytes(effective);

        assert_eq!(layer.settings.max_scan_bytes, 64 * 1024);
    }

    #[test]
    fn with_max_scan_bytes_preserves_small_prefix_in_normal_case() {
        // Normal/high-upload case: a large max_request_size_bytes (32 MiB
        // default) must NOT raise the effective cap — the small token_scan_bytes
        // prefix (2 MiB) stays the primary bound via `min`.
        let token_scan_bytes = default_csrf_config().token_scan_bytes; // 2 MiB
        let max_request_size_bytes = 32 * 1024 * 1024; // 32 MiB
        let effective = token_scan_bytes.min(max_request_size_bytes);

        let layer = CsrfLayer::from_config(&default_csrf_config()).with_max_scan_bytes(effective);

        assert_eq!(layer.settings.max_scan_bytes, token_scan_bytes);
        assert_eq!(layer.settings.max_scan_bytes, 2 * 1024 * 1024);
    }

    #[test]
    fn from_config_handles_invalid_header_name() {
        let config = CsrfConfig {
            token_header: "Invalid Header Name\n".to_string(),
            ..Default::default()
        };
        let layer = CsrfLayer::from_config(&config);
        assert_eq!(layer.settings.token_header.as_str(), "x-csrf-token");
    }

    // ── Signed CSRF tokens (RED phase) ────────────────────────────────────

    #[tokio::test]
    async fn csrf_token_is_hmac_signed_when_keys_set() {
        use crate::security::config::{SigningSecretConfig, resolve_signing_keys};
        use std::sync::Arc;

        let keys = Arc::new(resolve_signing_keys(&SigningSecretConfig {
            secret: Some("k".repeat(32)),
            previous_secrets: vec![],
        }));
        let layer = CsrfLayer::from_config(&default_csrf_config()).with_signing_keys(keys);

        let app = Router::new()
            .route("/", get(|| async { "ok" }))
            .layer(layer);

        let resp = app
            .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
            .await
            .unwrap();

        let set_cookie = resp
            .headers()
            .get("set-cookie")
            .expect("should set CSRF cookie")
            .to_str()
            .unwrap();
        let cookie_value = set_cookie
            .split('=')
            .nth(1)
            .unwrap()
            .split(';')
            .next()
            .unwrap()
            .trim();

        assert!(
            cookie_value.contains('.'),
            "signed CSRF cookie must be {{uuid}}.{{hmac}}, got: {cookie_value}"
        );
        let (_uuid_part, sig_part) = cookie_value.split_once('.').unwrap();
        assert_eq!(sig_part.len(), 64, "HMAC hex must be 64 chars");
    }

    #[tokio::test]
    async fn csrf_signed_token_validates_on_post() {
        use crate::security::config::{SigningSecretConfig, resolve_signing_keys};
        use std::sync::Arc;

        let keys = Arc::new(resolve_signing_keys(&SigningSecretConfig {
            secret: Some("k".repeat(32)),
            previous_secrets: vec![],
        }));
        let layer = CsrfLayer::from_config(&default_csrf_config()).with_signing_keys(keys);

        let app = Router::new()
            .route("/", post(|| async { "created" }))
            .layer(layer);

        // Mint a valid signed token
        let config = SigningSecretConfig {
            secret: Some("k".repeat(32)),
            previous_secrets: vec![],
        };
        let signing_keys = resolve_signing_keys(&config);
        let uuid = uuid::Uuid::new_v4().to_string();
        let sig = signing_keys.sign(uuid.as_bytes());
        let signed_token = format!("{uuid}.{sig}");

        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/")
                    .header("Cookie", format!("autumn-csrf={signed_token}"))
                    .header("X-CSRF-Token", &signed_token)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn csrf_unsigned_token_rejected_when_signing_active() {
        use crate::security::config::{SigningSecretConfig, resolve_signing_keys};
        use std::sync::Arc;

        let keys = Arc::new(resolve_signing_keys(&SigningSecretConfig {
            secret: Some("k".repeat(32)),
            previous_secrets: vec![],
        }));
        let layer = CsrfLayer::from_config(&default_csrf_config()).with_signing_keys(keys);

        let app = Router::new()
            .route("/", post(|| async { "created" }))
            .layer(layer);

        // Raw UUID without HMAC — should be rejected when signing is active
        let raw_token = uuid::Uuid::new_v4().to_string();
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/")
                    .header("Cookie", format!("autumn-csrf={raw_token}"))
                    .header("X-CSRF-Token", &raw_token)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(
            resp.status(),
            StatusCode::FORBIDDEN,
            "unsigned CSRF token must be rejected when signing is active"
        );
    }

    #[tokio::test]
    async fn csrf_previous_key_signed_token_accepted() {
        use crate::security::config::{
            ResolvedSigningKeys, SigningSecretConfig, resolve_signing_keys,
        };
        use std::sync::Arc;

        let old_secret = "old-key".repeat(5); // 35 bytes
        let old_keys = resolve_signing_keys(&SigningSecretConfig {
            secret: Some(old_secret.clone()),
            previous_secrets: vec![],
        });

        let uuid = uuid::Uuid::new_v4().to_string();
        let old_sig = old_keys.sign(uuid.as_bytes());
        let old_signed_token = format!("{uuid}.{old_sig}");

        let new_keys = Arc::new(ResolvedSigningKeys::new(
            "new-key".repeat(5).into_bytes(),
            vec![old_secret.into_bytes()],
        ));
        let layer = CsrfLayer::from_config(&default_csrf_config()).with_signing_keys(new_keys);

        let app = Router::new()
            .route("/", post(|| async { "created" }))
            .layer(layer);

        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/")
                    .header("Cookie", format!("autumn-csrf={old_signed_token}"))
                    .header("X-CSRF-Token", &old_signed_token)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(
            resp.status(),
            StatusCode::OK,
            "previous-key-signed CSRF token must pass during grace window"
        );
    }

    fn multipart_body(boundary: &str, fields: &[(&str, &str)]) -> String {
        let mut body = String::new();
        for (name, value) in fields {
            let _ = write!(
                body,
                "--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n"
            );
        }
        let _ = write!(body, "--{boundary}--\r\n");
        body
    }

    #[tokio::test]
    async fn post_multipart_with_csrf_field_passes() {
        let token = "test-csrf-token-uuid-1234";
        let boundary = "----WebKitFormBoundaryABC123";
        let body = multipart_body(boundary, &[("_csrf", token), ("name", "alice")]);
        let app = Router::new()
            .route("/upload", post(|| async { "ok" }))
            .layer(CsrfLayer::from_config(&default_csrf_config()));

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/upload")
                    .header("Cookie", format!("autumn-csrf={token}"))
                    .header(
                        "Content-Type",
                        format!("multipart/form-data; boundary={boundary}"),
                    )
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn post_multipart_csrf_field_after_other_field_passes() {
        // Regression: skipping a non-matching part must not advance pos past
        // the next part's headers (the +2 fix in scan_multipart_field).
        let token = "test-csrf-token-uuid-after";
        let boundary = "----WebKitFormBoundaryORDER";
        let body = multipart_body(boundary, &[("name", "alice"), ("_csrf", token)]);
        let app = Router::new()
            .route("/upload", post(|| async { "ok" }))
            .layer(CsrfLayer::from_config(&default_csrf_config()));

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/upload")
                    .header("Cookie", format!("autumn-csrf={token}"))
                    .header(
                        "Content-Type",
                        format!("multipart/form-data; boundary={boundary}"),
                    )
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn post_multipart_csrf_field_first_with_file_passes() {
        let token = "test-csrf-token-uuid-5678";
        let boundary = "----WebKitFormBoundaryDEF456";
        // _csrf first, then binary file field
        let mut body = format!(
            "--{boundary}\r\nContent-Disposition: form-data; name=\"_csrf\"\r\n\r\n{token}\r\n"
        );
        let _ = write!(
            body,
            "--{boundary}\r\nContent-Disposition: form-data; name=\"avatar\"; filename=\"photo.jpg\"\r\nContent-Type: image/jpeg\r\n\r\nFAKEJPEGDATA\r\n"
        );
        let _ = write!(body, "--{boundary}--\r\n");

        let app = Router::new()
            .route("/upload", post(|| async { "ok" }))
            .layer(CsrfLayer::from_config(&default_csrf_config()));

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/upload")
                    .header("Cookie", format!("autumn-csrf={token}"))
                    .header(
                        "Content-Type",
                        format!("multipart/form-data; boundary={boundary}"),
                    )
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn post_multipart_without_csrf_field_rejected() {
        let boundary = "----WebKitFormBoundaryGHI789";
        let body = multipart_body(boundary, &[("file", "fakebytes")]);
        let app = Router::new()
            .route("/upload", post(|| async { "ok" }))
            .layer(CsrfLayer::from_config(&default_csrf_config()));

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/upload")
                    .header("Cookie", "autumn-csrf=sometoken")
                    .header(http::header::ACCEPT, "text/html")
                    .header(
                        "Content-Type",
                        format!("multipart/form-data; boundary={boundary}"),
                    )
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn post_multipart_with_wrong_csrf_token_rejected() {
        let boundary = "----WebKitFormBoundaryJKL012";
        let body = multipart_body(boundary, &[("_csrf", "wrong-token")]);
        let app = Router::new()
            .route("/upload", post(|| async { "ok" }))
            .layer(CsrfLayer::from_config(&default_csrf_config()));

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/upload")
                    .header("Cookie", "autumn-csrf=correct-token")
                    .header(http::header::ACCEPT, "text/html")
                    .header(
                        "Content-Type",
                        format!("multipart/form-data; boundary={boundary}"),
                    )
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::FORBIDDEN);
    }

    /// Build a multipart body larger than the legacy 2 MiB scan cap: a valid
    /// `_csrf` field positioned first, followed by a padded binary file field.
    fn large_multipart_body(boundary: &str, token: &str, pad_bytes: usize) -> Vec<u8> {
        let mut body = format!(
            "--{boundary}\r\nContent-Disposition: form-data; name=\"_csrf\"\r\n\r\n{token}\r\n"
        )
        .into_bytes();
        body.extend_from_slice(
            format!(
                "--{boundary}\r\nContent-Disposition: form-data; name=\"avatar\"; \
                 filename=\"photo.bin\"\r\nContent-Type: application/octet-stream\r\n\r\n"
            )
            .as_bytes(),
        );
        body.extend(std::iter::repeat_n(b'A', pad_bytes));
        body.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes());
        body
    }

    /// Build a multipart body with a large filler field placed BEFORE `_csrf`,
    /// so the token sits `lead_bytes`+ into the body (used to push it past a
    /// scan prefix). Returns `(body, full_len)`.
    fn multipart_token_after_filler(boundary: &str, token: &str, lead_bytes: usize) -> Vec<u8> {
        let mut body =
            format!("--{boundary}\r\nContent-Disposition: form-data; name=\"filler\"\r\n\r\n")
                .into_bytes();
        body.extend(std::iter::repeat_n(b'x', lead_bytes));
        body.extend_from_slice(
            format!(
                "\r\n--{boundary}\r\nContent-Disposition: form-data; \
                 name=\"_csrf\"\r\n\r\n{token}\r\n--{boundary}--\r\n"
            )
            .as_bytes(),
        );
        body
    }

    /// Stream-through regression (issue #1866 redesign). A multipart body far
    /// larger than the scan prefix, with `_csrf` as the FIRST field, must:
    ///   1. PASS CSRF — the token is located within the bounded prefix; and
    ///   2. deliver the FULL, unmodified body to the handler — proving the
    ///      remainder streamed through and the reconstruction is lossless.
    /// The scan itself stops at the cap by construction: the 4 KiB prefix cap is
    /// far smaller than the body, yet the request still passes and streams, so
    /// the layer cannot have buffered the whole body to find the token.
    #[tokio::test]
    async fn post_large_multipart_token_first_streams_full_body_and_passes() {
        async fn echo_len(body: Body) -> String {
            let bytes = axum::body::to_bytes(body, usize::MAX).await.unwrap();
            bytes.len().to_string()
        }

        let token = "test-csrf-token-uuid-stream";
        let boundary = "----WebKitFormBoundarySTREAM";
        // _csrf first, then a ~256 KiB file field — body far exceeds the cap.
        let body = large_multipart_body(boundary, token, 256 * 1024);
        let full_len = body.len();
        assert!(full_len > 4096);

        // 4 KiB prefix cap: the leading `_csrf` field is well within it.
        let app = Router::new()
            .route("/upload", post(echo_len))
            .layer(CsrfLayer::from_config(&csrf_config_with_scan_bytes(4096)));

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/upload")
                    .header("Cookie", format!("autumn-csrf={token}"))
                    .header(http::header::ACCEPT, "text/html")
                    .header(
                        "Content-Type",
                        format!("multipart/form-data; boundary={boundary}"),
                    )
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let echoed = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let received: usize = std::str::from_utf8(&echoed).unwrap().parse().unwrap();
        assert_eq!(
            received, full_len,
            "handler must receive the full, unmodified body (tail streamed through)"
        );
    }

    /// Token-early constraint. When `_csrf` sits AFTER more than `max_scan_bytes`
    /// of preceding data, it is not observed in the prefix and the request is
    /// rejected as a missing token (403) — NOT a 413. A genuinely oversized body
    /// is left to the downstream body / upload limits.
    #[tokio::test]
    async fn post_multipart_token_beyond_scan_prefix_returns_403() {
        let token = "test-csrf-token-uuid-beyond";
        let boundary = "----WebKitFormBoundaryBEYOND";
        // Default 2 MiB cap; place `_csrf` after > 2 MiB of filler.
        let body = multipart_token_after_filler(boundary, token, 2 * 1024 * 1024 + 1024);
        assert!(body.len() > 2 * 1024 * 1024);

        let app = Router::new()
            .route("/upload", post(|| async { "ok" }))
            .layer(CsrfLayer::from_config(&default_csrf_config()));

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/upload")
                    .header("Cookie", format!("autumn-csrf={token}"))
                    .header(http::header::ACCEPT, "text/html")
                    .header(
                        "Content-Type",
                        format!("multipart/form-data; boundary={boundary}"),
                    )
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::FORBIDDEN);
    }

    /// Configurable cap moves the scan boundary. The SAME body — with `_csrf`
    /// ~8 KiB into it — is rejected under a 4 KiB cap (token beyond the prefix)
    /// but accepted under a 64 KiB cap (token within the prefix).
    #[tokio::test]
    async fn configurable_scan_cap_moves_token_boundary() {
        let token = "test-csrf-token-uuid-cap";
        let boundary = "----WebKitFormBoundaryCAP";
        let body = multipart_token_after_filler(boundary, token, 8 * 1024);

        let make_request = || {
            Request::builder()
                .method("POST")
                .uri("/upload")
                .header("Cookie", format!("autumn-csrf={token}"))
                .header(http::header::ACCEPT, "text/html")
                .header(
                    "Content-Type",
                    format!("multipart/form-data; boundary={boundary}"),
                )
                .body(Body::from(body.clone()))
                .unwrap()
        };

        // Small 4 KiB cap: `_csrf` sits beyond the prefix → not found → 403.
        let small = Router::new()
            .route("/upload", post(|| async { "ok" }))
            .layer(CsrfLayer::from_config(&csrf_config_with_scan_bytes(
                4 * 1024,
            )));
        let resp = small.oneshot(make_request()).await.unwrap();
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);

        // Larger 64 KiB cap: the same `_csrf` now falls within the prefix → 200.
        let large = Router::new()
            .route("/upload", post(|| async { "ok" }))
            .layer(CsrfLayer::from_config(&csrf_config_with_scan_bytes(
                64 * 1024,
            )));
        let resp = large.oneshot(make_request()).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    // ── Case-insensitive Content-Type matching (RFC 9110 8.3.1) ───────────────

    #[tokio::test]
    async fn post_mixed_case_multipart_content_type_with_valid_token_passes() {
        // Media types are case-insensitive (RFC 9110 8.3.1); the Multipart
        // extractor accepts `Multipart/Form-Data` with a `Boundary=` parameter.
        // A valid `_csrf` field in such a body must be scanned and the request
        // ACCEPTED — a case-sensitive `starts_with("multipart/form-data")` gate
        // wrongly rejects it (403). The weird-case boundary VALUE is identical in
        // the header and the body delimiters, which also proves the boundary
        // VALUE stays case-sensitive (RFC 2046) while the media type / param NAME
        // are matched case-insensitively.
        let token = "test-csrf-token-uuid-mixedmp";
        let boundary = "BoUnDaRy-XyZ-123";
        let body = multipart_body(boundary, &[("_csrf", token), ("name", "alice")]);
        let app = Router::new()
            .route("/upload", post(|| async { "ok" }))
            .layer(CsrfLayer::from_config(&default_csrf_config()));

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/upload")
                    .header("Cookie", format!("autumn-csrf={token}"))
                    .header(http::header::ACCEPT, "text/html")
                    .header(
                        "Content-Type",
                        format!("Multipart/Form-Data; Boundary={boundary}"),
                    )
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn post_mixed_case_urlencoded_content_type_with_valid_token_passes() {
        // Media types are case-insensitive (RFC 9110 8.3.1). A urlencoded form
        // POST carrying a valid `_csrf` field with an upper/mixed-case
        // Content-Type (`Application/x-www-form-urlencoded`) must be ACCEPTED — a
        // case-sensitive `starts_with("application/x-www-form-urlencoded")` gate
        // wrongly rejects it (403), skipping body scanning entirely.
        let token = "test-csrf-token-uuid-mixeduenc";
        let app = Router::new()
            .route("/submit", post(|| async { "created" }))
            .layer(CsrfLayer::from_config(&default_csrf_config()));

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/submit")
                    .header("Cookie", format!("autumn-csrf={token}"))
                    .header(http::header::ACCEPT, "text/html")
                    .header("Content-Type", "Application/x-www-form-urlencoded")
                    .body(Body::from(format!("_csrf={token}")))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn post_multipart_quoted_boundary_with_semicolon_passes() {
        // `mime` permits a `;` inside a QUOTED boundary parameter value, so
        // `boundary="x;y"` parses to the boundary `x;y` in the real Multipart
        // extractor (via `multer`). A hand-rolled `split(';')` truncates it to
        // `x`, so the `_csrf` field is never located and the request is wrongly
        // rejected (403). Parsing with `multer::parse_boundary` — the exact
        // parser the extractor uses — keeps the guard and the extractor in
        // agreement, so the valid token is found and the request ACCEPTED.
        let token = "test-csrf-token-uuid-quotedsemi";
        let boundary = "x;y";
        let body = multipart_body(boundary, &[("_csrf", token), ("name", "alice")]);
        let app = Router::new()
            .route("/upload", post(|| async { "ok" }))
            .layer(CsrfLayer::from_config(&default_csrf_config()));

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/upload")
                    .header("Cookie", format!("autumn-csrf={token}"))
                    .header(http::header::ACCEPT, "text/html")
                    .header(
                        "Content-Type",
                        format!("multipart/form-data; boundary=\"{boundary}\""),
                    )
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }
}