rustango 0.61.13

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
//! Security headers middleware — HSTS, X-Frame-Options, X-Content-Type-Options,
//! Referrer-Policy, Cross-Origin-Opener-Policy, and a Content-Security-Policy builder.
//!
//! Nothing is added for you: you **must mount the layer yourself**.
//! The presets cover the common cases.
//!
//! ## Quick start
//!
//! ```ignore
//! use rustango::security_headers::{SecurityHeadersLayer, SecurityHeadersRouterExt};
//!
//! let app = Router::new()
//!     .route("/api/posts", get(list_posts))
//!     .security_headers(SecurityHeadersLayer::strict());
//! ```
//!
//! ## Presets
//!
//! - [`SecurityHeadersLayer::strict`]: for production.
//! - [`SecurityHeadersLayer::relaxed`]: allows same-origin framing.
//! - [`SecurityHeadersLayer::dev`]: `nosniff` only. HSTS is left out
//!   so you do not pin your dev machine to HTTPS.
//!
//! ## Custom CSP
//!
//! ```ignore
//! let csp = CspBuilder::new()
//!     .default_src(&["'self'"])
//!     .script_src(&["'self'", "https://cdn.example.com"])
//!     .style_src(&["'self'", "'unsafe-inline'"])
//!     .img_src(&["'self'", "data:", "https:"])
//!     .build();
//!
//! let layer = SecurityHeadersLayer::strict().csp(csp);
//! ```
//!
//! [`SecurityHeadersLayer::strict`]: crate::security_headers::SecurityHeadersLayer::strict
//! [`SecurityHeadersLayer::relaxed`]: crate::security_headers::SecurityHeadersLayer::relaxed
//! [`SecurityHeadersLayer::dev`]: crate::security_headers::SecurityHeadersLayer::dev

use std::collections::BTreeMap;
use std::sync::Arc;

use axum::body::Body;
use axum::http::header::HeaderValue;
use axum::http::{HeaderName, Request, Response};
use axum::middleware::Next;
use axum::Router;

/// Configuration for the security headers middleware.
///
/// A header the handler already set is kept, not overwritten.
#[derive(Clone)]
pub struct SecurityHeadersLayer {
    pub hsts: Option<String>,
    pub xfo: Option<&'static str>,
    pub nosniff: bool,
    pub referrer_policy: Option<&'static str>,
    pub coop: Option<&'static str>,
    pub permissions_policy: Option<String>,
    pub csp: Option<String>,
    pub csp_report_only: bool,
    /// Custom additional headers — applied last.
    pub custom: BTreeMap<String, String>,
}

impl Default for SecurityHeadersLayer {
    fn default() -> Self {
        Self::strict()
    }
}

impl SecurityHeadersLayer {
    /// Empty config — no headers set. Build up with the chainable setters.
    #[must_use]
    pub fn empty() -> Self {
        Self {
            hsts: None,
            xfo: None,
            nosniff: false,
            referrer_policy: None,
            coop: None,
            permissions_policy: None,
            csp: None,
            csp_report_only: false,
            custom: BTreeMap::new(),
        }
    }

    /// Production preset.
    ///
    /// - HSTS: `max-age=31536000; includeSubDomains; preload`
    /// - X-Frame-Options: `DENY`
    /// - X-Content-Type-Options: `nosniff`
    /// - Referrer-Policy: `same-origin` (not `no-referrer`: that makes browsers send `Origin: null`)
    /// - Cross-Origin-Opener-Policy: `same-origin`
    /// - Permissions-Policy: `camera=(), microphone=(), geolocation=()`
    #[must_use]
    pub fn strict() -> Self {
        Self {
            hsts: Some("max-age=31536000; includeSubDomains; preload".into()),
            xfo: Some("DENY"),
            nosniff: true,
            referrer_policy: Some("same-origin"),
            coop: Some("same-origin"),
            permissions_policy: Some("camera=(), microphone=(), geolocation=()".into()),
            csp: None,
            csp_report_only: false,
            custom: BTreeMap::new(),
        }
    }

