webserver-base 0.4.6

A Rust library which contains shared logic for all of my webserver projects.
Documentation
//! Browser security headers, opt-in through [`WebServer::security_headers`](super::WebServer::security_headers).
//!
//! Every response gets `X-Content-Type-Options`, `Referrer-Policy` and `Permissions-Policy`.
//! An HTML response also gets `frame-ancestors` (enforced, in its own policy header, because a
//! report-only policy ignores that directive), `X-Frame-Options`, and the optional
//! [`ContentSecurityPolicy`]. The layer only sets headers; it never rewrites a body. A policy that
//! uses `{nonce}` gets a fresh nonce per request, which the layer hands to rendering as
//! `{{nonce}}` (see [`current_nonce`]); a template writes `nonce="{{nonce}}"` on each script it
//! trusts, so a script injected without it is blocked.

use std::sync::Arc;

use axum::extract::{Request, State};
use axum::http::header::{self, HeaderName, HeaderValue};
use axum::middleware::Next;
use axum::response::Response;
use uuid::Uuid;

tokio::task_local! {
    /// The nonce of the request being served, set by the layer for the handler's whole run.
    static NONCE: Arc<str>;
}

/// The current request's CSP nonce, for a template's `{{nonce}}`; empty when the request has none
/// (no policy uses `{nonce}`, or the call is off the request's task, such as a spawned one).
#[must_use]
pub fn current_nonce() -> String {
    NONCE
        .try_with(|nonce: &Arc<str>| nonce.to_string())
        .unwrap_or_default()
}

/// The placeholder in a [`ContentSecurityPolicy`] directive that becomes the response's nonce.
pub const NONCE_PLACEHOLDER: &str = "{nonce}";

const DEFAULT_REFERRER_POLICY: &str = "strict-origin-when-cross-origin";
const DEFAULT_PERMISSIONS_POLICY: &str =
    "camera=(), microphone=(), geolocation=(), payment=(), usb=()";
const DEFAULT_FRAME_ANCESTORS: &str = "'none'";

/// Whether a violation blocks the load or is only reported.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CspMode {
    /// `Content-Security-Policy-Report-Only`: nothing is blocked; the browser reports.
    ReportOnly,
    /// `Content-Security-Policy`: violations are blocked and reported.
    Enforce,
}

/// A Content-Security-Policy, built from directives.
///
/// A directive value containing [`NONCE_PLACEHOLDER`] gets this response's nonce. Templates read
/// the same value as `{{nonce}}` and write it on their own scripts; the layer does not touch the
/// body. Do not list `frame-ancestors` here:
/// use [`SecurityHeaders::frame_ancestors`].
#[derive(Clone, Debug)]
pub struct ContentSecurityPolicy {
    mode: CspMode,
    directives: Vec<(String, String)>,
    report_uri: Option<String>,
}

impl ContentSecurityPolicy {
    /// An empty policy in `mode`; add directives with [`directive`](Self::directive).
    #[must_use]
    pub const fn new(mode: CspMode) -> Self {
        Self {
            mode,
            directives: Vec::new(),
            report_uri: None,
        }
    }

    /// Adds `name value`, such as `("script-src", "'self' 'nonce-{nonce}'")`.
    #[must_use]
    pub fn directive(mut self, name: &str, value: &str) -> Self {
        self.directives.push((name.to_owned(), value.to_owned()));
        self
    }

    /// Where the browser posts violation reports (`report-uri`).
    #[must_use]
    pub fn report_uri(mut self, uri: &str) -> Self {
        self.report_uri = Some(uri.to_owned());
        self
    }

    fn uses_nonce(&self) -> bool {
        self.directives
            .iter()
            .any(|(_, value): &(String, String)| value.contains(NONCE_PLACEHOLDER))
    }

    fn template(&self) -> String {
        let mut parts: Vec<String> = self
            .directives
            .iter()
            .map(|(name, value): &(String, String)| format!("{name} {value}"))
            .collect();
        if let Some(uri) = &self.report_uri {
            parts.push(format!("report-uri {uri}"));
        }
        parts.join("; ")
    }

    const fn header_name(&self) -> HeaderName {
        match self.mode {
            CspMode::ReportOnly => header::CONTENT_SECURITY_POLICY_REPORT_ONLY,
            CspMode::Enforce => header::CONTENT_SECURITY_POLICY,
        }
    }
}

/// The security headers a server sends. [`new`](Self::new) is the strict default.
#[derive(Clone, Debug)]
pub struct SecurityHeaders {
    referrer_policy: String,
    permissions_policy: String,
    frame_ancestors: String,
    csp: Option<ContentSecurityPolicy>,
}

impl Default for SecurityHeaders {
    fn default() -> Self {
        Self::new()
    }
}

