rustango 0.60.0

Batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
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
//! CSRF middleware (slice 8.4C) — double-submit-cookie strategy.
//!
//! On safe methods (`GET`, `HEAD`, `OPTIONS`, `TRACE`) the layer is
//! a pass-through that ensures a fresh CSRF token cookie is set on
//! the response. On unsafe methods (`POST`, `PUT`, `PATCH`,
//! `DELETE`) the layer enforces that the request carries an
//! `X-CSRF-Token` header (or `_csrf` form field, when the body is
//! `application/x-www-form-urlencoded`) whose value matches the
//! `rustango_csrf` cookie. Mismatch / missing → `403 Forbidden`.
//!
//! The cookie is `HttpOnly = false` (the SPA / form code MUST be
//! able to read it) and `SameSite = Lax`. `Secure` comes from
//! [`CsrfConfig::secure`] on the middleware path (default `true`) and
//! from [`crate::session::secure_cookies`] in [`ensure_token`]; no
//! path inspects the request's URL scheme. Token is 32 bytes of
//! `OsRng` rendered as URL-safe base64 (no padding).
//!
//! Wire it as an axum layer:
//!
//! ```ignore
//! use rustango::forms::csrf;
//! let app = Router::new()
//!     .route("/items", post(create_item))
//!     .layer(csrf::layer());
//! ```
//!
//! The auto-admin auto-mounts this layer when the `admin` feature
//! is on; user route handlers that POST forms must apply it
//! themselves (or use a top-level `Router::layer(csrf::layer())`).
//!
//! Gated by the `csrf` feature (in `default` via `admin`). Drop the
//! `admin` feature to skip both the middleware code and the cookie
//! / rand / base64 deps.

use std::convert::Infallible;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use axum::body::Body;
use axum::extract::Request;
use axum::http::{HeaderValue, Method, Response, StatusCode};
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
use rand::RngCore;
use tower::Service;

/// Default cookie name set by the CSRF middleware. Distinct from
/// the tenancy session cookies (`rustango_session` /
/// `rustango_tenant_session`) so the two flows don't collide.
/// Public so view code that wants to read or mint a token via
/// [`ensure_token`] can use the canonical name without re-typing
/// it.
pub const CSRF_COOKIE: &str = "rustango_csrf";

/// HTTP header the middleware looks for on unsafe requests. SPAs
/// echo the cookie value here (the standard double-submit pattern).
const CSRF_HEADER: &str = "X-CSRF-Token";

/// Form-field name the middleware looks for on
/// `application/x-www-form-urlencoded` bodies. Templates render it as
/// a hidden input carrying the same token as the cookie.
pub const CSRF_FORM_FIELD: &str = "_csrf";

/// Create the CSRF middleware as a [`tower::Layer`].
///
/// Defaults are sensible: 32-byte tokens, Lax SameSite, HttpOnly
/// off (the SPA must read the cookie). Override via [`CsrfConfig`]
/// + [`with_config`].
pub fn layer() -> CsrfLayer {
    CsrfLayer::new(CsrfConfig::default())
}

/// Create the middleware with explicit config — used by integrators
/// who need a different cookie name (e.g. when stacking against a
/// different framework on the same host).
pub fn with_config(cfg: CsrfConfig) -> CsrfLayer {
    CsrfLayer::new(cfg)
}

/// Configuration for the CSRF layer. All fields have sensible
/// defaults; override only what diverges.
#[derive(Debug, Clone)]
pub struct CsrfConfig {
    /// Cookie name. Default `"rustango_csrf"`.
    pub cookie_name: String,
    /// Header name the middleware accepts on unsafe methods. Default
    /// `"X-CSRF-Token"`.
    pub header_name: String,
    /// `Secure` cookie attribute.
    ///
    /// Defaults to `true` since v0.43 — the safe production default.
    /// Browsers will not send a `Secure` cookie over plain HTTP, so
    /// local development against `http://localhost:8080` needs an
    /// explicit opt-out:
    ///
    /// ```ignore
    /// rustango::forms::csrf::with_config(
    ///     CsrfConfig::default().allow_insecure_for_dev(),
    /// )
    /// ```
    ///
    /// `manage check --deploy` continues to warn when this is `false`
    /// on a prod tier.
    pub secure: bool,
    /// Extra origins that may submit cross-origin POSTs without being
    /// rejected by the Origin-header check. Each entry is a
    /// scheme+host (optionally with port), e.g.
    /// `"https://app.example.com"` or
    /// `"https://*.example.com"` for a wildcard subdomain.
    ///
    /// Default `[]` (empty). The Origin check still runs: the
    /// request's own `Host` is the implicit trusted origin, so a
    /// same-origin deployment needs no configuration. Add entries only
    /// for origins *other* than the app's own.
    ///
    /// It used to be that an empty list skipped the check entirely,
    /// which left the default deployment on bare unsigned
    /// double-submit — forgeable by anyone able to write a cookie on
    /// the parent domain (#1529).
    pub trusted_origins: Vec<String>,
    /// URL path prefixes exempt from CSRF enforcement on unsafe
    /// methods. Default `[]`. Intended for `navigator.sendBeacon`
    /// collector endpoints (e.g. analytics), which cannot set an
    /// `X-CSRF-Token` header and — when the page is served from a CDN
    /// cache that strips `Set-Cookie` — may have no CSRF cookie at all.
    /// Each entry is matched with `req.uri().path().starts_with(prefix)`,
    /// so keep prefixes narrow and only exempt append-only endpoints
    /// that read/write no auth state.
    pub exempt_prefixes: Vec<String>,
    /// Enforce CSRF on the HTTP `QUERY` method (RFC 10008). Default
    /// `false` — QUERY is a *safe* method, browsers can't form-submit it,
    /// and a cross-origin `fetch` with method `QUERY` is never a
    /// CORS-safelisted "simple request", so it always triggers a preflight
    /// and carries no ambient-credential CSRF vector. It is therefore
    /// exempt like GET/HEAD/OPTIONS/TRACE. Set `true` for pure
    /// defense-in-depth if you want a token required on QUERY anyway.
    ///
    /// The default exemption stays safe only while two things hold — both
    /// true out of the box:
    /// - **QUERY handlers are side-effect-free.** RFC 10008 defines QUERY
    ///   as safe + idempotent; mount only read-only handlers on it (a
    ///   mutation on QUERY would have no token check under the default).
    /// - **`QUERY` is never added to the method-override allow-list**
    ///   ([`crate::method_override`], default `[PUT, PATCH, DELETE]`).
    ///   Allowing a form POST to be rewritten to QUERY would manufacture
    ///   the ambient-credential request the exemption assumes can't exist.
    ///
    /// If you can't guarantee both, set this to `true`.
    pub require_csrf_on_query: bool,
}