    /// Preset that allows same-origin framing.
    ///
    /// - HSTS: 1 year (no preload, no subdomains)
    /// - X-Frame-Options: `SAMEORIGIN`
    /// - X-Content-Type-Options: `nosniff`
    /// - Referrer-Policy: `strict-origin-when-cross-origin`
    #[must_use]
    pub fn relaxed() -> Self {
        Self {
            hsts: Some("max-age=31536000".into()),
            xfo: Some("SAMEORIGIN"),
            nosniff: true,
            referrer_policy: Some("strict-origin-when-cross-origin"),
            coop: None,
            permissions_policy: None,
            csp: None,
            csp_report_only: false,
            custom: BTreeMap::new(),
        }
    }

    /// Development preset: `nosniff` only. HSTS is left out on
    /// purpose, so you do not pin your dev machine to HTTPS.
    #[must_use]
    pub fn dev() -> Self {
        Self {
            hsts: None,
            xfo: None,
            nosniff: true,
            referrer_policy: None,
            coop: None,
            permissions_policy: None,
            csp: None,
            csp_report_only: false,
            custom: BTreeMap::new(),
        }
    }

    /// Override the HSTS header value (or set to None to remove).
    #[must_use]
    pub fn hsts(mut self, value: impl Into<String>) -> Self {
        self.hsts = Some(value.into());
        self
    }

    /// Set X-Frame-Options (`DENY`, `SAMEORIGIN`, or remove with `None`).
    #[must_use]
    pub fn xfo(mut self, value: &'static str) -> Self {
        self.xfo = Some(value);
        self
    }

    /// Attach a Content-Security-Policy. Build via [`CspBuilder`].
    #[must_use]
    pub fn csp(mut self, csp: String) -> Self {
        self.csp = Some(csp);
        self
    }

    /// Send CSP as `Content-Security-Policy-Report-Only` instead of enforcing.
    /// Use during rollout to monitor without breaking the page.
    #[must_use]
    pub fn csp_report_only(mut self, yes: bool) -> Self {
        self.csp_report_only = yes;
        self
    }

    /// Set the CSP `report-uri`. The browser POSTs violation reports
    /// there. Use [`csp_report_router`] to receive them.
    ///
    /// `report-uri` is deprecated in favour of `report-to`, which also
    /// needs a `Report-To` header naming an endpoint group.
    #[must_use]
    pub fn csp_report_uri(mut self, uri: &str) -> Self {
        if let Some(existing) = self.csp.as_mut() {
            existing.push_str(&format!("; report-uri {uri}"));
        } else {
            self.csp = Some(format!("default-src 'self'; report-uri {uri}"));
        }
        self
    }

    /// Add an arbitrary custom header. Overrides the preset's value
    /// for the same name.
    #[must_use]
    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.custom.insert(name.into(), value.into());
        self
    }

    /// Build the layer from a preset name:
    ///
    /// | name              | preset            |
    /// |-------------------|-------------------|
    /// | `"strict"`        | [`Self::strict`]  |
    /// | `"relaxed"`       | [`Self::relaxed`] |
    /// | `"dev"`           | [`Self::dev`]     |
    /// | `"none"`/`"empty"`| [`Self::empty`]   |
    ///
    /// Any other name gives [`Self::strict`]. A typo must not strip
    /// the security headers.
    #[must_use]
    pub fn from_preset(name: &str) -> Self {
        match name {
            "strict" => Self::strict(),
            "relaxed" => Self::relaxed(),
            "dev" => Self::dev(),
            "none" | "empty" => Self::empty(),
            // Unknown names get strict headers, never no headers.
            // `manage check --deploy` warns about the typo separately.
            _ => Self::strict(),
        }
    }

    /// Build the layer from a [`crate::config::SecuritySettings`]
    /// section. It starts from [`Self::from_preset`], using `strict`
    /// when `headers_preset` is unset, then applies overrides:
    ///
    /// - `csp` sets the Content-Security-Policy header as given.
    /// - `hsts_max_age_secs = 0` turns HSTS off.
    /// - A larger value rebuilds HSTS with that age and keeps
    ///   `includeSubDomains` and `preload`.
    ///
    /// ```no_run
    /// # use rustango::security_headers::{SecurityHeadersLayer, SecurityHeadersRouterExt};
    /// # fn wire(app: axum::Router) -> Result<axum::Router, Box<dyn std::error::Error>> {
    /// let cfg = rustango::config::Settings::load_from_env()?;
    /// let layer = SecurityHeadersLayer::from_settings(&cfg.security);
    /// let app = app.security_headers(layer);
    /// # Ok(app) }
    /// ```
    #[cfg(feature = "config")]
    #[must_use]
    pub fn from_settings(s: &crate::config::SecuritySettings) -> Self {
        let mut layer = match s.headers_preset.as_deref() {
            Some(name) => Self::from_preset(name),
            None => Self::strict(),
        };
        if let Some(csp) = s.csp.as_ref() {
            layer.csp = Some(csp.clone());
        }
        if let Some(secs) = s.hsts_max_age_secs {
            if adds_hsts_directives(layer.hsts.as_deref(), secs) {
                tracing::warn!(
                    target: "rustango::security_headers",
                    "[security] hsts_max_age_secs adds `includeSubDomains; preload` to preset {:?}, \
                     which sends neither; 0.62.0 will keep the preset's directives",
                    s.headers_preset.as_deref().unwrap_or("strict"),
                );
            }
            layer.hsts = if secs == 0 {
                None
            } else {
                Some(format!("max-age={secs}; includeSubDomains; preload"))
            };
        }
        layer
    }
}