impl SecurityHeaders {
    /// `nosniff`, `strict-origin-when-cross-origin`, camera, microphone, geolocation, payment and
    /// USB denied, and no framing by anyone.
    #[must_use]
    pub fn new() -> Self {
        Self {
            referrer_policy: DEFAULT_REFERRER_POLICY.to_owned(),
            permissions_policy: DEFAULT_PERMISSIONS_POLICY.to_owned(),
            frame_ancestors: DEFAULT_FRAME_ANCESTORS.to_owned(),
            csp: None,
        }
    }

    /// Replaces the `Referrer-Policy` value.
    #[must_use]
    pub fn referrer_policy(mut self, value: &str) -> Self {
        value.clone_into(&mut self.referrer_policy);
        self
    }

    /// Replaces the `Permissions-Policy` value.
    #[must_use]
    pub fn permissions_policy(mut self, value: &str) -> Self {
        value.clone_into(&mut self.permissions_policy);
        self
    }

    /// Replaces the `frame-ancestors` sources (default `'none'`). `X-Frame-Options` follows for
    /// `'none'` (`DENY`) and `'self'` (`SAMEORIGIN`), and is omitted otherwise.
    #[must_use]
    pub fn frame_ancestors(mut self, sources: &str) -> Self {
        sources.clone_into(&mut self.frame_ancestors);
        self
    }

    /// Adds a Content-Security-Policy to every HTML response.
    #[must_use]
    pub fn content_security_policy(mut self, policy: ContentSecurityPolicy) -> Self {
        self.csp = Some(policy);
        self
    }

    pub(super) fn build(self) -> Arc<Built> {
        let frame_options: Option<HeaderValue> = match self.frame_ancestors.trim() {
            "'none'" => Some(HeaderValue::from_static("DENY")),
            "'self'" => Some(HeaderValue::from_static("SAMEORIGIN")),
            _ => None,
        };
        let csp: Option<(HeaderName, String, bool)> = self.csp.as_ref().map(|policy| {
            (
                policy.header_name(),
                clean(&policy.template()),
                policy.uses_nonce(),
            )
        });
        Arc::new(Built {
            referrer_policy: value(&self.referrer_policy),
            permissions_policy: value(&self.permissions_policy),
            frame_policy: value(&format!("frame-ancestors {}", self.frame_ancestors)),
            frame_options,
            csp,
        })
    }
}

/// `text` without control characters, which no header value can carry.
fn clean(text: &str) -> String {
    text.chars().filter(|c: &char| !c.is_control()).collect()
}

fn value(text: &str) -> HeaderValue {
    HeaderValue::from_str(&clean(text)).unwrap_or_else(|_| HeaderValue::from_static(""))
}

/// [`SecurityHeaders`] with every value turned into a header value once, at boot.
pub(super) struct Built {
    referrer_policy: HeaderValue,
    permissions_policy: HeaderValue,
    frame_policy: HeaderValue,
    frame_options: Option<HeaderValue>,
    csp: Option<(HeaderName, String, bool)>,
}

const X_FRAME_OPTIONS: HeaderName = HeaderName::from_static("x-frame-options");
const PERMISSIONS_POLICY: HeaderName = HeaderName::from_static("permissions-policy");

/// `router` with the security layer, when configured.
pub(super) fn apply(router: axum::Router, security: Option<SecurityHeaders>) -> axum::Router {
    let Some(security) = security else {
        return router;
    };
    router.layer(axum::middleware::from_fn_with_state(
        security.build(),
        layer,
    ))
}

async fn layer(State(built): State<Arc<Built>>, request: Request, next: Next) -> Response {
    let uses_nonce: bool = built.csp.as_ref().is_some_and(|(_, _, uses)| *uses);
    let (nonce, mut response): (Option<String>, Response) = if uses_nonce {
        let nonce: String = Uuid::new_v4().simple().to_string();
        let response: Response = NONCE
            .scope(Arc::from(nonce.as_str()), next.run(request))
            .await;
        (Some(nonce), response)
    } else {
        (None, next.run(request).await)
    };
    let headers = response.headers_mut();
    headers.insert(
        header::X_CONTENT_TYPE_OPTIONS,
        HeaderValue::from_static("nosniff"),
    );
    headers.insert(header::REFERRER_POLICY, built.referrer_policy.clone());
    headers.insert(PERMISSIONS_POLICY, built.permissions_policy.clone());

    let is_html: bool = headers
        .get(header::CONTENT_TYPE)
        .and_then(|value: &HeaderValue| value.to_str().ok())
        .is_some_and(|value: &str| {
            value
                .trim_start()
                .to_ascii_lowercase()
                .starts_with("text/html")
        });
    if !is_html {
        return response;
    }
    headers.append(header::CONTENT_SECURITY_POLICY, built.frame_policy.clone());
    if let Some(options) = &built.frame_options {
        headers.insert(X_FRAME_OPTIONS, options.clone());
    }
    let Some((name, template, _)) = &built.csp else {
        return response;
    };
    let policy: String = nonce.as_deref().map_or_else(
        || template.clone(),
        |nonce: &str| template.replace(NONCE_PLACEHOLDER, nonce),
    );
    if let Ok(value) = HeaderValue::from_str(&policy) {
        response.headers_mut().append(name.clone(), value);
    }
    response
}

