footing 0.6.3

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

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

use crate::http::{
    CLIENT_ID_HEADER_NAME, IDEMPOTENCY_KEY_HEADER_NAME, IDEMPOTENCY_REPLAYED_HEADER_NAME,
    LOCALE_HEADER_NAME, REQUEST_ID_HEADER_NAME, SESSION_ID_HEADER_NAME, TIME_ZONE_HEADER_NAME,
    TRACEPARENT_HEADER_NAME, UTC_OFFSET_HEADER_NAME,
};
use crate::settings::{SettingsIssues, SettingsValidationError, field_path};

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.
///
/// Origin matching is independent of methods, headers and preflight caching.
/// [`Self::any_origin`] uses the same API defaults as [`Self::restricted`];
/// [`Self::permissive`] explicitly opens methods and headers as well.
/// Disabled mode ignores all other fields.
///
/// Omitted fields use their defaults. Explicit empty lists remain empty, and
/// nonempty lists replace the defaults. A wildcard (`"*"`) must be the only
/// entry in a method or header list and cannot be combined with credentials.
/// CORS controls browser access; it does not authenticate requests or restrict
/// which methods and headers the server's routes accept.
///
/// ```
/// use footing::http::{CorsPolicy, CorsSettings};
/// use std::time::Duration;
///
/// let mut cors = CorsSettings::any_origin();
/// cors.allowed_methods = vec!["GET".into()];
/// cors.allowed_headers = vec!["authorization".into()];
/// cors.exposed_headers = vec!["x-request-id".into()];
/// cors.max_age = Some(Duration::from_secs(60));
/// let policy = CorsPolicy::try_from(&cors)?;
/// # Ok::<(), footing::settings::SettingsValidationError>(())
/// ```
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.
    /// Must be empty in [`CorsMode::AnyOrigin`] to avoid silently ignoring a list.
    pub allowed_origins: Vec<String>,
    /// Whether cross-origin requests may include credentials.
    /// Any-origin 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.
    /// Defaults to GET, POST, PUT, PATCH and DELETE. `"*"` accepts any method.
    /// An empty list advertises no methods; browser-safelisted methods may still
    /// be usable without preflight.
    pub allowed_methods: Vec<String>,
    /// Request headers accepted in cross-origin requests.
    /// Defaults include authorization, idempotency and client context headers.
    /// `"*"` mirrors requested headers, including `Authorization`, which a
    /// literal wildcard response would not cover. An empty list advertises no
    /// additional headers; browser-safelisted headers remain usable.
    pub allowed_headers: Vec<String>,
    /// Response headers exposed to browser clients.
    /// Defaults expose request ID, idempotency replay status and retry delay.
    /// `"*"` exposes all headers readable under the browser's CORS rules.
    /// An empty list exposes no headers beyond the browser-safelisted ones.
    pub exposed_headers: Vec<String>,
    #[serde(with = "crate::settings::human_duration::option")]
    /// Optional browser preflight cache duration, in whole seconds.
    /// Defaults to ten minutes. Zero disables preflight caching. `None` omits
    /// the header, leaving the browser's default caching behavior in effect.
    /// Fractional seconds are rejected while CORS is enabled.
    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,
    /// Accepts any origin; other CORS rules still apply independently.
    AnyOrigin,
    /// Accepts only the explicitly listed origins.
    Restricted,
}