/// `hsts_max_age_secs = secs` would add `preload` the preset's HSTS lacks:
/// browsers cache it, so 0.61 keeps adding it and only warns.
#[cfg(feature = "config")]
fn adds_hsts_directives(preset: Option<&str>, secs: u64) -> bool {
    secs != 0 && !preset.is_some_and(|v| v.split(';').any(|p| p.trim() == "preload"))
}

/// Extension trait — `.security_headers(layer)` on Router.
pub trait SecurityHeadersRouterExt {
    #[must_use]
    fn security_headers(self, layer: SecurityHeadersLayer) -> Self;
}

impl<S: Clone + Send + Sync + 'static> SecurityHeadersRouterExt for Router<S> {
    fn security_headers(self, layer: SecurityHeadersLayer) -> Self {
        let cfg = Arc::new(layer);
        self.layer(axum::middleware::from_fn(
            move |req: Request<Body>, next: Next| {
                let cfg = cfg.clone();
                async move { handle(cfg, req, next).await }
            },
        ))
    }
}

async fn handle(cfg: Arc<SecurityHeadersLayer>, req: Request<Body>, next: Next) -> Response<Body> {
    let mut response = next.run(req).await;
    // Build the layer's own set first (a `.header()` overrides the
    // preset), then add only what the handler did not set (#1699).
    let mut own = axum::http::HeaderMap::new();
    let mut set = |name: &str, value: &str| {
        if let (Ok(n), Ok(v)) = (HeaderName::try_from(name), HeaderValue::from_str(value)) {
            own.insert(n, v);
        }
    };

    if let Some(v) = &cfg.hsts {
        set("strict-transport-security", v);
    }
    if let Some(v) = cfg.xfo {
        set("x-frame-options", v);
    }
    if cfg.nosniff {
        set("x-content-type-options", "nosniff");
    }
    if let Some(v) = cfg.referrer_policy {
        set("referrer-policy", v);
    }
    if let Some(v) = cfg.coop {
        set("cross-origin-opener-policy", v);
    }
    if let Some(v) = &cfg.permissions_policy {
        set("permissions-policy", v);
    }
    if let Some(v) = &cfg.csp {
        let name = if cfg.csp_report_only {
            "content-security-policy-report-only"
        } else {
            "content-security-policy"
        };
        set(name, v);
    }
    for (k, v) in &cfg.custom {
        set(k, v);
    }

    let headers = response.headers_mut();
    for (name, value) in own {
        if let Some(name) = name {
            headers.entry(name).or_insert(value);
        }
    }
    response
}

// ------------------------------------------------------------------ CSP report endpoint

