footing 0.1.4

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

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

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

use super::super::{
    error::HttpLayerError,
    policy::{CorsConfig, CorsPolicy},
    route_settings::parse_methods,
};

#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
/// Serializable settings for CORS.
pub struct CorsSettings {
    #[serde(default)]
    /// Origin matching mode.
    pub mode: CorsMode,
    #[serde(default)]
    /// Origins accepted when using allow-list mode.
    pub allowed_origins: Vec<String>,
    #[serde(default)]
    /// Whether cross-origin requests may include credentials.
    pub allow_credentials: bool,
    #[serde(default)]
    /// HTTP methods accepted in cross-origin requests.
    pub allowed_methods: Vec<String>,
    #[serde(default)]
    /// Request headers accepted in cross-origin requests.
    pub allowed_headers: Vec<String>,
    #[serde(default)]
    /// Response headers exposed to browser clients.
    pub exposed_headers: Vec<String>,
    #[serde(
        default = "default_cors_max_age",
        with = "crate::settings::human_duration::option"
    )]
    /// Optional browser preflight cache duration.
    pub max_age: Option<Duration>,
}

#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
/// Enumerates the supported CORS mode values.
pub enum CorsMode {
    #[default]
    /// The capability is disabled.
    Disabled,
    /// Indicates permissive.
    Permissive,
    /// Indicates restricted.
    Restricted,
}

impl Default for CorsSettings {
    fn default() -> Self {
        Self {
            mode: CorsMode::Disabled,
            allowed_origins: Vec::new(),
            allow_credentials: false,
            allowed_methods: Vec::new(),
            allowed_headers: Vec::new(),
            exposed_headers: Vec::new(),
            max_age: default_cors_max_age(),
        }
    }
}

impl CorsSettings {
    #[must_use]
    /// Creates disabled.
    pub fn disabled() -> Self {
        Self::default()
    }

    #[must_use]
    /// Creates permissive.
    pub fn permissive() -> Self {
        Self {
            mode: CorsMode::Permissive,
            ..Self::default()
        }
    }

    #[must_use]
    /// Creates restricted.
    pub fn restricted(origins: impl IntoIterator<Item = impl Into<String>>) -> Self {
        Self {
            mode: CorsMode::Restricted,
            allowed_origins: origins.into_iter().map(Into::into).collect(),
            ..Self::default()
        }
    }

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

    pub(crate) fn validate_at(&self, path: &str) -> Result<(), SettingsValidationError> {
        let mut issues = SettingsIssues::new();
        if matches!(self.mode, CorsMode::Restricted) {
            issues.require(
                !self.allowed_origins.is_empty(),
                format!("{path}.allowed_origins"),
                "must not be empty when CORS mode is restricted",
            );
        }
        for (index, origin) in self.allowed_origins.iter().enumerate() {
            let origin = origin.trim();
            issues.require(
                !origin.is_empty(),
                format!("{path}.allowed_origins.{index}"),
                "must not be empty",
            );
            issues.require(
                HeaderValue::from_str(origin).is_ok(),
                format!("{path}.allowed_origins.{index}"),
                "must be a valid HTTP header value",
            );
        }
        issues.require(
            !(self.allow_credentials
                && self
                    .allowed_origins
                    .iter()
                    .any(|origin| origin.trim() == "*")),
            format!("{path}.allow_credentials"),
            "must not be enabled with wildcard origins",
        );
        validate_method_settings(
            &mut issues,
            format!("{path}.allowed_methods"),
            &self.allowed_methods,
        );
        validate_header_name_settings(
            &mut issues,
            format!("{path}.allowed_headers"),
            &self.allowed_headers,
        );
        validate_header_name_settings(
            &mut issues,
            format!("{path}.exposed_headers"),
            &self.exposed_headers,
        );
        issues.into_result()
    }
}

impl TryFrom<&CorsSettings> for CorsPolicy {
    type Error = HttpLayerError;

    fn try_from(value: &CorsSettings) -> Result<Self, Self::Error> {
        match value.mode {
            CorsMode::Disabled => Ok(Self::Disabled),
            CorsMode::Permissive => Ok(Self::Permissive),
            CorsMode::Restricted => {
                let mut config = CorsConfig::from_origin_strs(&value.allowed_origins)
                    .map_err(|source| HttpLayerError::InvalidHeaderValue {
                        field: "allowed_origins",
                        source,
                    })?
                    .allow_credentials(value.allow_credentials)
                    .max_age(value.max_age);
                if !value.allowed_methods.is_empty() {
                    config = config
                        .allow_methods(parse_methods("allowed_methods", &value.allowed_methods)?);
                }
                if !value.allowed_headers.is_empty() {
                    config = config.allow_headers(parse_header_names(
                        "allowed_headers",
                        &value.allowed_headers,
                    )?);
                }
                if !value.exposed_headers.is_empty() {
                    config = config.expose_headers(parse_header_names(
                        "exposed_headers",
                        &value.exposed_headers,
                    )?);
                }
                config.validate()?;
                Ok(Self::Restricted(config))
            }
        }
    }
}

fn default_cors_max_age() -> Option<Duration> {
    Some(Duration::from_secs(10 * 60))
}

fn validate_method_settings(issues: &mut SettingsIssues, path: impl AsRef<str>, values: &[String]) {
    let path = path.as_ref();
    for (index, value) in values.iter().enumerate() {
        issues.require(
            value.trim().parse::<Method>().is_ok(),
            format!("{path}.{index}"),
            "must be a valid HTTP method",
        );
    }
}

fn validate_header_name_settings(
    issues: &mut SettingsIssues,
    path: impl AsRef<str>,
    values: &[String],
) {
    let path = path.as_ref();
    for (index, value) in values.iter().enumerate() {
        issues.require(
            HeaderName::try_from(value.trim()).is_ok(),
            format!("{path}.{index}"),
            "must be a valid HTTP header name",
        );
    }
}

fn parse_header_names(
    field: &'static str,
    values: &[String],
) -> Result<Vec<HeaderName>, HttpLayerError> {
    values
        .iter()
        .map(|value| {
            HeaderName::try_from(value.trim())
                .map_err(|source| HttpLayerError::InvalidHeaderName { field, source })
        })
        .collect()
}