impl Default for CsrfConfig {
    fn default() -> Self {
        Self {
            cookie_name: CSRF_COOKIE.to_owned(),
            header_name: CSRF_HEADER.to_owned(),
            secure: true,
            trusted_origins: Vec::new(),
            exempt_prefixes: Vec::new(),
            require_csrf_on_query: false,
        }
    }
}

impl CsrfConfig {
    /// Opt out of the `Secure` cookie attribute for local HTTP
    /// development. v0.43 — replaces the pre-v0.43 default of
    /// `secure: false`, which made dev easy but silently shipped to
    /// production unless the operator remembered to flip it.
    #[must_use]
    pub fn allow_insecure_for_dev(mut self) -> Self {
        self.secure = false;
        self
    }

    /// Builder — append a trusted origin (scheme+host, optionally
    /// `*.` wildcard subdomain) to [`Self::trusted_origins`].
    #[must_use]
    pub fn trust_origin(mut self, origin: impl Into<String>) -> Self {
        self.trusted_origins.push(origin.into());
        self
    }

    /// Builder — replace the trusted-origins list wholesale.
    /// Convenient when wiring from settings:
    /// `CsrfConfig::default().with_trusted_origins(settings.security.csrf_trusted_origins.clone())`.
    #[must_use]
    pub fn with_trusted_origins<I, S>(mut self, origins: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.trusted_origins = origins.into_iter().map(Into::into).collect();
        self
    }

    /// Builder — exempt a URL path prefix from CSRF enforcement on
    /// unsafe methods. For beacon/collector endpoints posted via
    /// `navigator.sendBeacon` (which cannot set a custom header) and
    /// reachable from CDN-cached pages that never received a CSRF
    /// cookie. Only exempt append-only endpoints that touch no auth
    /// state; keep the prefix narrow.
    #[must_use]
    pub fn exempt_prefix(mut self, prefix: impl Into<String>) -> Self {
        self.exempt_prefixes.push(prefix.into());
        self
    }
}

/// Origin-header check — defense-in-depth over the double-submit
/// cookie. Returns `true` if the request's Origin header is allowed:
///
/// * No Origin header → allow (some clients / curl don't send it).
/// * Origin's scheme **and** host match the request → allow
///   (same-origin POST is the common case). An Origin that is not
///   `scheme://host` — empty, the opaque `null`, a bare hostname —
///   never counts as same-origin, and a plain `http://` Origin does
///   not match a request that visibly arrived over TLS (#1529).
/// * Origin matches an entry in `trusted_origins` (exact or
///   `*.subdomain.example.com` wildcard) → allow.
/// * Anything else → reject.
///
/// An empty `trusted_origins` no longer skips the check: the
/// request's own `Host` is the implicit trusted origin, so
/// same-origin traffic passes with no configuration and a foreign
/// Origin is rejected by default (#1529).
/// Split an `Origin` header into `(scheme, host[:port])`.
///
/// `None` when it is not `scheme://host` — an empty header, the
/// opaque `null`, or a bare hostname. Those are never same-origin.
fn split_origin(origin: &str) -> Option<(&str, &str)> {
    let (scheme, rest) = origin.split_once("://")?;
    if scheme.is_empty() || rest.is_empty() {
        return None;
    }
    Some((scheme, rest))
}

/// `true` when the request visibly arrived over TLS.
///
/// Best-effort and deliberately one-directional: it is used only to
/// *reject* a plain-http Origin, so a proxy that forwards neither
/// header leaves behaviour exactly as it was rather than locking
/// anyone out.
fn request_is_https(h: &axum::http::HeaderMap, uri_is_https: bool) -> bool {
    if uri_is_https {
        return true;
    }
    if h.get("x-forwarded-proto")
        .and_then(|v| v.to_str().ok())
        .is_some_and(|v| {
            v.split(',')
                .next()
                .unwrap_or("")
                .trim()
                .eq_ignore_ascii_case("https")
        })
    {
        return true;
    }
    // RFC 7239 `Forwarded: proto=https;for=...`
    h.get("forwarded")
        .and_then(|v| v.to_str().ok())
        .is_some_and(|v| {
            v.split(';')
                .flat_map(|p| p.split(','))
                .filter_map(|p| p.trim().strip_prefix("proto="))
                .any(|p| p.trim_matches('"').eq_ignore_ascii_case("https"))
        })
}

fn origin_allowed(req: &Request<Body>, trusted: &[String]) -> bool {
    origin_allowed_in(
        req.headers(),
        req.uri().scheme_str() == Some("https"),
        trusted,
    )
}

fn origin_allowed_in(
    headers: &axum::http::HeaderMap,
    uri_is_https: bool,
    trusted: &[String],
) -> bool {
    let Some(origin) = headers
        .get(axum::http::header::ORIGIN)
        .and_then(|h| h.to_str().ok())
    else {
        // No Origin header. Over TLS this is refused: unsigned
        // double-submit alone is forgeable by anyone who can write a
        // cookie on the parent domain — XSS on a sibling subdomain, a
        // dangling-CNAME takeover, or a network attacker on any
        // plaintext `http://*.example.com` (`Secure` stops the cookie
        // being *sent* over HTTP, not *written*). Origin is what
        // catches that, so it must not be skippable by omitting it
        // (#1529).
        //
        // Plain HTTP keeps the old behaviour, so server-to-server and
        // curl callers on internal networks are not locked out by an
        // upgrade; they are still covered by the token check.
        return !request_is_https(headers, uri_is_https);
    };
    // Same-origin: Origin's scheme AND host must match the request.
    if let Some(host) = headers
        .get(axum::http::header::HOST)
        .and_then(|h| h.to_str().ok())
    {
        // An Origin that is not `scheme://host` is not same-origin.
        // This used to fall back to comparing the raw header against
        // Host, so `Origin: example.com` — and the opaque `Origin:
        // null` a sandboxed iframe sends — could match (#1529).
        if let Some((scheme, origin_host)) = split_origin(origin) {
            let host_matches = origin_host.trim_end_matches('/') == host;
            // Whenever the request visibly arrived over TLS, a plain
            // `http://` Origin is a different origin, not this one.
            // Accepting it let a network attacker who can serve the
            // http site forge a same-origin POST at the https one.
            let scheme_ok = !(scheme == "http" && request_is_https(headers, uri_is_https));
            if host_matches && scheme_ok {
                return true;
            }
        }
    }
    // Trusted-origin allowlist. Support `*.example.com` wildcard.
    for entry in trusted {
        let entry = entry.trim().trim_end_matches('/');
        if entry == origin {
            return true;
        }
        for scheme in ["https://", "http://"] {
            let Some(wild) = entry
                .strip_prefix(scheme)
                .and_then(|e| e.strip_prefix("*."))
            else {
                continue;
            };
            let Some(authority) = origin.strip_prefix(scheme) else {
                continue;
            };
            if wildcard_matches(authority, wild) {
                return true;
            }
        }
    }
    false
}