/// Build a router with a CSP-violation report endpoint at `path`,
/// usually `/__csp-report`. The browser POSTs a JSON report there
/// when a directive is violated, and the handler logs it with
/// `tracing::warn!`.
///
/// ## Quick start
///
/// ```ignore
/// use rustango::security_headers::{csp_report_router, SecurityHeadersLayer, CspBuilder};
///
/// let app = Router::new()
///     .route("/", get(home))
///     .merge(csp_report_router("/__csp-report"))
///     .security_headers(
///         SecurityHeadersLayer::strict()
///             .csp(CspBuilder::strict_starter().build())
///             .csp_report_uri("/__csp-report"),
///     );
/// ```
///
/// Reports look like:
/// ```json
/// {"csp-report": {
///   "document-uri": "https://app.example.com/page",
///   "violated-directive": "script-src 'self'",
///   "blocked-uri": "inline",
///   ...
/// }}
/// ```
///
/// It takes `application/csp-report` (`report-uri`), the Reporting API's
/// `application/reports+json` and plain JSON, up to 64 KiB. The CSRF layer
/// lets the two report types through without a token only at a path in
/// [`crate::forms::csrf::CsrfConfig::report_paths`] (default `/__csp-report`).
pub fn csp_report_router(path: &str) -> axum::Router {
    use axum::routing::post;
    let path = path.to_owned();
    axum::Router::new().route(
        &path,
        post(handle_csp_report).layer(axum::extract::DefaultBodyLimit::max(CSP_REPORT_MAX_BYTES)),
    )
}

/// Largest CSP report body accepted.
const CSP_REPORT_MAX_BYTES: usize = 64 * 1024;

async fn handle_csp_report(body: axum::body::Bytes) -> axum::http::StatusCode {
    let Ok(value) = serde_json::from_slice::<serde_json::Value>(&body) else {
        return axum::http::StatusCode::BAD_REQUEST;
    };
    match value {
        // Reporting API: `[{"type": "csp-violation", "body": {...}}, ...]`.
        serde_json::Value::Array(reports) => {
            let mut violations = reports.iter().filter(|r| r["type"] == "csp-violation");
            for r in violations.by_ref().take(CSP_REPORTS_LOGGED) {
                let b = &r["body"];
                log_csp_violation(
                    str_at(b, "documentURL"),
                    str_at(b, "effectiveDirective"),
                    str_at(b, "blockedURL"),
                );
            }
            let skipped = violations.count();
            if skipped > 0 {
                tracing::warn!(skipped, "CSP violation reports not logged");
            }
        }
        // `report-uri`: `{"csp-report": {...}}`.
        v => {
            let report = v.get("csp-report").unwrap_or(&v);
            log_csp_violation(
                str_at(report, "document-uri"),
                str_at(report, "violated-directive"),
                str_at(report, "blocked-uri"),
            );
        }
    }
    axum::http::StatusCode::NO_CONTENT
}

fn str_at<'a>(v: &'a serde_json::Value, key: &str) -> &'a str {
    v.get(key).and_then(|v| v.as_str()).unwrap_or("?")
}

/// Violations logged per request; one body of tiny reports was thousands of lines.
const CSP_REPORTS_LOGGED: usize = 10;

// `?` escapes the newlines a forged report may carry.
fn log_csp_violation(document_uri: &str, violated: &str, blocked: &str) {
    // Query and fragment can carry tokens (`?token=`, `?code=`): log the path only.
    let no_query = |u: &'_ str| u.split(['?', '#']).next().unwrap_or_default().to_owned();
    tracing::warn!(
        document_uri = ?no_query(document_uri),
        violated_directive = ?violated,
        blocked_uri = ?no_query(blocked),
        "CSP violation report",
    );
}

// ------------------------------------------------------------------ CspBuilder

/// Builder for a Content-Security-Policy header value.
///
/// ```
/// use rustango::security_headers::CspBuilder;
/// let csp = CspBuilder::new()
///     .default_src(&["'self'"])
///     .script_src(&["'self'", "https://cdn.example.com"])
///     .img_src(&["'self'", "data:"])
///     .build();
/// assert!(csp.contains("default-src 'self'"));
/// assert!(csp.contains("script-src 'self' https://cdn.example.com"));
/// ```
#[derive(Debug, Clone, Default)]
pub struct CspBuilder {
    directives: BTreeMap<String, Vec<String>>,
}

impl CspBuilder {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    fn set(&mut self, name: &str, sources: &[&str]) {
        self.directives.insert(
            name.to_owned(),
            sources.iter().map(|s| (*s).to_owned()).collect(),
        );
    }

    #[must_use]
    pub fn default_src(mut self, sources: &[&str]) -> Self {
        self.set("default-src", sources);
        self
    }

    #[must_use]
    pub fn script_src(mut self, sources: &[&str]) -> Self {
        self.set("script-src", sources);
        self
    }

    #[must_use]
    pub fn style_src(mut self, sources: &[&str]) -> Self {
        self.set("style-src", sources);
        self
    }

