footing 0.6.5

Feature-gated foundations for Rust backend services
Documentation
//! Validated HTTP security-header policy.

use axum::http::{HeaderMap, HeaderName, HeaderValue};

pub(super) mod defaults {
    pub const CONTENT_TYPE_OPTIONS: Option<&str> = Some("nosniff");
    pub const CONTENT_SECURITY_POLICY: Option<&str> = None;
    pub const FRAME_OPTIONS: Option<&str> = Some("DENY");
    pub const REFERRER_POLICY: Option<&str> = Some("no-referrer");
    pub const CROSS_ORIGIN_OPENER_POLICY: Option<&str> = Some("same-origin");
    pub const CROSS_ORIGIN_RESOURCE_POLICY: Option<&str> = Some("same-origin");
    pub const PERMISSIONS_POLICY: Option<&str> = None;
    pub const HSTS_MAX_AGE_SECONDS: u64 = 31_536_000;
    pub const HSTS_INCLUDE_SUBDOMAINS: bool = true;
    pub const HSTS_PRELOAD: bool = false;
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Validated configuration for security headers.
pub struct SecurityHeadersConfig {
    content_type_options: Option<HeaderValue>,
    content_security_policy: Option<HeaderValue>,
    frame_options: Option<HeaderValue>,
    referrer_policy: Option<HeaderValue>,
    cross_origin_opener_policy: Option<HeaderValue>,
    cross_origin_resource_policy: Option<HeaderValue>,
    permissions_policy: Option<HeaderValue>,
    strict_transport_security: Option<HeaderValue>,
}

impl SecurityHeadersConfig {
    #[must_use]
    /// Creates security headers for JSON APIs.
    ///
    /// Emits `nosniff`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer`
    /// and same-origin opener/resource policies. CSP, Permissions-Policy and
    /// HSTS are left unset. The opener policy prevents cross-origin OAuth popup
    /// callbacks; use `with_cross_origin_opener_policy(None)` when cross-origin
    /// popup communication is required.
    pub fn api_defaults() -> Self {
        Self {
            content_type_options: defaults::CONTENT_TYPE_OPTIONS.map(HeaderValue::from_static),
            content_security_policy: defaults::CONTENT_SECURITY_POLICY
                .map(HeaderValue::from_static),
            frame_options: defaults::FRAME_OPTIONS.map(HeaderValue::from_static),
            referrer_policy: defaults::REFERRER_POLICY.map(HeaderValue::from_static),
            cross_origin_opener_policy: defaults::CROSS_ORIGIN_OPENER_POLICY
                .map(HeaderValue::from_static),
            cross_origin_resource_policy: defaults::CROSS_ORIGIN_RESOURCE_POLICY
                .map(HeaderValue::from_static),
            permissions_policy: defaults::PERMISSIONS_POLICY.map(HeaderValue::from_static),
            strict_transport_security: None,
        }
    }

    #[must_use]
    /// Adds one year of HSTS, including subdomains, to [`Self::api_defaults`].
    /// Use only when the application and all subdomains are served over HTTPS.
    /// HSTS preload is not requested.
    pub fn strict_api_defaults() -> Self {
        Self::api_defaults().with_strict_transport_security(
            defaults::HSTS_MAX_AGE_SECONDS,
            defaults::HSTS_INCLUDE_SUBDOMAINS,
            defaults::HSTS_PRELOAD,
        )
    }

    #[must_use]
    /// Removes HSTS from this policy, leaving other headers unchanged.
    ///
    /// This leaves an application's existing response header untouched and does
    /// not revoke a browser's stored policy. To request revocation over HTTPS,
    /// use [`Self::with_strict_transport_security`] with zero seconds.
    pub fn without_strict_transport_security(mut self) -> Self {
        self.strict_transport_security = None;
        self
    }

