footing 0.4.2

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

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

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

use super::super::{
    policy::{CorsConfig, CorsPolicy},
    route_settings::parse_method,
};

#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
/// Serializable settings for CORS.
///
/// Disabled mode ignores all other fields. Permissive mode only requires
/// `allow_credentials` to be false; allow-list fields apply to restricted mode.
/// Permissive mode mirrors requested headers, including `Authorization`.
pub struct CorsSettings {
    /// Origin matching mode.
    pub mode: CorsMode,
    /// Serialized origins accepted in restricted mode, such as `https://example.com`.
    /// Paths, trailing slashes, credentials and noncanonical URLs are rejected.
    /// The opaque origin `null` must be listed explicitly if it should be allowed.
    pub allowed_origins: Vec<String>,
    /// Whether cross-origin requests may include credentials.
    /// Permissive mode does not support credentials; restricted mode requires
    /// explicit origins, methods and header names when credentials are enabled.
    pub allow_credentials: bool,
    /// HTTP methods accepted in cross-origin requests.
    pub allowed_methods: Vec<String>,
    /// Request headers accepted in cross-origin requests.
    /// An empty list uses the API defaults, including idempotency and client
    /// context headers. A nonempty list replaces those defaults.
    pub allowed_headers: Vec<String>,
    /// Response headers exposed to browser clients.
    /// An empty list exposes request ID, idempotency replay status and retry
    /// delay. A nonempty list replaces those defaults.
    pub exposed_headers: Vec<String>,
    #[serde(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: Some(Duration::from_secs(10 * 60)),
        }
    }
}

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(in crate::http::layers) fn build_at(
        &self,
        path: &str,
    ) -> Result<CorsPolicy, SettingsValidationError> {
        match self.mode {
            CorsMode::Disabled => return Ok(CorsPolicy::Disabled),
            CorsMode::Permissive => {
                return if self.allow_credentials {
                    Err(SettingsValidationError::single(
                        format!("{path}.allow_credentials"),
                        "must not be enabled with wildcard origins",
                    ))
                } else {
                    Ok(CorsPolicy::Permissive)
                };
            }
            CorsMode::Restricted => {}
        }

        let mut issues = SettingsIssues::new();
        issues.require(
            !self.allowed_origins.is_empty(),
            format!("{path}.allowed_origins"),
            "must not be empty when CORS mode is restricted",
        );
        if self.allow_credentials {
            for (field, values) in [
                ("allowed_methods", &self.allowed_methods),
                ("allowed_headers", &self.allowed_headers),
                ("exposed_headers", &self.exposed_headers),
            ] {
                issues.require(
                    !values.iter().any(|value| value.trim() == "*"),
                    format!("{path}.{field}"),
                    "must not contain '*' when credentials are enabled",
                );
            }
        }
        let origins = parse_values(
            &mut issues,
            &format!("{path}.allowed_origins"),
            &self.allowed_origins,
            parse_origin,
            "must be a serialized origin (scheme://host[:port]) or 'null', without paths, credentials or wildcards",
        );
        let mut config = CorsConfig::new(origins);
        config.allow_credentials = self.allow_credentials;
        config.max_age = self.max_age;
        if !self.allowed_methods.is_empty() {
            config.allowed_methods = parse_values(
                &mut issues,
                &format!("{path}.allowed_methods"),
                &self.allowed_methods,
                parse_method,
                "must be a valid HTTP method",
            );
        }
        for (field, values, target) in [
            (
                "allowed_headers",
                &self.allowed_headers,
                &mut config.allowed_headers,
            ),
            (
                "exposed_headers",
                &self.exposed_headers,
                &mut config.exposed_headers,
            ),
        ] {
            if !values.is_empty() {
                *target = parse_values(
                    &mut issues,
                    &format!("{path}.{field}"),
                    values,
                    |value| HeaderName::try_from(value),
                    "must be a valid HTTP header name",
                );
            }
        }
        issues.into_result()?;
        Ok(CorsPolicy::Restricted(config))
    }
}

fn parse_origin(value: &str) -> Result<HeaderValue, ()> {
    if value.contains('*')
        || (value != "null"
            && !url::Url::parse(value).is_ok_and(|url| url.origin().ascii_serialization() == value))
    {
        return Err(());
    }
    HeaderValue::from_str(value).map_err(|_| ())
}

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

    fn try_from(value: &CorsSettings) -> Result<Self, Self::Error> {
        value.build_at("http.cors")
    }
}

fn parse_values<T, E>(
    issues: &mut SettingsIssues,
    path: &str,
    values: &[String],
    parse: impl Fn(&str) -> Result<T, E>,
    message: &str,
) -> Vec<T> {
    values
        .iter()
        .enumerate()
        .filter_map(|(index, value)| match parse(value.trim()) {
            Ok(value) => Some(value),
            Err(_) => {
                issues.push(format!("{path}.{index}"), message);
                None
            }
        })
        .collect()
}