    #[must_use]
    pub fn img_src(mut self, sources: &[&str]) -> Self {
        self.set("img-src", sources);
        self
    }

    #[must_use]
    pub fn font_src(mut self, sources: &[&str]) -> Self {
        self.set("font-src", sources);
        self
    }

    #[must_use]
    pub fn connect_src(mut self, sources: &[&str]) -> Self {
        self.set("connect-src", sources);
        self
    }

    #[must_use]
    pub fn frame_src(mut self, sources: &[&str]) -> Self {
        self.set("frame-src", sources);
        self
    }

    #[must_use]
    pub fn frame_ancestors(mut self, sources: &[&str]) -> Self {
        self.set("frame-ancestors", sources);
        self
    }

    #[must_use]
    pub fn object_src(mut self, sources: &[&str]) -> Self {
        self.set("object-src", sources);
        self
    }

    /// Add any other directive that has no named method here.
    #[must_use]
    pub fn directive(mut self, name: impl Into<String>, sources: &[&str]) -> Self {
        let name = name.into();
        self.directives
            .insert(name, sources.iter().map(|s| (*s).to_owned()).collect());
        self
    }

    /// Strict starter preset: `default-src 'self'; object-src 'none'; base-uri 'self'`.
    #[must_use]
    pub fn strict_starter() -> Self {
        Self::new()
            .default_src(&["'self'"])
            .object_src(&["'none'"])
            .directive("base-uri", &["'self'"])
    }