    /// Configures HSTS with an exact, nonnegative number of seconds.
    ///
    /// Send this header only over HTTPS. Zero emits `max-age=0`, requesting
    /// removal of the browser's stored HSTS policy for the current host, as
    /// specified by [RFC 6797](https://www.rfc-editor.org/rfc/rfc6797.html#section-6.1.1).
    /// Omitting the header does not send that revocation instruction.
    ///
    /// ```
    /// use footing::http::SecurityHeadersConfig;
    ///
    /// let headers = SecurityHeadersConfig::default()
    ///     .with_strict_transport_security(31_536_000, true, false);
    /// let revocation = headers.with_strict_transport_security(0, false, false);
    /// assert_eq!(revocation.strict_transport_security().unwrap(), "max-age=0");
    /// ```
    #[must_use]
    #[expect(
        clippy::expect_used,
        reason = "fixed ASCII directives and decimal u64 digits form a valid header value"
    )]
    pub fn with_strict_transport_security(
        mut self,
        max_age_seconds: u64,
        include_subdomains: bool,
        preload: bool,
    ) -> Self {
        let mut value = format!("max-age={max_age_seconds}");
        if include_subdomains {
            value.push_str("; includeSubDomains");
        }
        if preload {
            value.push_str("; preload");
        }

        self.strict_transport_security =
            Some(HeaderValue::try_from(value).expect("HSTS directives are header-safe ASCII"));
        self
    }

    #[must_use]
    /// Configures content type options and returns the updated value.
    pub fn with_content_type_options(mut self, value: Option<HeaderValue>) -> Self {
        self.content_type_options = value;
        self
    }

    #[must_use]
    /// Configures content security policy and returns the updated value.
    pub fn with_content_security_policy(mut self, value: Option<HeaderValue>) -> Self {
        self.content_security_policy = value;
        self
    }

    #[must_use]
    /// Configures frame options and returns the updated value.
    pub fn with_frame_options(mut self, value: Option<HeaderValue>) -> Self {
        self.frame_options = value;
        self
    }

    #[must_use]
    /// Configures referrer policy and returns the updated value.
    pub fn with_referrer_policy(mut self, value: Option<HeaderValue>) -> Self {
        self.referrer_policy = value;
        self
    }

    #[must_use]
    /// Configures cross origin opener policy and returns the updated value.
    pub fn with_cross_origin_opener_policy(mut self, value: Option<HeaderValue>) -> Self {
        self.cross_origin_opener_policy = value;
        self
    }

    #[must_use]
    /// Configures cross origin resource policy and returns the updated value.
    pub fn with_cross_origin_resource_policy(mut self, value: Option<HeaderValue>) -> Self {
        self.cross_origin_resource_policy = value;
        self
    }

    #[must_use]
    /// Configures permissions policy and returns the updated value.
    pub fn with_permissions_policy(mut self, value: Option<HeaderValue>) -> Self {
        self.permissions_policy = value;
        self
    }

    #[must_use]
    /// Returns the content type options.
    pub fn content_type_options(&self) -> Option<&HeaderValue> {
        self.content_type_options.as_ref()
    }

    #[must_use]
    /// Returns the content security policy.
    pub fn content_security_policy(&self) -> Option<&HeaderValue> {
        self.content_security_policy.as_ref()
    }

    #[must_use]
    /// Returns the frame options.
    pub fn frame_options(&self) -> Option<&HeaderValue> {
        self.frame_options.as_ref()
    }

    #[must_use]
    /// Returns the referrer policy.
    pub fn referrer_policy(&self) -> Option<&HeaderValue> {
        self.referrer_policy.as_ref()
    }

    #[must_use]
    /// Returns the cross origin opener policy.
    pub fn cross_origin_opener_policy(&self) -> Option<&HeaderValue> {
        self.cross_origin_opener_policy.as_ref()
    }

    #[must_use]
    /// Returns the cross origin resource policy.
    pub fn cross_origin_resource_policy(&self) -> Option<&HeaderValue> {
        self.cross_origin_resource_policy.as_ref()
    }

    #[must_use]
    /// Returns the permissions policy.
    pub fn permissions_policy(&self) -> Option<&HeaderValue> {
        self.permissions_policy.as_ref()
    }

    #[must_use]
    /// Returns the strict transport security.
    pub fn strict_transport_security(&self) -> Option<&HeaderValue> {
        self.strict_transport_security.as_ref()
    }

    /// Applies the configured security headers to a response header map.
    pub fn apply(&self, headers: &mut HeaderMap) {
        insert_header(
            headers,
            HeaderName::from_static("x-content-type-options"),
            &self.content_type_options,
        );
        insert_header(
            headers,
            HeaderName::from_static("content-security-policy"),
            &self.content_security_policy,
        );
        insert_header(
            headers,
            HeaderName::from_static("x-frame-options"),
            &self.frame_options,
        );
        insert_header(
            headers,
            HeaderName::from_static("referrer-policy"),
            &self.referrer_policy,
        );
        insert_header(
            headers,
            HeaderName::from_static("cross-origin-opener-policy"),
            &self.cross_origin_opener_policy,
        );
        insert_header(
            headers,
            HeaderName::from_static("cross-origin-resource-policy"),
            &self.cross_origin_resource_policy,
        );
        insert_header(
            headers,
            HeaderName::from_static("permissions-policy"),
            &self.permissions_policy,
        );
        insert_header(
            headers,
            HeaderName::from_static("strict-transport-security"),
            &self.strict_transport_security,
        );
    }
}

impl Default for SecurityHeadersConfig {
    fn default() -> Self {
        Self::api_defaults()
    }
}

fn insert_header(headers: &mut HeaderMap, name: HeaderName, value: &Option<HeaderValue>) {
    if let Some(value) = value {
        headers.insert(name, value.clone());
    }
}