impl Default for CorsSettings {
    fn default() -> Self {
        Self {
            mode: CorsMode::Disabled,
            allowed_origins: Vec::new(),
            allow_credentials: false,
            allowed_methods: ["GET", "POST", "PUT", "PATCH", "DELETE"]
                .map(str::to_owned)
                .into(),
            allowed_headers: [
                "accept",
                "accept-language",
                "authorization",
                "content-type",
                "user-agent",
                REQUEST_ID_HEADER_NAME,
                TRACEPARENT_HEADER_NAME,
                IDEMPOTENCY_KEY_HEADER_NAME,
                LOCALE_HEADER_NAME,
                TIME_ZONE_HEADER_NAME,
                UTC_OFFSET_HEADER_NAME,
                CLIENT_ID_HEADER_NAME,
                SESSION_ID_HEADER_NAME,
            ]
            .map(str::to_owned)
            .into(),
            exposed_headers: [
                REQUEST_ID_HEADER_NAME,
                IDEMPOTENCY_REPLAYED_HEADER_NAME,
                "retry-after",
            ]
            .map(str::to_owned)
            .into(),
            max_age: Some(Duration::from_secs(10 * 60)),
        }
    }
}

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

    /// 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]
    /// Disables CORS header handling.
    pub fn disabled() -> Self {
        Self::default()
    }

    #[must_use]
    /// Accepts any origin, method and request header, and exposes response headers.
    /// Credentials are disabled and no preflight cache duration is advertised.
    /// Each field can subsequently be narrowed independently.
    pub fn permissive() -> Self {
        Self {
            allowed_methods: vec!["*".into()],
            allowed_headers: vec!["*".into()],
            exposed_headers: vec!["*".into()],
            max_age: None,
            ..Self::any_origin()
        }
    }

    #[must_use]
    /// Accepts any origin with the default API methods, headers and cache duration.
    /// Credentials cannot be enabled with this origin mode.
    pub fn any_origin() -> Self {
        Self {
            mode: CorsMode::AnyOrigin,
            ..Self::default()
        }
    }

    #[must_use]
    /// Accepts only these origins, with the default API methods, headers and caching.
    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> {
        if self.mode == CorsMode::Disabled {
            return Ok(CorsPolicy::Disabled);
        }

        let mut issues = SettingsIssues::new();
        if let Some(max_age) = self.max_age {
            issues.require(
                max_age.subsec_nanos() == 0,
                field_path(path, "max_age"),
                "must be a whole number of seconds",
            );
        }
        if self.mode == CorsMode::AnyOrigin {
            issues.require(
                !self.allow_credentials,
                field_path(path, "allow_credentials"),
                "must not be enabled with wildcard origins",
            );
            issues.require(
                self.allowed_origins.is_empty(),
                field_path(path, "allowed_origins"),
                "must be empty when CORS mode is any_origin",
            );
        } else {
            issues.require(
                !self.allowed_origins.is_empty(),
                field_path(path, "allowed_origins"),
                "must not be empty when CORS mode is restricted",
            );
        }
        for (field, values) in [
            ("allowed_methods", &self.allowed_methods),
            ("allowed_headers", &self.allowed_headers),
            ("exposed_headers", &self.exposed_headers),
        ] {
            if values.iter().any(|value| value.trim() == "*") {
                issues.require(
                    !self.allow_credentials,
                    field_path(path, field),
                    "must not contain '*' when credentials are enabled",
                );
                issues.require(
                    values.len() == 1,
                    field_path(path, field),
                    "'*' must be the only entry",
                );
            }
        }
        let config = CorsConfig {
            allowed_origins: parse_values(
                &mut issues,
                &field_path(path, "allowed_origins"),
                &self.allowed_origins,
                parse_origin,
                "must be a serialized origin (scheme://host[:port]) or 'null', without paths, credentials or wildcards",
            ),
            allowed_methods: parse_values(
                &mut issues,
                &field_path(path, "allowed_methods"),
                &self.allowed_methods,
                parse_method,
                "must be a valid HTTP method",
            ),
            allowed_headers: parse_values(
                &mut issues,
                &field_path(path, "allowed_headers"),
                &self.allowed_headers,
                |value| HeaderName::try_from(value),
                "must be a valid HTTP header name",
            ),
            exposed_headers: parse_values(
                &mut issues,
                &field_path(path, "exposed_headers"),
                &self.exposed_headers,
                |value| HeaderName::try_from(value),
                "must be a valid HTTP header name",
            ),
            allow_credentials: self.allow_credentials,
            max_age: self.max_age,
        };
        issues.into_result()?;
        Ok(if self.mode == CorsMode::AnyOrigin {
            CorsPolicy::AnyOrigin(config)
        } else {
            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(field_path(path, &index.to_string()), message);
                None
            }
        })
        .collect()
}