/// `true` when `authority` (`host` or `host:port`) is covered by a
/// `*.<wild>` entry — either `wild` itself or any subdomain of it.
///
/// The port is stripped first. Matching the raw authority meant
/// `https://sub.example.com:8443` missed a `https://*.example.com`
/// entry the operator believed covered it, and the symptom was a 403
/// that reads as flaky rather than as a config problem (#1529).
fn wildcard_matches(authority: &str, wild: &str) -> bool {
    let host = authority.split(':').next().unwrap_or(authority);
    let wild_host = wild.split(':').next().unwrap_or(wild);
    if host == wild_host {
        return true;
    }
    host.strip_suffix(wild_host)
        .is_some_and(|rest| rest.ends_with('.'))
}

/// The outermost CSRF layer on this request, in its extensions; `checked`
/// once it verified the token, so an inner layer need not (#1722).
#[derive(Clone)]
pub(crate) struct ActiveCsrf {
    cfg: Arc<CsrfConfig>,
    checked: bool,
}

/// The cookie name the CSRF layer on this request checks; the default
/// when there is none.
#[cfg(feature = "template_views")]
#[must_use]
pub(crate) fn active_cookie_name(extensions: &axum::http::Extensions) -> &str {
    extensions
        .get::<ActiveCsrf>()
        .map_or(CSRF_COOKIE, |a| a.cfg.cookie_name.as_str())
}

/// The [`tower::Layer`] implementation. Wraps inner services with
/// [`CsrfService`].
#[derive(Clone)]
pub struct CsrfLayer {
    cfg: Arc<CsrfConfig>,
}

impl CsrfLayer {
    fn new(cfg: CsrfConfig) -> Self {
        Self { cfg: Arc::new(cfg) }
    }
}

impl<S> tower::Layer<S> for CsrfLayer {
    type Service = CsrfService<S>;
    fn layer(&self, inner: S) -> Self::Service {
        CsrfService {
            inner,
            cfg: Arc::clone(&self.cfg),
        }
    }
}

/// The wrapped service. Validates unsafe-method requests, ensures
/// safe-method responses carry a CSRF cookie.
#[derive(Clone)]
pub struct CsrfService<S> {
    inner: S,
    cfg: Arc<CsrfConfig>,
}

impl<S> Service<Request<Body>> for CsrfService<S>
where
    S: Service<Request<Body>, Response = Response<Body>, Error = Infallible>
        + Clone
        + Send
        + 'static,
    S::Future: Send + 'static,
{
    type Response = Response<Body>;
    type Error = Infallible;
    type Future =
        Pin<Box<dyn std::future::Future<Output = Result<Response<Body>, Infallible>> + Send>>;

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

    fn call(&mut self, req: Request<Body>) -> Self::Future {
        let cfg = Arc::clone(&self.cfg);
        let mut inner = self.inner.clone();
        Box::pin(async move {
            let mut req = req;
            // An outer layer's names win (#1722). If it verified the token,
            // defer; if it skipped an exempt path, check here without them.
            let active = req.extensions().get::<ActiveCsrf>().cloned();
            // The outer layer seeds the cookie; a second one here would not
            // match the token the page rendered (#2131).
            let nested = active.is_some();
            let cfg = match active {
                Some(a) if a.checked => return inner.call(req).await,
                Some(a) => Arc::new(CsrfConfig {
                    exempt_prefixes: Vec::new(),
                    ..CsrfConfig::clone(&a.cfg)
                }),
                None => {
                    req.extensions_mut().insert(ActiveCsrf {
                        cfg: Arc::clone(&cfg),
                        checked: false,
                    });
                    cfg
                }
            };
            let cookie_value = read_csrf_cookie(&req, &cfg.cookie_name);

            // Enforce on unsafe methods — unless the path is exempt
            // (beacon/collector endpoints; see `CsrfConfig::exempt_prefix`).
            let enforced = !method_is_csrf_exempt(req.method(), &cfg)
                && !path_is_exempt(req.uri().path(), &cfg.exempt_prefixes);
            let mut req = if enforced {
                // Origin-header defense-in-depth. Always runs; an empty
                // `trusted_origins` means same-host only (#1529).
                if !origin_allowed(&req, &cfg.trusted_origins) {
                    return Ok(forbid_response(
                        "CSRF: request Origin not in CSRF_TRUSTED_ORIGINS \
                         and does not match Host",
                    ));
                }
                let header_value = req
                    .headers()
                    .get(&cfg.header_name)
                    .and_then(|v| v.to_str().ok())
                    .map(str::to_owned);
                if let Some(h) = header_value {
                    // Header path — short-circuit, no body buffering.
                    if !tokens_match(cookie_value.as_deref(), Some(&h)) {
                        return Ok(forbid_response("CSRF token missing or mismatched"));
                    }
                    req
                } else if is_form_encoded(&req) {
                    // Form-encoded POST without the header — read
                    // `_csrf` from the body. Body is consumed once,
                    // so we buffer + replace so the inner handler
                    // can still parse it.
                    let (parts, body) = req.into_parts();
                    let bytes = match axum::body::to_bytes(body, BODY_BUFFER_LIMIT).await {
                        Ok(b) => b,
                        Err(_) => {
                            return Ok(forbid_response("CSRF: form body exceeded buffer limit"));
                        }
                    };
                    let form_token = read_form_field(&bytes, CSRF_FORM_FIELD);
                    if !tokens_match(cookie_value.as_deref(), form_token.as_deref()) {
                        return Ok(forbid_response("CSRF token missing or mismatched"));
                    }
                    Request::from_parts(parts, Body::from(bytes))
                } else {
                    // Neither header nor form body — reject.
                    return Ok(forbid_response("CSRF token missing or mismatched"));
                }
            } else {
                req
            };
            if enforced {
                req.extensions_mut().insert(ActiveCsrf {
                    cfg: Arc::clone(&cfg),
                    checked: true,
                });
            }

            // Pass to inner. After the response comes back, ensure
            // the CSRF cookie is set so the next safe-method GET
            // doesn't have to seed it.
            let mut response = inner.call(req).await?;
            // Seed the cookie only if the request had none *and* the
            // handler didn't already set one.
            //
            // `stamp_into_context` (and `ensure_token` generally) mints a
            // token, renders it into the form, and appends its own
            // `Set-Cookie`. Minting a second one here appended a
            // *different* value, and a browser keeps the last — so on a
            // visitor's first-ever view of any form the rendered `_csrf`
            // and the stored cookie disagreed, and their first submit was
            // a 403. Reloading masked it, which is why it survived: only
            // brand-new visitors ever saw it.
            if cookie_value.is_none()
                && !nested
                && !sets_cookie(&response, &cfg.cookie_name)
                && !is_publicly_cacheable(response.headers())
            {
                let token = mint_token();
                let cookie_str = format!(
                    "{}={token}; Path=/; SameSite=Lax{}",
                    cfg.cookie_name,
                    if cfg.secure { "; Secure" } else { "" }
                );
                if let Ok(hv) = HeaderValue::from_str(&cookie_str) {
                    response
                        .headers_mut()
                        .append(axum::http::header::SET_COOKIE, hv);
                }
            }
            Ok(response)
        })
    }
}