    /// Render the policy as a string ready to drop into the CSP header.
    #[must_use]
    pub fn build(&self) -> String {
        self.directives
            .iter()
            .map(|(k, v)| format!("{k} {}", v.join(" ")))
            .collect::<Vec<_>>()
            .join("; ")
    }
}

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

    #[test]
    fn strict_preset_has_all_canonical_headers() {
        let l = SecurityHeadersLayer::strict();
        assert!(l.hsts.is_some());
        assert_eq!(l.xfo, Some("DENY"));
        assert!(l.nosniff);
        assert_eq!(l.referrer_policy, Some("same-origin"));
        assert_eq!(l.coop, Some("same-origin"));
        assert!(l.permissions_policy.is_some());
    }

    /// A header the handler set is kept (#1699): the impersonation
    /// handoff's `no-referrer` must survive the outer layer.
    #[tokio::test]
    async fn a_header_the_handler_set_wins() {
        use axum::routing::get;
        use tower::ServiceExt as _;
        let app = Router::new()
            .route(
                "/",
                get(|| async { ([("referrer-policy", "no-referrer")], "ok") }),
            )
            .security_headers(SecurityHeadersLayer::strict());
        let resp = app
            .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(resp.headers()["referrer-policy"], "no-referrer");
        assert_eq!(resp.headers()["x-frame-options"], "DENY");
    }

    /// `.header()` still overrides the preset for the same name.
    #[tokio::test]
    async fn a_custom_header_overrides_the_preset() {
        use axum::routing::get;
        use tower::ServiceExt as _;
        let app = Router::new()
            .route("/", get(|| async { "ok" }))
            .security_headers(
                SecurityHeadersLayer::strict().header("x-frame-options", "SAMEORIGIN"),
            );
        let resp = app
            .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(resp.headers()["x-frame-options"], "SAMEORIGIN");
    }

    /// Under `no-referrer` browsers send `Origin: null` on every POST,
    /// and the CSRF Origin check refuses it, so no form works (#1695).
    #[test]
    fn no_preset_makes_browsers_send_a_null_origin() {
        for l in [
            SecurityHeadersLayer::strict(),
            SecurityHeadersLayer::relaxed(),
            SecurityHeadersLayer::dev(),
        ] {
            assert_ne!(l.referrer_policy, Some("no-referrer"));
        }
    }

    #[test]
    fn relaxed_preset_allows_same_origin_framing() {
        let l = SecurityHeadersLayer::relaxed();
        assert_eq!(l.xfo, Some("SAMEORIGIN"));
        assert!(l.hsts.is_some());
        assert!(l.coop.is_none());
    }

    #[test]
    fn dev_preset_only_nosniff() {
        let l = SecurityHeadersLayer::dev();
        assert!(
            l.hsts.is_none(),
            "dev must NOT set HSTS — would lock localhost to https"
        );
        assert!(l.xfo.is_none());
        assert!(l.nosniff);
    }

    #[test]
    fn empty_preset_sets_nothing() {
        let l = SecurityHeadersLayer::empty();
        assert!(l.hsts.is_none());
        assert!(!l.nosniff);
        assert!(l.csp.is_none());
    }

    #[test]
    fn custom_header_chained_in() {
        let l = SecurityHeadersLayer::strict().header("x-custom", "value");
        assert_eq!(l.custom.get("x-custom").map(String::as_str), Some("value"));
    }

    #[test]
    fn csp_builder_basic() {
        let csp = CspBuilder::new().default_src(&["'self'"]).build();
        assert_eq!(csp, "default-src 'self'");
    }

    #[test]
    fn csp_builder_multi_source() {
        let csp = CspBuilder::new()
            .script_src(&["'self'", "https://cdn.example.com"])
            .build();
        assert_eq!(csp, "script-src 'self' https://cdn.example.com");
    }

    #[test]
    fn csp_builder_multiple_directives_joined_by_semicolon() {
        let csp = CspBuilder::new()
            .default_src(&["'self'"])
            .img_src(&["'self'", "data:"])
            .build();
        // BTreeMap orders alphabetically: default-src then img-src
        assert_eq!(csp, "default-src 'self'; img-src 'self' data:");
    }

    #[test]
    fn csp_builder_strict_starter_preset() {
        let csp = CspBuilder::strict_starter().build();
        assert!(csp.contains("default-src 'self'"));
        assert!(csp.contains("object-src 'none'"));
        assert!(csp.contains("base-uri 'self'"));
    }

    #[test]
    fn csp_builder_directive_helper() {
        let csp = CspBuilder::new()
            .directive("upgrade-insecure-requests", &[])
            .build();
        assert!(csp.contains("upgrade-insecure-requests"));
    }

    #[test]
    fn csp_attached_to_layer() {
        let csp = CspBuilder::new().default_src(&["'self'"]).build();
        let l = SecurityHeadersLayer::strict().csp(csp.clone());
        assert_eq!(l.csp.as_deref(), Some(csp.as_str()));
    }

    #[test]
    fn report_only_flag_toggles() {
        let l = SecurityHeadersLayer::strict()
            .csp("default-src 'self'".into())
            .csp_report_only(true);
        assert!(l.csp_report_only);
    }

    #[test]
    fn csp_report_uri_appends_to_existing_csp() {
        let l = SecurityHeadersLayer::strict()
            .csp("default-src 'self'".into())
            .csp_report_uri("/__csp-report");
        let csp = l.csp.unwrap();
        assert!(csp.contains("default-src 'self'"));
        assert!(csp.contains("report-uri /__csp-report"));
    }

    #[test]
    fn csp_report_uri_creates_default_csp_if_missing() {
        let l = SecurityHeadersLayer::strict().csp_report_uri("/__csp-report");
        let csp = l.csp.unwrap();
        assert!(csp.contains("default-src 'self'"));
        assert!(csp.contains("report-uri"));
    }

    // ---- from_preset + from_settings ----

    #[test]
    fn from_preset_maps_known_names() {
        assert_eq!(
            SecurityHeadersLayer::from_preset("strict").hsts.as_deref(),
            SecurityHeadersLayer::strict().hsts.as_deref(),
        );
        assert!(SecurityHeadersLayer::from_preset("dev").hsts.is_none());
        assert!(SecurityHeadersLayer::from_preset("none").hsts.is_none());
        assert!(!SecurityHeadersLayer::from_preset("none").nosniff);
    }

    /// An unknown preset name falls back to `strict()`. A typo in the
    /// TOML must not strip security headers in production.
    #[test]
    fn from_preset_unknown_name_fails_safe_to_strict() {
        let l = SecurityHeadersLayer::from_preset("strixt"); // typo
        assert_eq!(
            l.hsts.as_deref(),
            SecurityHeadersLayer::strict().hsts.as_deref(),
            "unknown preset should yield strict, not empty"
        );
    }

    #[cfg(feature = "config")]
    #[test]
    fn from_settings_default_picks_strict() {
        let s = crate::config::SecuritySettings::default();
        let l = SecurityHeadersLayer::from_settings(&s);
        assert_eq!(
            l.hsts.as_deref(),
            SecurityHeadersLayer::strict().hsts.as_deref(),
        );
    }

    #[cfg(feature = "config")]
    #[test]
    fn from_settings_honors_preset_name() {
        let mut s = crate::config::SecuritySettings::default();
        s.headers_preset = Some("dev".into());
        let l = SecurityHeadersLayer::from_settings(&s);
        assert!(l.hsts.is_none());
    }

    /// `hsts_max_age_secs = 0` turns HSTS off even if the preset set
    /// it. Useful on a staging tier with a self-signed certificate.
    #[cfg(feature = "config")]
    #[test]
    fn from_settings_zero_hsts_disables_header() {
        let mut s = crate::config::SecuritySettings::default();
        s.headers_preset = Some("strict".into());
        s.hsts_max_age_secs = Some(0);
        let l = SecurityHeadersLayer::from_settings(&s);
        assert!(l.hsts.is_none(), "hsts_max_age_secs = 0 should drop HSTS");
    }

    #[cfg(feature = "config")]
    #[test]
    fn from_settings_custom_hsts_max_age() {
        let mut s = crate::config::SecuritySettings::default();
        s.hsts_max_age_secs = Some(60);
        let l = SecurityHeadersLayer::from_settings(&s);
        let hsts = l.hsts.expect("hsts present");
        assert!(hsts.contains("max-age=60"), "got: {hsts}");
        assert!(
            hsts.contains("includeSubDomains"),
            "preserved subdomain inclusion"
        );
    }

    /// A max-age on a preset without `preload` still adds it, with a warning.
    #[cfg(feature = "config")]
    #[test]
    fn a_max_age_on_a_preset_without_preload_warns() {
        let relaxed = SecurityHeadersLayer::relaxed();
        let strict = SecurityHeadersLayer::strict();
        assert!(adds_hsts_directives(relaxed.hsts.as_deref(), 60));
        assert!(adds_hsts_directives(None, 60), "dev / none send no HSTS");
        assert!(!adds_hsts_directives(strict.hsts.as_deref(), 60));
        assert!(!adds_hsts_directives(relaxed.hsts.as_deref(), 0));

        let mut s = crate::config::SecuritySettings::default();
        s.headers_preset = Some("relaxed".into());
        s.hsts_max_age_secs = Some(60);
        assert_eq!(
            SecurityHeadersLayer::from_settings(&s).hsts.as_deref(),
            Some("max-age=60; includeSubDomains; preload"),
            "the output itself is unchanged in 0.61"
        );
    }

    #[cfg(feature = "config")]
    #[test]
    fn from_settings_custom_csp_overrides_preset() {
        let mut s = crate::config::SecuritySettings::default();
        s.csp = Some("default-src 'self'; img-src *".into());
        let l = SecurityHeadersLayer::from_settings(&s);
        assert_eq!(l.csp.as_deref(), Some("default-src 'self'; img-src *"));
    }
}

