Skip to main content

webserver_base/webserver/
security.rs

1//! Browser security headers, sent by default ([`SecurityHeaders::new`]). Replace the set with
2//! [`WebServer::security_headers`](super::WebServer::security_headers), or turn it off with
3//! [`WebServer::without_security_headers`](super::WebServer::without_security_headers) (rarely right).
4//!
5//! Every response gets `X-Content-Type-Options`, `Referrer-Policy` and `Permissions-Policy`.
6//! An HTML response also gets `frame-ancestors`, `X-Frame-Options`, and the optional
7//! [`ContentSecurityPolicy`]. An enforced policy carries `frame-ancestors` inside the one
8//! `Content-Security-Policy` header; a report-only policy ignores that directive, so then
9//! `frame-ancestors` stays enforced in its own header. The layer only sets headers; it never rewrites a body. A policy that
10//! uses `{nonce}` gets a fresh nonce per request, which the layer hands to rendering as
11//! `{{nonce}}` (see [`current_nonce`]); a template writes `nonce="{{nonce}}"` on each script it
12//! trusts, so a script injected without it is blocked.
13
14use std::collections::BTreeSet;
15use std::sync::Arc;
16
17use axum::extract::{Request, State};
18use axum::http::header::{self, HeaderName, HeaderValue};
19use axum::middleware::Next;
20use axum::response::Response;
21use uuid::Uuid;
22
23tokio::task_local! {
24    /// The nonce of the request being served, set by the layer for the handler's whole run.
25    static NONCE: Arc<str>;
26}
27
28/// The current request's CSP nonce, for a template's `{{nonce}}`; empty when the request has none
29/// (no policy uses `{nonce}`, or the call is off the request's task, such as a spawned one).
30#[must_use]
31pub fn current_nonce() -> String {
32    NONCE
33        .try_with(|nonce: &Arc<str>| nonce.to_string())
34        .unwrap_or_default()
35}
36
37/// The placeholder in a [`ContentSecurityPolicy`] directive that becomes the response's nonce.
38pub const NONCE_PLACEHOLDER: &str = "{nonce}";
39
40const DEFAULT_REFERRER_POLICY: &str = "strict-origin-when-cross-origin";
41const DEFAULT_PERMISSIONS_POLICY: &str =
42    "camera=(), microphone=(), geolocation=(), payment=(), usb=()";
43const DEFAULT_FRAME_ANCESTORS: &str = "'none'";
44
45/// Whether a violation blocks the load or is only reported.
46#[derive(Clone, Copy, Debug, Eq, PartialEq)]
47pub enum CspMode {
48    /// `Content-Security-Policy-Report-Only`: nothing is blocked; the browser reports.
49    ReportOnly,
50    /// `Content-Security-Policy`: violations are blocked and reported.
51    Enforce,
52}
53
54/// A Content-Security-Policy, built from directives.
55///
56/// A directive value containing [`NONCE_PLACEHOLDER`] gets this response's nonce. Templates read
57/// the same value as `{{nonce}}` and write it on their own scripts; the layer does not touch the
58/// body. Prefer [`SecurityHeaders::frame_ancestors`] over listing `frame-ancestors` here; if you do
59/// list it, an enforced policy is merged with the server's so the stricter one holds (never
60/// weaker than both applied together). A report-only policy never enforces it.
61#[derive(Clone, Debug)]
62pub struct ContentSecurityPolicy {
63    mode: CspMode,
64    directives: Vec<(String, String)>,
65    report_uri: Option<String>,
66}
67
68impl ContentSecurityPolicy {
69    /// An empty policy in `mode`; add directives with [`directive`](Self::directive).
70    #[must_use]
71    pub const fn new(mode: CspMode) -> Self {
72        Self {
73            mode,
74            directives: Vec::new(),
75            report_uri: None,
76        }
77    }
78
79    /// Adds `name value`, such as `("script-src", "'self' 'nonce-{nonce}'")`.
80    #[must_use]
81    pub fn directive(mut self, name: &str, value: &str) -> Self {
82        self.directives.push((name.to_owned(), value.to_owned()));
83        self
84    }
85
86    /// Where the browser posts violation reports (`report-uri`).
87    #[must_use]
88    pub fn report_uri(mut self, uri: &str) -> Self {
89        self.report_uri = Some(uri.to_owned());
90        self
91    }
92
93    fn uses_nonce(&self) -> bool {
94        self.directives
95            .iter()
96            .any(|(_, value): &(String, String)| value.contains(NONCE_PLACEHOLDER))
97    }
98
99    /// The policy text, with `frame_ancestors` (the server's own sources) merged in when `merge` is
100    /// set. Returns the text and whether `frame-ancestors` still needs its own enforced header.
101    ///
102    /// Before merging, a response carried two enforced headers and the browser applied both, so
103    /// the effective `frame-ancestors` was the intersection of the two. One header cannot hold two
104    /// `frame-ancestors` (the browser ignores the second), so the merge never loosens that:
105    /// - the site policy has none: the server's is appended;
106    /// - the server's is `'none'`: it replaces the site's (nothing is stricter);
107    /// - the site's is `'none'`, or lists the same sources as the server's: the site's stays;
108    /// - any other pair cannot be intersected as text without parsing hosts and wildcards, so the
109    ///   server's goes back into its own header and the browser intersects the two, as before.
110    fn template(&self, frame_ancestors: &str, merge: bool) -> (String, bool) {
111        let ours: &str = frame_ancestors.trim();
112        // A `;` or `,` in any name, value or report URI could smuggle in a directive or a second
113        // policy ahead of ours, and a control character hides a name from the match below until
114        // `clean` strips it, so such a policy is never merged.
115        let smuggles = |text: &str| text.contains([';', ',']) || text.chars().any(char::is_control);
116        let merge: bool = merge
117            && !smuggles(ours)
118            && !self
119                .directives
120                .iter()
121                .any(|(name, value): &(String, String)| smuggles(name) || smuggles(value))
122            && !self.report_uri.as_deref().is_some_and(smuggles);
123        let mut separate: bool = !merge;
124        let mut parts: Vec<String> = Vec::new();
125        let mut seen: bool = false;
126        for (name, value) in &self.directives {
127            if merge && name.trim().eq_ignore_ascii_case("frame-ancestors") {
128                if seen {
129                    // The browser ignores a repeated directive, so a repeat adds nothing.
130                    continue;
131                }
132                seen = true;
133                if ours == "'none'" {
134                    parts.push("frame-ancestors 'none'".to_owned());
135                } else if value.trim() == "'none'" || same_sources(value, ours) {
136                    parts.push(format!("{name} {value}"));
137                } else {
138                    separate = true;
139                    parts.push(format!("{name} {value}"));
140                }
141                continue;
142            }
143            parts.push(format!("{name} {value}"));
144        }
145        if merge && !seen {
146            parts.push(format!("frame-ancestors {ours}"));
147        }
148        if let Some(uri) = &self.report_uri {
149            parts.push(format!("report-uri {uri}"));
150        }
151        (parts.join("; "), separate)
152    }
153
154    const fn header_name(&self) -> HeaderName {
155        match self.mode {
156            CspMode::ReportOnly => header::CONTENT_SECURITY_POLICY_REPORT_ONLY,
157            CspMode::Enforce => header::CONTENT_SECURITY_POLICY,
158        }
159    }
160}
161
162/// The security headers a server sends. [`new`](Self::new) is the strict default every
163/// [`WebServer`](super::WebServer) uses unless the site replaces it.
164#[derive(Clone, Debug)]
165pub struct SecurityHeaders {
166    referrer_policy: String,
167    permissions_policy: String,
168    frame_ancestors: String,
169    csp: Option<ContentSecurityPolicy>,
170}
171
172impl Default for SecurityHeaders {
173    fn default() -> Self {
174        Self::new()
175    }
176}
177
178impl SecurityHeaders {
179    /// `nosniff`, `strict-origin-when-cross-origin`, camera, microphone, geolocation, payment and
180    /// USB denied, and no framing by anyone.
181    #[must_use]
182    pub fn new() -> Self {
183        Self {
184            referrer_policy: DEFAULT_REFERRER_POLICY.to_owned(),
185            permissions_policy: DEFAULT_PERMISSIONS_POLICY.to_owned(),
186            frame_ancestors: DEFAULT_FRAME_ANCESTORS.to_owned(),
187            csp: None,
188        }
189    }
190
191    /// Replaces the `Referrer-Policy` value.
192    #[must_use]
193    pub fn referrer_policy(mut self, value: &str) -> Self {
194        value.clone_into(&mut self.referrer_policy);
195        self
196    }
197
198    /// Replaces the `Permissions-Policy` value.
199    #[must_use]
200    pub fn permissions_policy(mut self, value: &str) -> Self {
201        value.clone_into(&mut self.permissions_policy);
202        self
203    }
204
205    /// Replaces the `frame-ancestors` sources (default `'none'`). `X-Frame-Options` follows for
206    /// `'none'` (`DENY`) and `'self'` (`SAMEORIGIN`), and is omitted otherwise.
207    #[must_use]
208    pub fn frame_ancestors(mut self, sources: &str) -> Self {
209        sources.clone_into(&mut self.frame_ancestors);
210        self
211    }
212
213    /// Adds a Content-Security-Policy to every HTML response.
214    #[must_use]
215    pub fn content_security_policy(mut self, policy: ContentSecurityPolicy) -> Self {
216        self.csp = Some(policy);
217        self
218    }
219
220    pub(super) fn build(self) -> Arc<Built> {
221        let frame_options: Option<HeaderValue> = match self.frame_ancestors.trim() {
222            "'none'" => Some(HeaderValue::from_static("DENY")),
223            "'self'" => Some(HeaderValue::from_static("SAMEORIGIN")),
224            _ => None,
225        };
226        let mut separate_frame: bool = true;
227        let csp: Option<(HeaderName, String, bool)> = self.csp.as_ref().map(|policy| {
228            let merge: bool = matches!(policy.mode, CspMode::Enforce);
229            let (template, separate): (String, bool) =
230                policy.template(&self.frame_ancestors, merge);
231            separate_frame = separate;
232            (policy.header_name(), clean(&template), policy.uses_nonce())
233        });
234        Arc::new(Built {
235            referrer_policy: value(&self.referrer_policy),
236            permissions_policy: value(&self.permissions_policy),
237            frame_policy: separate_frame
238                .then(|| value(&format!("frame-ancestors {}", self.frame_ancestors))),
239            frame_options,
240            csp,
241        })
242    }
243}
244
245/// Whether two `frame-ancestors` source lists name the same sources, in any order. Sources are
246/// compared exactly: CSP paths are case-sensitive.
247fn same_sources(a: &str, b: &str) -> bool {
248    let set =
249        |text: &str| -> BTreeSet<String> { text.split_whitespace().map(str::to_owned).collect() };
250    set(a) == set(b)
251}
252
253/// `text` without control characters, which no header value can carry.
254fn clean(text: &str) -> String {
255    text.chars().filter(|c: &char| !c.is_control()).collect()
256}
257
258fn value(text: &str) -> HeaderValue {
259    HeaderValue::from_str(&clean(text)).unwrap_or_else(|_| HeaderValue::from_static(""))
260}
261
262/// [`SecurityHeaders`] with every value turned into a header value once, at boot.
263pub(super) struct Built {
264    referrer_policy: HeaderValue,
265    permissions_policy: HeaderValue,
266    frame_policy: Option<HeaderValue>,
267    frame_options: Option<HeaderValue>,
268    csp: Option<(HeaderName, String, bool)>,
269}
270
271const X_FRAME_OPTIONS: HeaderName = HeaderName::from_static("x-frame-options");
272const PERMISSIONS_POLICY: HeaderName = HeaderName::from_static("permissions-policy");
273
274/// `router` with the security layer, when configured.
275pub(super) fn apply(router: axum::Router, security: Option<SecurityHeaders>) -> axum::Router {
276    let Some(security) = security else {
277        return router;
278    };
279    router.layer(axum::middleware::from_fn_with_state(
280        security.build(),
281        layer,
282    ))
283}
284
285async fn layer(State(built): State<Arc<Built>>, request: Request, next: Next) -> Response {
286    let uses_nonce: bool = built.csp.as_ref().is_some_and(|(_, _, uses)| *uses);
287    let (nonce, mut response): (Option<String>, Response) = if uses_nonce {
288        let nonce: String = Uuid::new_v4().simple().to_string();
289        let response: Response = NONCE
290            .scope(Arc::from(nonce.as_str()), next.run(request))
291            .await;
292        (Some(nonce), response)
293    } else {
294        (None, next.run(request).await)
295    };
296    let headers = response.headers_mut();
297    headers.insert(
298        header::X_CONTENT_TYPE_OPTIONS,
299        HeaderValue::from_static("nosniff"),
300    );
301    headers.insert(header::REFERRER_POLICY, built.referrer_policy.clone());
302    headers.insert(PERMISSIONS_POLICY, built.permissions_policy.clone());
303
304    let is_html: bool = headers
305        .get(header::CONTENT_TYPE)
306        .and_then(|value: &HeaderValue| value.to_str().ok())
307        .is_some_and(|value: &str| {
308            value
309                .trim_start()
310                .to_ascii_lowercase()
311                .starts_with("text/html")
312        });
313    if !is_html {
314        return response;
315    }
316    if let Some(frame_policy) = &built.frame_policy {
317        headers.append(header::CONTENT_SECURITY_POLICY, frame_policy.clone());
318    }
319    if let Some(options) = &built.frame_options {
320        headers.insert(X_FRAME_OPTIONS, options.clone());
321    }
322    let Some((name, template, _)) = &built.csp else {
323        return response;
324    };
325    let policy: String = nonce.as_deref().map_or_else(
326        || template.clone(),
327        |nonce: &str| template.replace(NONCE_PLACEHOLDER, nonce),
328    );
329    if let Ok(value) = HeaderValue::from_str(&policy) {
330        response.headers_mut().append(name.clone(), value);
331    }
332    response
333}
334
335#[cfg(test)]
336mod tests {
337    use axum::Router;
338    use axum::body::Body;
339    use axum::http::{Request, StatusCode};
340    use axum::middleware::from_fn_with_state;
341    use axum::response::Html;
342    use axum::routing::get;
343    use tower::ServiceExt;
344
345    use super::*;
346
347    fn app(headers: SecurityHeaders) -> Router {
348        Router::new()
349            .route(
350                "/",
351                get(|| async {
352                    Html(format!(
353                        "<script nonce=\"{}\">1</script><script>injected</script>",
354                        current_nonce()
355                    ))
356                }),
357            )
358            .route("/api", get(|| async { "{}" }))
359            .layer(from_fn_with_state(headers.build(), layer))
360    }
361
362    async fn get_path(app: &Router, path: &str) -> Response {
363        app.clone()
364            .oneshot(Request::get(path).body(Body::empty()).expect("a request"))
365            .await
366            .expect("infallible")
367    }
368
369    fn header_of<'a>(response: &'a Response, name: &str) -> Vec<&'a str> {
370        response
371            .headers()
372            .get_all(name)
373            .iter()
374            .map(|value: &HeaderValue| value.to_str().expect("ascii"))
375            .collect()
376    }
377
378    #[tokio::test]
379    async fn an_html_page_gets_every_header_and_a_nonce_matching_its_scripts() {
380        let policy: ContentSecurityPolicy = ContentSecurityPolicy::new(CspMode::ReportOnly)
381            .directive("script-src", "'self' 'nonce-{nonce}'")
382            .report_uri("/r");
383        let app: Router = app(SecurityHeaders::new().content_security_policy(policy));
384        let response: Response = get_path(&app, "/").await;
385        assert_eq!(StatusCode::OK, response.status());
386        assert_eq!(
387            vec!["nosniff"],
388            header_of(&response, "x-content-type-options")
389        );
390        assert_eq!(
391            vec!["strict-origin-when-cross-origin"],
392            header_of(&response, "referrer-policy")
393        );
394        assert_eq!(
395            vec![DEFAULT_PERMISSIONS_POLICY],
396            header_of(&response, "permissions-policy")
397        );
398        assert_eq!(vec!["DENY"], header_of(&response, "x-frame-options"));
399        assert_eq!(
400            vec!["frame-ancestors 'none'"],
401            header_of(&response, "content-security-policy")
402        );
403        // Report-only cannot carry an enforced directive: two headers, frame-ancestors enforced.
404        let report: Vec<&str> = header_of(&response, "content-security-policy-report-only");
405        let nonce: String = report[0]
406            .strip_prefix("script-src 'self' 'nonce-")
407            .and_then(|rest: &str| rest.strip_suffix("'; report-uri /r"))
408            .expect("the nonce is in the policy")
409            .to_owned();
410        assert_eq!(32, nonce.len());
411        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
412            .await
413            .expect("body");
414        // The layer never rewrites the body: a script a template injected stays without a nonce.
415        assert_eq!(
416            format!("<script nonce=\"{nonce}\">1</script><script>injected</script>"),
417            String::from_utf8_lossy(&body)
418        );
419    }
420
421    #[tokio::test]
422    async fn each_response_gets_its_own_nonce() {
423        let policy: ContentSecurityPolicy =
424            ContentSecurityPolicy::new(CspMode::Enforce).directive("script-src", "'nonce-{nonce}'");
425        let app: Router = app(SecurityHeaders::new().content_security_policy(policy));
426        let first: Response = get_path(&app, "/").await;
427        let second: Response = get_path(&app, "/").await;
428        let a: Vec<&str> = header_of(&first, "content-security-policy");
429        let b: Vec<&str> = header_of(&second, "content-security-policy");
430        assert_eq!(1, a.len());
431        assert!(a[0].ends_with("; frame-ancestors 'none'"));
432        assert_ne!(a[0], b[0]);
433    }
434
435    async fn enforced(site: &str, ours: &str) -> Vec<String> {
436        let policy: ContentSecurityPolicy = ContentSecurityPolicy::new(CspMode::Enforce)
437            .directive("default-src", "'self'")
438            .directive("frame-ancestors", site);
439        let app: Router = app(SecurityHeaders::new()
440            .frame_ancestors(ours)
441            .content_security_policy(policy));
442        let response: Response = get_path(&app, "/").await;
443        header_of(&response, "content-security-policy")
444            .into_iter()
445            .map(str::to_owned)
446            .collect()
447    }
448
449    #[tokio::test]
450    async fn an_enforced_policy_without_frame_ancestors_gets_ours_in_one_header() {
451        let policy: ContentSecurityPolicy =
452            ContentSecurityPolicy::new(CspMode::Enforce).directive("default-src", "'self'");
453        let app: Router = app(SecurityHeaders::new().content_security_policy(policy));
454        let response: Response = get_path(&app, "/").await;
455        assert_eq!(
456            vec!["default-src 'self'; frame-ancestors 'none'"],
457            header_of(&response, "content-security-policy")
458        );
459    }
460
461    #[tokio::test]
462    async fn a_sites_own_frame_ancestors_never_loosens_the_merge() {
463        // Ours is 'none' (default): ours wins, one header.
464        assert_eq!(
465            vec!["default-src 'self'; frame-ancestors 'none'"],
466            enforced("https://a.example", "'none'").await
467        );
468        // Site 'none' is stricter than ours: the site's stays, one header.
469        assert_eq!(
470            vec!["default-src 'self'; frame-ancestors 'none'"],
471            enforced("'none'", "'self'").await
472        );
473        // Same sources in another order: one header.
474        assert_eq!(
475            vec!["default-src 'self'; frame-ancestors 'self' https://a.example"],
476            enforced("'self' https://a.example", "https://a.example 'self'").await
477        );
478        // Anything else cannot be intersected as text: both stay enforced, as before the merge.
479        assert_eq!(
480            vec![
481                "frame-ancestors 'self'",
482                "default-src 'self'; frame-ancestors https://a.example"
483            ],
484            enforced("https://a.example", "'self'").await
485        );
486    }
487
488    #[tokio::test]
489    async fn source_paths_are_compared_case_sensitively() {
490        assert_eq!(
491            vec![
492                "frame-ancestors https://a.example/x",
493                "default-src 'self'; frame-ancestors https://a.example/X"
494            ],
495            enforced("https://a.example/X", "https://a.example/x").await
496        );
497    }
498
499    #[tokio::test]
500    async fn a_semicolon_or_comma_in_the_policy_is_never_merged() {
501        for smuggled in ["'self'; frame-ancestors *", "'self', frame-ancestors *"] {
502            let policy: ContentSecurityPolicy =
503                ContentSecurityPolicy::new(CspMode::Enforce).directive("default-src", smuggled);
504            let app: Router = app(SecurityHeaders::new().content_security_policy(policy));
505            let response: Response = get_path(&app, "/").await;
506            let headers: Vec<&str> = header_of(&response, "content-security-policy");
507            assert!(
508                headers.contains(&"frame-ancestors 'none'"),
509                "{smuggled}: {headers:?}"
510            );
511            assert_eq!(2, headers.len(), "{smuggled}: {headers:?}");
512        }
513    }
514
515    #[tokio::test]
516    async fn a_control_character_in_a_directive_name_is_never_merged() {
517        let policy: ContentSecurityPolicy =
518            ContentSecurityPolicy::new(CspMode::Enforce).directive("frame-ancestors\u{1}", "*");
519        let app: Router = app(SecurityHeaders::new().content_security_policy(policy));
520        let response: Response = get_path(&app, "/").await;
521        let headers: Vec<&str> = header_of(&response, "content-security-policy");
522        assert!(headers.contains(&"frame-ancestors 'none'"), "{headers:?}");
523        assert_eq!(2, headers.len(), "{headers:?}");
524    }
525
526    #[tokio::test]
527    async fn a_report_only_policy_keeps_frame_ancestors_enforced_in_its_own_header() {
528        let policy: ContentSecurityPolicy =
529            ContentSecurityPolicy::new(CspMode::ReportOnly).directive("default-src", "'self'");
530        let app: Router = app(SecurityHeaders::new().content_security_policy(policy));
531        let response: Response = get_path(&app, "/").await;
532        assert_eq!(
533            vec!["frame-ancestors 'none'"],
534            header_of(&response, "content-security-policy")
535        );
536        assert_eq!(
537            vec!["default-src 'self'"],
538            header_of(&response, "content-security-policy-report-only")
539        );
540    }
541
542    #[tokio::test]
543    async fn a_non_html_response_gets_only_the_always_on_headers() {
544        let policy: ContentSecurityPolicy =
545            ContentSecurityPolicy::new(CspMode::Enforce).directive("default-src", "'self'");
546        let app: Router = app(SecurityHeaders::new().content_security_policy(policy));
547        let response: Response = get_path(&app, "/api").await;
548        assert_eq!(
549            vec!["nosniff"],
550            header_of(&response, "x-content-type-options")
551        );
552        assert!(response.headers().get("content-security-policy").is_none());
553        assert!(response.headers().get("x-frame-options").is_none());
554    }
555
556    #[test]
557    fn control_characters_are_removed_from_a_header_value() {
558        let built = SecurityHeaders::new()
559            .referrer_policy("no-ref\nerrer")
560            .build();
561        assert_eq!("no-referrer", built.referrer_policy);
562    }
563
564    #[test]
565    fn the_default_permissions_policy_has_no_interest_cohort() {
566        assert!(!DEFAULT_PERMISSIONS_POLICY.contains("interest-cohort"));
567    }
568}