/// Cap the form-body buffer the CSRF middleware will consume while
/// extracting the `_csrf` field. axum's default request body limit
/// (2 MB), which the handler buffers up to anyway: a lower cap here
/// turned a large admin edit (a long text field) into a 403 (#1714).
const BODY_BUFFER_LIMIT: usize = 2 * 1024 * 1024;

/// `true` when `path` starts with any configured exempt prefix. Used to
/// skip CSRF enforcement for beacon/collector endpoints.
fn path_is_exempt(path: &str, prefixes: &[String]) -> bool {
    prefixes.iter().any(|p| path.starts_with(p.as_str()))
}

fn is_safe_method(m: &Method) -> bool {
    matches!(
        *m,
        Method::GET | Method::HEAD | Method::OPTIONS | Method::TRACE
    )
}

/// Whether `m` is exempt from CSRF token enforcement. The classic safe
/// methods always are; the RFC 10008 `QUERY` method is too (a safe method
/// with no browser CSRF vector) unless [`CsrfConfig::require_csrf_on_query`]
/// opts it back in. `QUERY` is matched by name so this stays independent
/// of the `admin`-gated `http_query` module.
fn method_is_csrf_exempt(m: &Method, cfg: &CsrfConfig) -> bool {
    is_safe_method(m) || (!cfg.require_csrf_on_query && m.as_str() == "QUERY")
}

/// Does this response already issue `name` as a cookie?
///
/// Checked before the layer seeds its own, so a handler that stamped a
/// token into its template keeps the value it rendered.
/// `true` when a shared cache may store the response (`Cache-Control:
/// public`). A `Set-Cookie` on it would hand one token to every visitor.
pub(crate) fn is_publicly_cacheable(headers: &axum::http::HeaderMap) -> bool {
    headers
        .get_all(axum::http::header::CACHE_CONTROL)
        .iter()
        .filter_map(|v| v.to_str().ok())
        .flat_map(|v| v.split(','))
        .any(|d| d.trim().eq_ignore_ascii_case("public"))
}

fn sets_cookie<B>(response: &Response<B>, name: &str) -> bool {
    response
        .headers()
        .get_all(axum::http::header::SET_COOKIE)
        .iter()
        .filter_map(|v| v.to_str().ok())
        .any(|v| {
            v.split(';')
                .next()
                .and_then(|pair| pair.split_once('='))
                .is_some_and(|(k, _)| k.trim() == name)
        })
}

fn read_csrf_cookie(req: &Request<Body>, name: &str) -> Option<String> {
    read_csrf_cookie_from_headers(req.headers(), name)
}

fn read_csrf_cookie_from_headers(headers: &axum::http::HeaderMap, name: &str) -> Option<String> {
    crate::cookies::cookie_from_headers(headers, name).map(str::to_owned)
}