#[cfg(all(test, feature = "csrf"))]
mod csp_report_tests {
    use axum::body::Body;
    use axum::http::Request;
    use tower::ServiceExt as _;

    /// The app as deployed: report route behind the CSRF layer.
    async fn post(content_type: &str, origin: Option<&str>, body: String) -> u16 {
        let app = super::csp_report_router("/__csp-report").layer(crate::forms::csrf::layer());
        let mut req = Request::post("/__csp-report")
            .header("host", "app.test")
            .header("content-type", content_type);
        if let Some(o) = origin {
            req = req.header("origin", o);
        }
        let resp = app
            .oneshot(req.body(Body::from(body)).unwrap())
            .await
            .unwrap();
        resp.status().as_u16()
    }

    #[tokio::test]
    async fn browser_report_types_are_accepted_without_a_token() {
        let legacy = r#"{"csp-report":{"document-uri":"http://app.test/","violated-directive":"script-src","blocked-uri":"inline"}}"#;
        let api = r#"[{"type":"csp-violation","body":{"documentURL":"http://app.test/","effectiveDirective":"script-src","blockedURL":"inline"}}]"#;
        let origin = Some("http://app.test");
        assert_eq!(
            post("application/csp-report", origin, legacy.into()).await,
            204
        );
        assert_eq!(
            post("application/reports+json", origin, api.into()).await,
            204
        );
    }