#[cfg(test)]
mod tests {
    use axum::Router;
    use axum::body::Body;
    use axum::http::{Request, StatusCode};
    use axum::middleware::from_fn_with_state;
    use axum::response::Html;
    use axum::routing::get;
    use tower::ServiceExt;

    use super::*;

    fn app(headers: SecurityHeaders) -> Router {
        Router::new()
            .route(
                "/",
                get(|| async {
                    Html(format!(
                        "<script nonce=\"{}\">1</script><script>injected</script>",
                        current_nonce()
                    ))
                }),
            )
            .route("/api", get(|| async { "{}" }))
            .layer(from_fn_with_state(headers.build(), layer))
    }

    async fn get_path(app: &Router, path: &str) -> Response {
        app.clone()
            .oneshot(Request::get(path).body(Body::empty()).expect("a request"))
            .await
            .expect("infallible")
    }

    fn header_of<'a>(response: &'a Response, name: &str) -> Vec<&'a str> {
        response
            .headers()
            .get_all(name)
            .iter()
            .map(|value: &HeaderValue| value.to_str().expect("ascii"))
            .collect()
    }

    #[tokio::test]
    async fn an_html_page_gets_every_header_and_a_nonce_matching_its_scripts() {
        let policy: ContentSecurityPolicy = ContentSecurityPolicy::new(CspMode::ReportOnly)
            .directive("script-src", "'self' 'nonce-{nonce}'")
            .report_uri("/r");
        let app: Router = app(SecurityHeaders::new().content_security_policy(policy));
        let response: Response = get_path(&app, "/").await;
        assert_eq!(StatusCode::OK, response.status());
        assert_eq!(
            vec!["nosniff"],
            header_of(&response, "x-content-type-options")
        );
        assert_eq!(
            vec!["strict-origin-when-cross-origin"],
            header_of(&response, "referrer-policy")
        );
        assert_eq!(
            vec![DEFAULT_PERMISSIONS_POLICY],
            header_of(&response, "permissions-policy")
        );
        assert_eq!(vec!["DENY"], header_of(&response, "x-frame-options"));
        assert_eq!(
            vec!["frame-ancestors 'none'"],
            header_of(&response, "content-security-policy")
        );
        let report: Vec<&str> = header_of(&response, "content-security-policy-report-only");
        let nonce: String = report[0]
            .strip_prefix("script-src 'self' 'nonce-")
            .and_then(|rest: &str| rest.strip_suffix("'; report-uri /r"))
            .expect("the nonce is in the policy")
            .to_owned();
        assert_eq!(32, nonce.len());
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("body");
        // The layer never rewrites the body: a script a template injected stays without a nonce.
        assert_eq!(
            format!("<script nonce=\"{nonce}\">1</script><script>injected</script>"),
            String::from_utf8_lossy(&body)
        );
    }

    #[tokio::test]
    async fn each_response_gets_its_own_nonce() {
        let policy: ContentSecurityPolicy =
            ContentSecurityPolicy::new(CspMode::Enforce).directive("script-src", "'nonce-{nonce}'");
        let app: Router = app(SecurityHeaders::new().content_security_policy(policy));
        let first: Response = get_path(&app, "/").await;
        let second: Response = get_path(&app, "/").await;
        let a: Vec<&str> = header_of(&first, "content-security-policy");
        let b: Vec<&str> = header_of(&second, "content-security-policy");
        assert_eq!("frame-ancestors 'none'", a[0]);
        assert_ne!(a[1], b[1]);
    }

    #[tokio::test]
    async fn a_non_html_response_gets_only_the_always_on_headers() {
        let policy: ContentSecurityPolicy =
            ContentSecurityPolicy::new(CspMode::Enforce).directive("default-src", "'self'");
        let app: Router = app(SecurityHeaders::new().content_security_policy(policy));
        let response: Response = get_path(&app, "/api").await;
        assert_eq!(
            vec!["nosniff"],
            header_of(&response, "x-content-type-options")
        );
        assert!(response.headers().get("content-security-policy").is_none());
        assert!(response.headers().get("x-frame-options").is_none());
    }

    #[test]
    fn control_characters_are_removed_from_a_header_value() {
        let built = SecurityHeaders::new()
            .referrer_policy("no-ref\nerrer")
            .build();
        assert_eq!("no-referrer", built.referrer_policy);
    }

    #[test]
    fn the_default_permissions_policy_has_no_interest_cohort() {
        assert!(!DEFAULT_PERMISSIONS_POLICY.contains("interest-cohort"));
    }
}