Skip to main content

webserver_base/webserver/
security.rs

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