    #[tokio::test]
    async fn report_types_still_need_a_same_origin_and_a_small_body() {
        let legacy = r#"{"csp-report":{}}"#;
        let evil = Some("http://evil.example");
        assert_eq!(
            post("application/csp-report", evil, legacy.into()).await,
            403
        );
        let big = format!(r#"{{"csp-report":{{"x":"{}"}}}}"#, "a".repeat(100 * 1024));
        assert_eq!(post("application/csp-report", None, big).await, 413);
        assert_eq!(
            post("text/plain", None, legacy.into()).await,
            403,
            "other types need the token"
        );
    }

    /// Only the report route skips the token; `Json` also reads `+json` types.
    #[tokio::test]
    async fn report_types_need_the_token_on_other_routes() {
        let api = axum::Router::new()
            .route(
                "/api/items",
                axum::routing::post(|b: String| async move { b }),
            )
            .merge(super::csp_report_router("/__csp-report"))
            .layer(crate::forms::csrf::layer())
            .layer(crate::forms::csrf::layer());
        for ct in ["application/reports+json", "application/csp-report"] {
            let req = Request::post("/api/items")
                .header("host", "app.test")
                .header("origin", "http://app.test")
                .header("content-type", ct)
                .body(Body::from("[]"))
                .unwrap();
            let resp = api.clone().oneshot(req).await.unwrap();
            assert_eq!(resp.status().as_u16(), 403, "{ct}");
        }
    }

    /// A big batch logs a bounded number of lines, each on one line.
    #[cfg(feature = "runtime")]
    #[test]
    fn a_report_batch_logs_a_bounded_number_of_lines() {
        let buf = crate::testkit::CaptureWriter::default();
        let subscriber = tracing_subscriber::fmt()
            .with_writer(buf.clone())
            .with_ansi(false)
            .finish();
        let one = r#"{"type":"csp-violation","body":{"documentURL":"a\nFAKE b"}}"#;
        let body = format!("[{}]", vec![one; 500].join(","));
        let rt = tokio::runtime::Builder::new_current_thread()
            .build()
            .unwrap();
        let status = tracing::subscriber::with_default(subscriber, || {
            rt.block_on(super::handle_csp_report(body.into()))
        });
        assert_eq!(status, 204);
        let out = buf.contents();
        assert_eq!(out.lines().count(), 10 + 1, "{out}");
        assert!(!out.lines().any(|l| l.starts_with("FAKE")), "{out}");
        assert!(out.contains("skipped=490"), "{out}");
    }

    #[cfg(feature = "runtime")]
    #[test]
    fn a_report_logs_urls_without_query_or_fragment() {
        let buf = crate::testkit::CaptureWriter::default();
        let subscriber = tracing_subscriber::fmt()
            .with_writer(buf.clone())
            .with_ansi(false)
            .finish();
        let body = r#"{"csp-report":{"document-uri":"https://app.test/reset?token=SECRET1#x","violated-directive":"img-src","blocked-uri":"https://app.test/cb?code=SECRET2"}}"#;
        let rt = tokio::runtime::Builder::new_current_thread()
            .build()
            .unwrap();
        let status = tracing::subscriber::with_default(subscriber, || {
            rt.block_on(super::handle_csp_report(body.into()))
        });
        assert_eq!(status, 204);
        let out = buf.contents();
        assert!(out.contains("https://app.test/reset"), "{out}");
        assert!(!out.contains("SECRET"), "{out}");
    }

    /// Over HTTPS a report with no Origin is taken; a foreign one is not.
    #[tokio::test]
    async fn https_report_without_origin_is_accepted() {
        let send = |origin: Option<&'static str>| async move {
            let app = super::csp_report_router("/__csp-report").layer(crate::forms::csrf::layer());
            let mut req = Request::post("/__csp-report")
                .header("host", "app.test")
                .header("x-forwarded-proto", "https")
                .header("content-type", "application/csp-report");
            if let Some(o) = origin {
                req = req.header("origin", o);
            }
            let body = Body::from(r#"{"csp-report":{}}"#);
            app.oneshot(req.body(body).unwrap())
                .await
                .unwrap()
                .status()
                .as_u16()
        };
        assert_eq!(send(None).await, 204);
        assert_eq!(send(Some("https://app.test")).await, 204);
        assert_eq!(send(Some("https://evil.example")).await, 403);
    }
}