/// `true` when the request body is `application/x-www-form-urlencoded`
/// — the only format the CSRF middleware knows how to scan for the
/// `_csrf` field. Multipart uploads use a different MIME and are
/// expected to send the token via the `X-CSRF-Token` header.
fn is_form_encoded(req: &Request<Body>) -> bool {
    let Some(ct) = req
        .headers()
        .get(axum::http::header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
    else {
        return false;
    };
    // Strip any `; charset=...` suffix and lowercase-compare.
    let head = ct
        .split(';')
        .next()
        .unwrap_or("")
        .trim()
        .to_ascii_lowercase();
    head == "application/x-www-form-urlencoded"
}

/// Tiny form-encoded parser scoped to extracting one named field.
/// Accepts `key=value&key2=value2` shape, percent-decoded, with
/// `+` treated as space (the form-encoded convention). Returns
/// the FIRST matching field's value — duplicates are rare in
/// well-formed forms.
fn read_form_field(body: &[u8], name: &str) -> Option<String> {
    let s = std::str::from_utf8(body).ok()?;
    for pair in s.split('&') {
        let Some((k, v)) = pair.split_once('=') else {
            continue;
        };
        // Strict: a malformed field is refused, not truncated.
        let key = url_decode_strict(k)?;
        if key == name {
            return url_decode_strict(v);
        }
    }
    None
}

use crate::url_codec::url_decode_strict;

/// Generate a fresh 32-byte token, base64url-encoded (no padding).
fn mint_token() -> String {
    let mut bytes = [0u8; 32];
    rand::rngs::OsRng.fill_bytes(&mut bytes);
    URL_SAFE_NO_PAD.encode(bytes)
}

/// `true` for the shape [`mint_token`] produces: 43 base64url chars.
fn is_minted_token(t: &str) -> bool {
    t.len() == 43
        && t.bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}

/// Read the existing CSRF cookie from request headers, or mint a
/// fresh token. Returns `(token, Some(set_cookie_header_value))`
/// when the cookie was missing — caller is responsible for adding
/// the `Set-Cookie` header to the response so the template's
/// `<input value="{{ csrf_token }}">` matches what the browser
/// sends back on POST. Returns `(token, None)` when the cookie was
/// already present (no `Set-Cookie` needed).
///
/// Usage from a Tera-rendering view (template_views, custom HTML
/// handlers):
///
/// ```ignore
/// let (token, set_cookie) = rustango::forms::csrf::ensure_token(
///     req_headers,
///     rustango::forms::csrf::CSRF_COOKIE,
/// );
/// ctx.insert("csrf_token", &token);
/// let mut resp = render_template(...);
/// if let Some(c) = set_cookie {
///     resp.headers_mut().append(
///         axum::http::header::SET_COOKIE,
///         axum::http::HeaderValue::from_str(&c).unwrap(),
///     );
/// }
/// ```
///
/// Without this helper, the first-ever GET to a form view would
/// render with an empty `csrf_token`, the user's POST would fail
/// CSRF validation, and only the second attempt would succeed.
/// `ensure_token` makes the first GET idempotent.
#[must_use]
pub fn ensure_token(
    headers: &axum::http::HeaderMap,
    cookie_name: &str,
) -> (String, Option<String>) {
    // Reuse only a token this module could have minted. A sibling
    // subdomain can plant any cookie value, and the token is rendered
    // into pages (#1712 review).
    if let Some(existing) = read_csrf_cookie_from_headers(headers, cookie_name) {
        if is_minted_token(&existing) {
            return (existing, None);
        }
    }
    let token = mint_token();
    // `Secure` from the same policy the session cookies use: the boot
    // override, else the prod tier. Without it this cookie went out over
    // plaintext in every tier, so a MITM on one cleartext request could
    // read or fix the token (#1608).
    let secure = if crate::session::secure_cookies() {
        "; Secure"
    } else {
        ""
    };
    let cookie = format!("{cookie_name}={token}; Path=/; SameSite=Lax{secure}");
    (token, Some(cookie))
}

/// Validate a server-rendered form POST. Returns `true` iff the Origin
/// is the request's own Host (no trusted list; #1695) and
/// [`CSRF_COOKIE`] matches `submitted` (the `_csrf` field) in constant time.
///
/// For handlers that render their own form and seed the token via
/// [`ensure_token`] + [`csrf_input_html`] (so the GET response sets the
/// cookie and the form carries the matching token), rather than relying
/// on the [`CsrfLayer`] middleware. Using the layer *and* seeding the
/// token in the handler would set two conflicting cookies.
#[must_use]
pub fn verify_form_token(headers: &axum::http::HeaderMap, submitted: Option<&str>) -> bool {
    if !origin_allowed_in(headers, false, &[]) {
        return false;
    }
    tokens_match(
        read_csrf_cookie_from_headers(headers, CSRF_COOKIE).as_deref(),
        submitted,
    )
}

/// The one double-submit check: both tokens present, non-empty and
/// equal in constant time (#1693).
fn tokens_match(cookie: Option<&str>, submitted: Option<&str>) -> bool {
    match (cookie, submitted) {
        (Some(c), Some(s)) if !c.is_empty() => {
            crate::crypto::constant_time_compare(c.as_bytes(), s.as_bytes())
        }
        _ => false,
    }
}

fn forbid_response(detail: &'static str) -> Response<Body> {
    let mut response = Response::new(Body::from(detail));
    *response.status_mut() = StatusCode::FORBIDDEN;
    response
        .headers_mut()
        .insert("Content-Type", HeaderValue::from_static("text/plain"));
    response
}

// ============================================================== template helpers (issue #15)

/// Render the hidden `<input>` HTML that posts the token back to the
/// middleware. Use this when you already have the token string and
/// just need the form field. Pair with [`stamp_into_context`] for the
/// full handler-side flow.
///
/// ```ignore
/// let html = csrf_input_html("abc123");
/// assert_eq!(html, r#"<input type="hidden" name="_csrf" value="abc123">"#);
/// ```
#[must_use]
pub fn csrf_input_html(token: &str) -> String {
    let escaped = html_escape_attr(token);
    format!(r#"<input type="hidden" name="{CSRF_FORM_FIELD}" value="{escaped}">"#)
}

use crate::text::html_escape as html_escape_attr;

/// Read or mint a CSRF token and stamp it into the Tera context with
/// two keys callers can pick from: `csrf_token` (raw string, for SPA
/// meta tags or custom HTML) and `csrf_input` (pre-rendered hidden
/// input, ready for `{{ csrf_input | safe }}`). Returns the
/// optional `Set-Cookie` header value the caller should attach to
/// the response when a fresh token was minted (so the first GET
/// doesn't render an empty token).
///
/// Public counterpart of the private helper used by [`crate::template_views`]
/// — promoted so users with hand-rolled handlers don't re-implement
/// the cookie-mint dance. Uses [`CSRF_COOKIE`]; with a custom
/// [`CsrfConfig::cookie_name`] call [`stamp_named_into_context`].
///
/// ```ignore
/// async fn contact_form(headers: HeaderMap) -> Response {
///     let mut ctx = tera::Context::new();
///     let set_cookie = rustango::forms::csrf::stamp_into_context(&headers, &mut ctx);
///     let mut res = render(&tera, "contact.html", &ctx);
///     if let Some(c) = set_cookie {
///         if let Ok(h) = axum::http::HeaderValue::from_str(&c) {
///             res.headers_mut().append(axum::http::header::SET_COOKIE, h);
///         }
///     }
///     res
/// }
/// ```
///
/// Template usage:
///
/// ```jinja
/// <form method="POST">
///   {{ csrf_input | safe }}
///   …
/// </form>
///
/// <!-- SPA meta-tag variant: -->
/// <meta name="csrf-token" content="{{ csrf_token }}">
/// ```
#[cfg(feature = "template_views")]
#[must_use]
pub fn stamp_into_context(
    headers: &axum::http::HeaderMap,
    ctx: &mut tera::Context,
) -> Option<String> {
    stamp_named_into_context(headers, CSRF_COOKIE, ctx)
}

/// [`stamp_into_context`] for the cookie `cookie_name`, e.g. the
/// [`CsrfConfig::cookie_name`] of your CSRF layer.
#[cfg(feature = "template_views")]
#[must_use]
pub fn stamp_named_into_context(
    headers: &axum::http::HeaderMap,
    cookie_name: &str,
    ctx: &mut tera::Context,
) -> Option<String> {
    let (token, set_cookie) = ensure_token(headers, cookie_name);
    let html = csrf_input_html(&token);
    ctx.insert("csrf_token", &token);
    ctx.insert("csrf_input", &html);
    set_cookie
}

/// Register a `csrf_input` Tera filter that converts a token string
/// to the hidden-input HTML. Useful when a template has the raw
/// `csrf_token` in context (the existing `template_views` shape) but
/// wants the `<input>` shape without hand-writing it:
///
/// ```jinja
/// {{ csrf_token | csrf_input | safe }}
/// ```
///
/// Call at app setup, alongside any other Tera registration. Pair
/// with [`stamp_into_context`] for handlers that don't go through
/// the built-in `template_views` CBVs.
///
/// Non-string filter input passes through unchanged so the chain
/// doesn't blow up on accidental wiring.
#[cfg(feature = "template_views")]
pub fn register_csrf_filter(tera: &mut tera::Tera) {
    tera.register_filter("csrf_input", csrf_input_filter);
}

#[cfg(feature = "template_views")]
fn csrf_input_filter(
    value: &tera::Value,
    _: &std::collections::HashMap<String, tera::Value>,
) -> tera::Result<tera::Value> {
    if let Some(s) = value.as_str() {
        Ok(tera::Value::String(csrf_input_html(s)))
    } else {
        Ok(value.clone())
    }
}

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

    /// Build a POST with the given Origin/Host, optionally over TLS.
    fn post(origin: Option<&str>, host: &str, https: bool) -> Request<Body> {
        let mut b = Request::builder().method(Method::POST).uri("/forms/submit");
        if let Some(o) = origin {
            b = b.header(axum::http::header::ORIGIN, o);
        }
        if https {
            b = b.header("x-forwarded-proto", "https");
        }
        b.header(axum::http::header::HOST, host)
            .body(Body::empty())
            .unwrap()
    }

    /// The default config must reject a cross-origin POST (#1529).
    ///
    /// This is the whole point of the issue: an attacker who can write
    /// a cookie on the parent domain — XSS on a sibling subdomain, a
    /// dangling-CNAME takeover, a network attacker on any plaintext
    /// `http://*.example.com` — forges a matching double-submit pair.
    /// Origin is what catches that, and it used to be off unless the
    /// integrator populated a list.
    #[test]
    fn a_foreign_origin_is_rejected_with_the_default_config() {
        let cfg = CsrfConfig::default();
        assert!(cfg.trusted_origins.is_empty(), "the default is still []");

        assert!(
            !origin_allowed(
                &post(Some("https://evil.example"), "app.example.com", true),
                &cfg.trusted_origins
            ),
            "a foreign Origin must be refused out of the box"
        );
        // Same-origin still passes with no configuration at all.
        assert!(origin_allowed(
            &post(Some("https://app.example.com"), "app.example.com", true),
            &cfg.trusted_origins
        ));
    }

    /// A missing Origin must not be a way around the check on HTTPS —
    /// otherwise anything able to omit the header skips it (#1529).
    #[test]
    fn a_missing_origin_is_refused_over_tls_only() {
        let empty: Vec<String> = Vec::new();
        assert!(
            !origin_allowed(&post(None, "app.example.com", true), &empty),
            "no Origin over TLS must be refused"
        );
        // Plain HTTP keeps the old behaviour so server-to-server and
        // curl callers are not locked out by an upgrade.
        assert!(
            origin_allowed(&post(None, "app.example.com", false), &empty),
            "no Origin over plain http stays allowed"
        );
    }

    /// A wildcard entry covers a non-default port. Matching the raw
    /// authority made this a silent false negative that reads as a
    /// flaky 403 (#1529).
    #[test]
    fn a_wildcard_entry_matches_a_non_default_port() {
        let trusted = vec!["https://*.example.com".to_owned()];
        for origin in [
            "https://sub.example.com:8443",
            "https://sub.example.com",
            "https://deep.sub.example.com:443",
        ] {
            assert!(
                origin_allowed(&post(Some(origin), "app.other", true), &trusted),
                "`{origin}` should match the wildcard"
            );
        }
        // Still not a free pass for a lookalike domain.
        for origin in [
            "https://sub.example.com.evil.test",
            "https://notexample.com:8443",
        ] {
            assert!(
                !origin_allowed(&post(Some(origin), "app.other", true), &trusted),
                "`{origin}` must not match the wildcard"
            );
        }
    }

    #[test]
    fn safe_method_predicate() {
        assert!(is_safe_method(&Method::GET));
        assert!(is_safe_method(&Method::HEAD));
        assert!(is_safe_method(&Method::OPTIONS));
        assert!(!is_safe_method(&Method::POST));
        assert!(!is_safe_method(&Method::PUT));
        assert!(!is_safe_method(&Method::DELETE));
    }

    #[test]
    fn query_method_is_csrf_exempt_by_default() {
        let query = Method::from_bytes(b"QUERY").unwrap();
        let cfg = CsrfConfig::default();
        // QUERY exempt by default (safe method, no browser CSRF vector)…
        assert!(method_is_csrf_exempt(&query, &cfg));
        // …but still not a mutating method like POST.
        assert!(!method_is_csrf_exempt(&Method::POST, &cfg));
    }

    #[test]
    fn require_csrf_on_query_opts_query_back_in() {
        let query = Method::from_bytes(b"QUERY").unwrap();
        let cfg = CsrfConfig {
            require_csrf_on_query: true,
            ..CsrfConfig::default()
        };
        assert!(!method_is_csrf_exempt(&query, &cfg));
        // Classic safe methods are unaffected by the knob.
        assert!(method_is_csrf_exempt(&Method::GET, &cfg));
    }

    #[test]
    fn exempt_prefix_matches_only_configured_paths() {
        let prefixes = vec!["/__cms__/collect".to_owned()];
        // Exact + sub-path match (prefix semantics).
        assert!(path_is_exempt("/__cms__/collect", &prefixes));
        assert!(path_is_exempt("/__cms__/collect/extra", &prefixes));
        // Unrelated paths still enforced.
        assert!(!path_is_exempt("/__cms__/other", &prefixes));
        assert!(!path_is_exempt("/forms/submit/1", &prefixes));
        assert!(!path_is_exempt("/", &prefixes));
        // Empty config exempts nothing (back-compat default).
        assert!(!path_is_exempt("/__cms__/collect", &[]));
    }

    #[test]
    fn exempt_prefix_builder_appends() {
        let cfg = CsrfConfig::default().exempt_prefix("/__cms__/collect");
        assert_eq!(cfg.exempt_prefixes, vec!["/__cms__/collect".to_owned()]);
    }

    #[test]
    fn ct_eq_matches_eq() {
        assert!(crate::crypto::constant_time_compare(b"abc", b"abc"));
        assert!(!crate::crypto::constant_time_compare(b"abc", b"abd"));
        assert!(!crate::crypto::constant_time_compare(b"abc", b"abcd"));
        assert!(crate::crypto::constant_time_compare(b"", b""));
    }

    #[test]
    fn mint_token_is_base64url_no_pad() {
        let t = mint_token();
        // 32 bytes → 43 base64 chars (no padding).
        assert_eq!(t.len(), 43);
        assert!(!t.contains('='));
        assert!(URL_SAFE_NO_PAD.decode(t.as_bytes()).is_ok());
    }

    #[test]
    fn read_csrf_cookie_finds_named_pair() {
        use axum::http::Request;
        let req = Request::builder()
            .header("cookie", "session=abc; rustango_csrf=hello; theme=dark")
            .body(Body::empty())
            .unwrap();
        assert_eq!(
            read_csrf_cookie(&req, "rustango_csrf").as_deref(),
            Some("hello")
        );
        assert_eq!(read_csrf_cookie(&req, "missing").as_deref(), None);
    }

    #[test]
    fn read_csrf_cookie_returns_none_when_no_header() {
        use axum::http::Request;
        let req = Request::builder().body(Body::empty()).unwrap();
        assert_eq!(read_csrf_cookie(&req, "anything"), None);
    }

    /// The minted cookie carries `Secure` when the policy asks for it.
    /// It never did, in any tier, which put the token on the wire in
    /// plaintext (#1608).
    #[test]
    fn ensure_token_marks_the_cookie_secure_under_a_secure_policy() {
        // `SECURE_COOKIES_OVERRIDE` is a `OnceLock`, and nextest runs
        // each test in its own process, so this is ours to set. If
        // something did get there first, only assert when the policy it
        // chose is the one this test is about.
        let ours = crate::session::set_secure_cookies(true);
        if !ours && !crate::session::secure_cookies() {
            return;
        }
        let headers = axum::http::HeaderMap::new();
        let (_token, set_cookie) = ensure_token(&headers, CSRF_COOKIE);
        let cookie = set_cookie.expect("no cookie in the request, so one is minted");
        assert!(
            cookie.contains("; Secure"),
            "policy is secure, so the cookie must say so: {cookie}"
        );
    }

    /// A planted cookie that is not a minted token is replaced, not
    /// reused — it is rendered into pages, `<script>` included.
    #[test]
    fn ensure_token_replaces_a_planted_cookie() {
        let mut headers = axum::http::HeaderMap::new();
        headers.insert(
            axum::http::header::COOKIE,
            "rustango_csrf=</script><svg/onload=alert(1)>"
                .parse()
                .unwrap(),
        );
        let (token, set_cookie) = ensure_token(&headers, CSRF_COOKIE);
        assert!(is_minted_token(&token), "{token}");
        assert!(set_cookie.is_some(), "the planted cookie is overwritten");

        let good = mint_token();
        let mut headers = axum::http::HeaderMap::new();
        headers.insert(
            axum::http::header::COOKIE,
            format!("rustango_csrf={good}").parse().unwrap(),
        );
        assert_eq!(ensure_token(&headers, CSRF_COOKIE), (good, None));
    }

    /// `is_form_encoded` recognizes the canonical content type +
    /// the `; charset=utf-8` variant browsers sometimes append.
    /// Other types (multipart, JSON) return false.
    #[test]
    fn is_form_encoded_recognizes_canonical_and_charset_variants() {
        use axum::http::Request;
        let req = Request::builder()
            .header("content-type", "application/x-www-form-urlencoded")
            .body(Body::empty())
            .unwrap();
        assert!(is_form_encoded(&req));

        let req = Request::builder()
            .header(
                "content-type",
                "application/x-www-form-urlencoded; charset=UTF-8",
            )
            .body(Body::empty())
            .unwrap();
        assert!(is_form_encoded(&req));

        let req = Request::builder()
            .header("content-type", "multipart/form-data; boundary=---")
            .body(Body::empty())
            .unwrap();
        assert!(!is_form_encoded(&req));

        let req = Request::builder()
            .header("content-type", "application/json")
            .body(Body::empty())
            .unwrap();
        assert!(!is_form_encoded(&req));

        // No content-type header: false.
        let req = Request::builder().body(Body::empty()).unwrap();
        assert!(!is_form_encoded(&req));
    }

    /// `read_form_field` extracts the named field, percent-decoded,
    /// `+` → space.
    #[test]
    fn read_form_field_extracts_named_value() {
        let body = b"foo=bar&_csrf=tok123&other=baz";
        assert_eq!(read_form_field(body, "_csrf").as_deref(), Some("tok123"));
        assert_eq!(read_form_field(body, "foo").as_deref(), Some("bar"));
        assert_eq!(read_form_field(body, "missing"), None);
    }

    #[test]
    fn read_form_field_percent_decodes_value() {
        let body = b"_csrf=abc%2Fxyz";
        assert_eq!(read_form_field(body, "_csrf").as_deref(), Some("abc/xyz"));
    }

    /// The field parser refuses a malformed token rather than passing
    /// through a lenient decode of it.
    #[test]
    fn read_form_field_refuses_a_malformed_token() {
        assert_eq!(read_form_field(b"_csrf=ab%ZZ", "_csrf"), None);
        assert_eq!(read_form_field(b"_csrf=ab%2", "_csrf"), None);
    }

    #[test]
    fn read_form_field_treats_plus_as_space() {
        let body = b"q=hello+world";
        assert_eq!(read_form_field(body, "q").as_deref(), Some("hello world"));
    }

    #[test]
    fn read_form_field_returns_none_for_malformed_pairs() {
        // Pair without `=` sign — skipped.
        let body = b"foo&_csrf=tok";
        assert_eq!(read_form_field(body, "_csrf").as_deref(), Some("tok"));
        assert_eq!(read_form_field(body, "foo"), None);
    }

    #[test]
    fn percent_decode_rejects_malformed() {
        assert!(url_decode_strict("%2").is_none()); // truncated
        assert!(url_decode_strict("%ZZ").is_none()); // non-hex
        assert!(url_decode_strict("%+5").is_none()); // sign is not hex
        assert!(url_decode_strict("%FF").is_none()); // not UTF-8
        assert_eq!(url_decode_strict("plain").as_deref(), Some("plain"));
        assert_eq!(url_decode_strict("a%20b+c").as_deref(), Some("a b c"));
    }

    // ---- template helpers (issue #15) ----

    #[test]
    fn csrf_input_html_uses_form_field_constant() {
        let html = csrf_input_html("abc123");
        assert_eq!(html, r#"<input type="hidden" name="_csrf" value="abc123">"#);
        // The `name` attribute matches the middleware-expected constant.
        assert!(html.contains(&format!(r#"name="{CSRF_FORM_FIELD}""#)));
    }

    #[test]
    fn verify_form_token_matches_cookie_constant_time() {
        let mut headers = axum::http::HeaderMap::new();
        headers.insert(
            axum::http::header::COOKIE,
            format!("{CSRF_COOKIE}=tok-abc123; other=x")
                .parse()
                .unwrap(),
        );
        // Cookie present + form token equal → ok.
        assert!(verify_form_token(&headers, Some("tok-abc123")));
        // Mismatch → reject.
        assert!(!verify_form_token(&headers, Some("tok-different")));
        // Missing form token → reject.
        assert!(!verify_form_token(&headers, None));
        // Missing cookie entirely → reject.
        let empty = axum::http::HeaderMap::new();
        assert!(!verify_form_token(&empty, Some("tok-abc123")));
    }

    /// #1693 — an empty cookie with an empty token is refused on
    /// every entry point: the form helper, the header and the form body.
    #[tokio::test]
    async fn an_empty_cookie_and_empty_token_are_refused() {
        use tower::ServiceExt as _;
        let mut headers = axum::http::HeaderMap::new();
        headers.insert(
            axum::http::header::COOKIE,
            format!("{CSRF_COOKIE}=").parse().unwrap(),
        );
        let mut passed = Vec::new();
        if verify_form_token(&headers, Some("")) {
            passed.push("verify_form_token");
        }

        let app = axum::Router::new()
            .route("/save", axum::routing::post(|| async { "saved" }))
            .layer(layer());
        let send = |req: Request<Body>| app.clone().oneshot(req);
        let base = || {
            Request::builder()
                .method("POST")
                .uri("/save")
                .header("cookie", "rustango_csrf=")
        };
        let by_header = base().header("x-csrf-token", "").body(Body::empty());
        let by_form = base()
            .header("content-type", "application/x-www-form-urlencoded")
            .body(Body::from("_csrf="));
        for (name, req) in [("header", by_header.unwrap()), ("form", by_form.unwrap())] {
            if send(req).await.unwrap().status() != StatusCode::FORBIDDEN {
                passed.push(name);
            }
        }
        assert!(passed.is_empty(), "empty tokens passed via {passed:?}");
    }

    /// #1695 — a matching pair from a foreign Origin is refused.
    #[test]
    fn verify_form_token_checks_origin() {
        let with = |origin: Option<&str>, proto: Option<&str>| {
            let mut h = axum::http::HeaderMap::new();
            h.insert(
                axum::http::header::COOKIE,
                format!("{CSRF_COOKIE}=tok").parse().unwrap(),
            );
            h.insert(axum::http::header::HOST, "t01.example.com".parse().unwrap());
            if let Some(o) = origin {
                h.insert(axum::http::header::ORIGIN, o.parse().unwrap());
            }
            if let Some(p) = proto {
                h.insert("x-forwarded-proto", p.parse().unwrap());
            }
            verify_form_token(&h, Some("tok"))
        };
        assert!(!with(Some("http://t02.example.com"), None));
        assert!(!with(Some("null"), None));
        assert!(with(Some("http://t01.example.com"), None));
        assert!(with(None, None), "plain http without Origin keeps working");
        assert!(!with(None, Some("https")), "over TLS, Origin is required");
    }

    #[test]
    fn csrf_input_html_escapes_attribute_specials() {
        // Defensive escape — base64url tokens never contain these,
        // but a user could pass in something else by accident.
        let html = csrf_input_html(r#"x"<&>'"#);
        assert!(
            !html.contains(r#"x"<&>'"#),
            "raw specials must NOT survive: {html}"
        );
        assert!(html.contains("&quot;"), "{html}");
        assert!(html.contains("&lt;"), "{html}");
        assert!(html.contains("&amp;"), "{html}");
        assert!(html.contains("&gt;"), "{html}");
        assert!(html.contains("&#x27;"), "{html}");
    }

    #[cfg(feature = "template_views")]
    #[test]
    fn stamp_into_context_stamps_both_keys_and_returns_set_cookie_on_fresh() {
        let headers = axum::http::HeaderMap::new(); // no cookie → fresh mint
        let mut ctx = tera::Context::new();
        let set_cookie = stamp_into_context(&headers, &mut ctx);

        assert!(set_cookie.is_some(), "fresh GET should return Set-Cookie");
        let json = ctx.into_json();
        let token = json
            .get("csrf_token")
            .and_then(|v| v.as_str())
            .expect("csrf_token stamped");
        let input_html = json
            .get("csrf_input")
            .and_then(|v| v.as_str())
            .expect("csrf_input stamped");
        assert!(!token.is_empty(), "minted token shouldn't be empty");
        assert!(
            input_html.contains(token),
            "csrf_input should embed the token: {input_html}"
        );
    }

    #[cfg(feature = "template_views")]
    #[test]
    fn stamp_into_context_reuses_existing_cookie_no_set_cookie() {
        let mut headers = axum::http::HeaderMap::new();
        headers.insert(
            axum::http::header::COOKIE,
            axum::http::HeaderValue::from_static(
                "rustango_csrf=fixed_value-fixed_value-fixed_value-fixed_v",
            ),
        );
        let mut ctx = tera::Context::new();
        let set_cookie = stamp_into_context(&headers, &mut ctx);

        assert!(set_cookie.is_none(), "existing cookie should not re-mint");
        let json = ctx.into_json();
        assert_eq!(
            json.get("csrf_token").and_then(|v| v.as_str()),
            Some("fixed_value-fixed_value-fixed_value-fixed_v")
        );
    }

    #[cfg(feature = "template_views")]
    #[test]
    fn csrf_input_filter_converts_token_to_html() {
        let mut tera = tera::Tera::default();
        register_csrf_filter(&mut tera);
        tera.add_raw_template("_", "{{ csrf_token | csrf_input | safe }}")
            .unwrap();

        let mut ctx = tera::Context::new();
        ctx.insert("csrf_token", "tok-abc");
        let out = tera.render("_", &ctx).unwrap();
        assert_eq!(out, r#"<input type="hidden" name="_csrf" value="tok-abc">"#);
    }

    #[cfg(feature = "template_views")]
    #[test]
    fn csrf_input_filter_passes_through_non_string_values() {
        let mut tera = tera::Tera::default();
        register_csrf_filter(&mut tera);
        // Number → filter passes through, Tera renders as the number.
        tera.add_raw_template("_", "{{ n | csrf_input }}").unwrap();
        let mut ctx = tera::Context::new();
        ctx.insert("n", &42_i64);
        assert_eq!(tera.render("_", &ctx).unwrap(), "42");
    }

    #[test]
    fn sets_cookie_spots_the_handlers_own_token() {
        let resp = axum::http::Response::builder()
            .header(axum::http::header::SET_COOKIE, "rustango_csrf=abc; Path=/")
            .body(())
            .unwrap();
        assert!(sets_cookie(&resp, "rustango_csrf"));
        assert!(!sets_cookie(&resp, "other_cookie"));
    }

    /// #1714 — no CSRF cookie rides on a publicly cacheable response.
    #[tokio::test]
    async fn no_cookie_is_seeded_on_a_public_cacheable_response() {
        use tower::ServiceExt as _;
        let app = axum::Router::new()
            .route(
                "/asset",
                axum::routing::get(|| async { ([("cache-control", "public, max-age=300")], "x") }),
            )
            .route("/page", axum::routing::get(|| async { "x" }))
            .layer(with_config(CsrfConfig::default().allow_insecure_for_dev()));
        let get = |uri: &'static str| {
            app.clone()
                .oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap())
        };
        assert!(get("/asset")
            .await
            .unwrap()
            .headers()
            .get("set-cookie")
            .is_none());
        assert!(get("/page")
            .await
            .unwrap()
            .headers()
            .get("set-cookie")
            .is_some());
    }

    /// #1714 — a large form (a long text field) is not refused for its
    /// size when it carries a valid token.
    #[tokio::test]
    async fn a_large_form_with_a_valid_token_passes() {
        use tower::ServiceExt as _;
        let app = axum::Router::new()
            .route("/save", axum::routing::post(|| async { "saved" }))
            .layer(with_config(CsrfConfig::default().allow_insecure_for_dev()));
        let body = format!("_csrf=tok&text={}", "a".repeat(200 * 1024));
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/save")
                    .header("cookie", "rustango_csrf=tok")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[test]
    fn sets_cookie_is_false_when_the_response_sets_none() {
        let resp = axum::http::Response::builder().body(()).unwrap();
        assert!(!sets_cookie(&resp, "rustango_csrf"));
    }

    #[test]
    fn sets_cookie_ignores_a_different_cookie_with_a_similar_prefix() {
        // `rustango_csrf_other=` must not count as `rustango_csrf`.
        let resp = axum::http::Response::builder()
            .header(axum::http::header::SET_COOKIE, "rustango_csrf_other=abc")
            .header(axum::http::header::SET_COOKIE, "session=xyz; HttpOnly")
            .body(())
            .unwrap();
        assert!(!sets_cookie(&resp, "rustango_csrf"));
    }
}