footing 0.6.1

Feature-gated foundations for Rust backend services
Documentation
use std::time::Duration;

use axum::http::HeaderValue;
use serde::{Deserialize, Serialize};

use crate::settings::{SettingsIssues, SettingsValidationError, field_path};

use super::super::policy::DEFAULT_HSTS_MAX_AGE;
use crate::http::SecurityHeadersConfig;

#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
/// Serializable settings for security headers.
///
/// Missing fields retain the API defaults. An explicit `None` (JSON `null`)
/// prevents this layer from writing that header; it does not remove a header
/// supplied by the application or another layer. Header values are validated
/// as HTTP header values, not against individual browser policy grammars.
pub struct SecurityHeadersSettings {
    /// Whether security response headers are emitted.
    pub enabled: bool,
    /// HTTP Strict Transport Security configuration.
    pub strict_transport_security: StrictTransportSecuritySettings,
    /// Value of `X-Content-Type-Options`, or `None` to omit it. Defaults to `nosniff`.
    pub content_type_options: Option<String>,
    /// Value of `X-Frame-Options`, or `None` to omit it. Defaults to `DENY`.
    pub frame_options: Option<String>,
    /// Value of `Referrer-Policy`, or `None` to omit it. Defaults to `no-referrer`.
    pub referrer_policy: Option<String>,
    /// Value of `Cross-Origin-Opener-Policy`, or `None` to omit it.
    pub cross_origin_opener_policy: Option<String>,
    /// Value of `Cross-Origin-Resource-Policy`, or `None` to omit it.
    /// Defaults to `same-origin`.
    pub cross_origin_resource_policy: Option<String>,
    /// Value of `Content-Security-Policy`, or `None` to omit it.
    pub content_security_policy: Option<String>,
    /// Value of `Permissions-Policy`, or `None` to omit it.
    pub permissions_policy: Option<String>,
}

#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
/// Serializable settings for strict transport security.
pub struct StrictTransportSecuritySettings {
    /// Whether the HSTS header is emitted.
    pub enabled: bool,
    #[serde(with = "crate::settings::human_duration")]
    /// Browser HSTS retention duration, in whole seconds.
    /// When enabled, zero sends `max-age=0` to revoke the current host's stored
    /// HSTS policy over HTTPS. Disabling the header does not request revocation.
    /// Fractional seconds are rejected when HSTS and security headers are enabled.
    pub max_age: Duration,
    /// Whether HSTS also applies to subdomains.
    pub include_subdomains: bool,
    /// Whether to request inclusion in browser preload lists.
    pub preload: bool,
}

impl Default for SecurityHeadersSettings {
    fn default() -> Self {
        Self {
            enabled: true,
            strict_transport_security: StrictTransportSecuritySettings::default(),
            content_type_options: Some("nosniff".to_owned()),
            frame_options: Some("DENY".to_owned()),
            referrer_policy: Some("no-referrer".to_owned()),
            cross_origin_opener_policy: Some("same-origin".to_owned()),
            cross_origin_resource_policy: Some("same-origin".to_owned()),
            content_security_policy: None,
            permissions_policy: None,
        }
    }
}

impl Default for StrictTransportSecuritySettings {
    fn default() -> Self {
        Self {
            enabled: false,
            max_age: DEFAULT_HSTS_MAX_AGE,
            include_subdomains: true,
            preload: false,
        }
    }
}

impl SecurityHeadersSettings {
    /// Validates settings beneath `http.security_headers`.
    pub fn validate(&self) -> Result<(), SettingsValidationError> {
        self.validate_at("http.security_headers")
    }

    /// Validates settings using their location in the application configuration.
    ///
    /// `path` prefixes every reported field. An empty path reports fields at the
    /// document root; the supplied path is otherwise used unchanged.
    pub fn validate_at(&self, path: &str) -> Result<(), SettingsValidationError> {
        self.build_at(path).map(|_| ())
    }

    #[must_use]
    /// Creates disabled.
    pub const fn disabled() -> Self {
        Self {
            enabled: false,
            strict_transport_security: StrictTransportSecuritySettings {
                enabled: false,
                max_age: DEFAULT_HSTS_MAX_AGE,
                include_subdomains: true,
                preload: false,
            },
            content_type_options: None,
            frame_options: None,
            referrer_policy: None,
            cross_origin_opener_policy: None,
            cross_origin_resource_policy: None,
            content_security_policy: None,
            permissions_policy: None,
        }
    }

    #[must_use]
    /// Configures enabled and returns the updated value.
    pub const fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    #[must_use]
    /// Configures strict transport security and returns the updated value.
    pub const fn with_strict_transport_security(
        mut self,
        strict_transport_security: StrictTransportSecuritySettings,
    ) -> Self {
        self.strict_transport_security = strict_transport_security;
        self
    }

    #[must_use]
    /// Sets `X-Content-Type-Options`; `None` leaves the response header untouched.
    pub fn with_content_type_options(mut self, value: Option<impl Into<String>>) -> Self {
        self.content_type_options = value.map(Into::into);
        self
    }

    #[must_use]
    /// Sets `X-Frame-Options`; `None` leaves the response header untouched.
    pub fn with_frame_options(mut self, value: Option<impl Into<String>>) -> Self {
        self.frame_options = value.map(Into::into);
        self
    }

