footing 0.1.3

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};

use super::super::{
    error::HttpLayerError, policy::DEFAULT_HSTS_MAX_AGE, security::SecurityHeadersConfig,
};
use super::default_true;

#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
/// Serializable settings for security headers.
pub struct SecurityHeadersSettings {
    #[serde(default = "default_true")]
    /// Whether security response headers are emitted.
    pub enabled: bool,
    #[serde(default)]
    /// HTTP Strict Transport Security configuration.
    pub strict_transport_security: StrictTransportSecuritySettings,
    #[serde(default = "default_same_origin_header")]
    /// Value of `Cross-Origin-Opener-Policy`, or `None` to omit it.
    pub cross_origin_opener_policy: Option<String>,
    #[serde(default)]
    /// Value of `Content-Security-Policy`, or `None` to omit it.
    pub content_security_policy: Option<String>,
    #[serde(default)]
    /// 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(deny_unknown_fields)]
#[non_exhaustive]
/// Serializable settings for strict transport security.
pub struct StrictTransportSecuritySettings {
    #[serde(default)]
    /// Whether the HSTS header is emitted.
    pub enabled: bool,
    #[serde(
        default = "default_hsts_max_age_setting",
        with = "crate::settings::human_duration"
    )]
    /// Browser HSTS retention duration.
    pub max_age: Duration,
    #[serde(default = "default_true")]
    /// Whether HSTS also applies to subdomains.
    pub include_subdomains: bool,
    #[serde(default)]
    /// 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(),
            cross_origin_opener_policy: default_same_origin_header(),
            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 {
    #[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,
            },
            cross_origin_opener_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]
    /// 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]
    /// 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 try_config(
        value: &Self,
    ) -> Result<Option<SecurityHeadersConfig>, HttpLayerError> {
        if !value.enabled {
            return Ok(None);
        }
        let mut config = SecurityHeadersConfig::api_defaults();
        config = config.with_cross_origin_opener_policy(optional_header_value(
            "cross_origin_opener_policy",
            value.cross_origin_opener_policy.as_deref(),
        )?);
        config = config.with_content_security_policy(optional_header_value(
            "content_security_policy",
            value.content_security_policy.as_deref(),
        )?);
        config = config.with_permissions_policy(optional_header_value(
            "permissions_policy",
            value.permissions_policy.as_deref(),
        )?);
        if value.strict_transport_security.enabled {
            config = config
                .with_strict_transport_security(
                    value.strict_transport_security.max_age,
                    value.strict_transport_security.include_subdomains,
                    value.strict_transport_security.preload,
                )
                .map_err(|source| HttpLayerError::InvalidHeaderValue {
                    field: "strict_transport_security",
                    source,
                })?;
        }
        Ok(Some(config))
    }

    pub(crate) fn validate_at(&self, path: &str) -> Result<(), SettingsValidationError> {
        let mut issues = SettingsIssues::new();
        if self.enabled && self.strict_transport_security.enabled {
            issues.require(
                !self.strict_transport_security.max_age.is_zero(),
                format!("{path}.strict_transport_security.max_age"),
                "must be greater than zero when strict transport security is enabled",
            );
        }
        if let Some(value) = self.cross_origin_opener_policy.as_deref() {
            issues.require(
                HeaderValue::from_str(value.trim()).is_ok(),
                format!("{path}.cross_origin_opener_policy"),
                "must be a valid HTTP header value",
            );
        }
        for (field, value) in [
            (
                "content_security_policy",
                self.content_security_policy.as_deref(),
            ),
            ("permissions_policy", self.permissions_policy.as_deref()),
        ] {
            if let Some(value) = value {
                issues.require(
                    HeaderValue::from_str(value.trim()).is_ok(),
                    format!("{path}.{field}"),
                    "must be a valid HTTP header value",
                );
            }
        }
        issues.into_result()
    }
}

impl StrictTransportSecuritySettings {
    #[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]
    /// Creates disabled.
    pub const fn disabled() -> Self {
        Self {
            enabled: false,
            max_age: DEFAULT_HSTS_MAX_AGE,
            include_subdomains: true,
            preload: false,
        }
    }

    #[must_use]
    /// Creates enabled.
    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 default_same_origin_header() -> Option<String> {
    Some("same-origin".to_owned())
}

fn default_hsts_max_age_setting() -> Duration {
    DEFAULT_HSTS_MAX_AGE
}

fn optional_header_value(
    field: &'static str,
    value: Option<&str>,
) -> Result<Option<HeaderValue>, HttpLayerError> {
    value
        .map(str::trim)
        .map(HeaderValue::from_str)
        .transpose()
        .map_err(|source| HttpLayerError::InvalidHeaderValue { field, source })
}