    #[must_use]
    /// Sets `Referrer-Policy`; `None` leaves the response header untouched.
    pub fn with_referrer_policy(mut self, value: Option<impl Into<String>>) -> Self {
        self.referrer_policy = value.map(Into::into);
        self
    }

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

    #[must_use]
    /// Sets `Cross-Origin-Resource-Policy`; `None` leaves the response header untouched.
    pub fn with_cross_origin_resource_policy(mut self, value: Option<impl Into<String>>) -> Self {
        self.cross_origin_resource_policy = value.map(Into::into);
        self
    }

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

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

    pub(in crate::http::layers) fn build_at(
        &self,
        path: &str,
    ) -> Result<Option<SecurityHeadersConfig>, SettingsValidationError> {
        let mut issues = SettingsIssues::new();
        if self.enabled {
            issues.extend_result(
                self.strict_transport_security
                    .validate_at(&field_path(path, "strict_transport_security")),
            );
        }
        let content_type_options = optional_header_value(
            field_path(path, "content_type_options"),
            self.content_type_options.as_deref(),
        );
        let frame_options = optional_header_value(
            field_path(path, "frame_options"),
            self.frame_options.as_deref(),
        );
        let referrer_policy = optional_header_value(
            field_path(path, "referrer_policy"),
            self.referrer_policy.as_deref(),
        );
        let opener_policy = optional_header_value(
            field_path(path, "cross_origin_opener_policy"),
            self.cross_origin_opener_policy.as_deref(),
        );
        let resource_policy = optional_header_value(
            field_path(path, "cross_origin_resource_policy"),
            self.cross_origin_resource_policy.as_deref(),
        );
        let content_policy = optional_header_value(
            field_path(path, "content_security_policy"),
            self.content_security_policy.as_deref(),
        );
        let permissions_policy = optional_header_value(
            field_path(path, "permissions_policy"),
            self.permissions_policy.as_deref(),
        );
        for result in [
            &content_type_options,
            &frame_options,
            &referrer_policy,
            &opener_policy,
            &resource_policy,
            &content_policy,
            &permissions_policy,
        ] {
            if let Err(error) = result {
                issues.extend(error.clone());
            }
        }
        issues.into_result()?;
        if !self.enabled {
            return Ok(None);
        }
        let mut config = SecurityHeadersConfig::api_defaults()
            .with_content_type_options(content_type_options?)
            .with_frame_options(frame_options?)
            .with_referrer_policy(referrer_policy?)
            .with_cross_origin_opener_policy(opener_policy?)
            .with_cross_origin_resource_policy(resource_policy?)
            .with_content_security_policy(content_policy?)
            .with_permissions_policy(permissions_policy?);
        if self.strict_transport_security.enabled {
            config = config.with_strict_transport_security(
                self.strict_transport_security.max_age.as_secs(),
                self.strict_transport_security.include_subdomains,
                self.strict_transport_security.preload,
            );
        }
        Ok(Some(config))
    }
}

impl StrictTransportSecuritySettings {
    /// Validates settings beneath `http.security_headers.strict_transport_security`.
    pub fn validate(&self) -> Result<(), SettingsValidationError> {
        self.validate_at("http.security_headers.strict_transport_security")
    }

    /// Validates settings using their location in the application configuration.
    ///
    /// `path` prefixes every reported field. An empty path reports fields at the
    /// document root; the supplied path is otherwise used unchanged.
    pub fn validate_at(&self, path: &str) -> Result<(), SettingsValidationError> {
        let mut issues = SettingsIssues::new();
        issues.require(
            !self.enabled || self.max_age.subsec_nanos() == 0,
            field_path(path, "max_age"),
            "must be a whole number of seconds when strict transport security is enabled",
        );
        issues.into_result()
    }

    #[must_use]
    /// Creates a new instance.
    pub const fn new(
        enabled: bool,
        max_age: Duration,
        include_subdomains: bool,
        preload: bool,
    ) -> Self {
        Self {
            enabled,
            max_age,
            include_subdomains,
            preload,
        }
    }

    #[must_use]
    /// Stops this layer from writing HSTS, without revoking a stored policy.
    pub const fn disabled() -> Self {
        Self {
            enabled: false,
            max_age: DEFAULT_HSTS_MAX_AGE,
            include_subdomains: true,
            preload: false,
        }
    }

    #[must_use]
    /// Enables an HSTS header with the given whole-second duration.
    /// Zero requests revocation of the current host's stored policy over HTTPS.
    pub const fn enabled(max_age: Duration) -> Self {
        Self {
            enabled: true,
            max_age,
            include_subdomains: true,
            preload: false,
        }
    }

    #[must_use]
    /// Configures include subdomains and returns the updated value.
    pub const fn with_include_subdomains(mut self, include_subdomains: bool) -> Self {
        self.include_subdomains = include_subdomains;
        self
    }

    #[must_use]
    /// Configures preload and returns the updated value.
    pub const fn with_preload(mut self, preload: bool) -> Self {
        self.preload = preload;
        self
    }
}

fn optional_header_value(
    path: String,
    value: Option<&str>,
) -> Result<Option<HeaderValue>, SettingsValidationError> {
    value
        .map(str::trim)
        .map(HeaderValue::from_str)
        .transpose()
        .map_err(|_| SettingsValidationError::single(path, "must be a valid HTTP header value"))
}