footing 0.6.4

Feature-gated foundations for Rust backend services
Documentation
//! Origin verification for explicitly protected browser routes.
//!
//! [`RequestOriginPolicy`] checks requests against a fixed list of permitted
//! HTTP(S) origins. Apply it to login, logout, and other browser endpoints that
//! change state, including requests made before a session cookie exists.
//! `GET`, `HEAD`, and `OPTIONS` bypass the check and must not change state.
//! All other methods, including custom methods, require an accepted source.
//!
//! A single `Origin` takes precedence. Missing `Origin` permits checking a
//! single `Referer` instead; an invalid, opaque (`null`), repeated, or untrusted
//! `Origin` never falls back to `Referer`. If neither header proves an allowed
//! source, the check fails. A valid `Origin` makes `Referer` irrelevant.
//!
//! Names, subdomains, schemes, and nondefault ports must match exactly after URL
//! normalization. There are no wildcard or suffix matches. Allowed origins are
//! explicit deployment configuration, never inferred from `Host`, `Forwarded`,
//! or other request headers. The policy performs no I/O and logs no header data.
//!
//! ```no_run
//! use axum::{
//!     Router,
//!     extract::{Request, State},
//!     http::StatusCode,
//!     middleware::{self, Next},
//!     response::Response,
//!     routing::post,
//! };
//! use footing::http::{ApiProblem, ProblemCode, RequestContext, RequestOriginPolicy};
//!
//! async fn check_origin(
//!     State(policy): State<RequestOriginPolicy>,
//!     context: RequestContext,
//!     request: Request,
//!     next: Next,
//! ) -> Result<Response, ApiProblem> {
//!     policy.check(request.method(), request.headers()).map_err(|_| {
//!         ApiProblem::forbidden(
//!             ProblemCode::from_static("request_origin_rejected"),
//!             "request origin is not permitted",
//!         ).with_request_context(&context)
//!     })?;
//!     Ok(next.run(request).await)
//! }
//!
//! let policy = RequestOriginPolicy::new(["https://app.example.com"])?;
//! let app: Router = Router::new()
//!     .route("/session", post(|| async { StatusCode::NO_CONTENT }))
//!     .route_layer(middleware::from_fn_with_state(policy, check_origin));
//! # Ok::<(), footing::http::OriginPolicyError>(())
//! ```
//!
//! Applications select the protected routes and map [`OriginRejection`] to
//! their public errors. Browser callbacks from third parties and non-browser
//! clients need an explicitly chosen authentication/CSRF policy of their own.
//! This check constrains browser request origins; it does not authenticate a
//! caller, and cannot stop malicious scripts already running on an allowed
//! origin. CORS and cookie attributes remain separate policies.

use axum::http::{HeaderMap, HeaderName, Method, header};
use thiserror::Error;
use url::{Origin, Url};

use crate::result::{ClassifyError, ErrorCode, ErrorKind};

/// A validated allowlist for browser requests that can change application state.
///
/// Construction installs no routes, background tasks, or logging. See the module
/// example for Axum use.
#[derive(Clone, Debug)]
pub struct RequestOriginPolicy {
    allowed: Vec<Origin>,
}

impl RequestOriginPolicy {
    /// Validates a nonempty list of HTTP(S) origins such as `https://example.com`.
    ///
    /// Each entry must be ASCII `scheme://host[:port]`, without a trailing slash,
    /// path, credentials, query, fragment, wildcard, whitespace, or backslash.
    /// Use punycode for internationalized names. Host case, IPv6 spelling and
    /// default ports are normalized by the URL parser; duplicate origins collapse
    /// to one entry. HTTP must be explicitly listed when used for development.
    pub fn new(
        origins: impl IntoIterator<Item = impl AsRef<str>>,
    ) -> Result<Self, OriginPolicyError> {
        let mut allowed = Vec::new();
        for (index, value) in origins.into_iter().enumerate() {
            let origin = parse_web_origin(value.as_ref(), false)
                .ok_or(OriginPolicyError::InvalidOrigin { index })?;
            if !allowed.contains(&origin) {
                allowed.push(origin);
            }
        }
        if allowed.is_empty() {
            return Err(OriginPolicyError::EmptyOrigins);
        }
        Ok(Self { allowed })
    }

    /// Checks a request without changing its method or headers.
    ///
    /// `GET`, `HEAD`, and `OPTIONS` succeed without inspecting source headers.
    /// Other methods require exactly one allowed `Origin`, or, only when it is
    /// absent, one absolute HTTP(S) `Referer` from an allowed origin. A referer
    /// may include a path and query, but not credentials or a fragment.
    /// Repeated header fields are rejected even when their values are equal.
    ///
    /// Errors retain neither header values nor parser diagnostics. In particular,
    /// referer paths and queries never enter errors or policy debug output.
    pub fn check(&self, method: &Method, headers: &HeaderMap) -> Result<(), OriginRejection> {
        if matches!(*method, Method::GET | Method::HEAD | Method::OPTIONS) {
            return Ok(());
        }

        let origin = if let Some(value) =
            single_header(headers, header::ORIGIN).map_err(|()| OriginRejection::RepeatedOrigin)?
        {
            let value = value
                .to_str()
                .map_err(|_| OriginRejection::MalformedOrigin)?;
            if value == "null" {
                return Err(OriginRejection::OpaqueOrigin);
            }
            parse_web_origin(value, false).ok_or(OriginRejection::MalformedOrigin)?
        } else {
            let value = single_header(headers, header::REFERER)
                .map_err(|()| OriginRejection::RepeatedReferer)?
                .ok_or(OriginRejection::Missing)?
                .to_str()
                .map_err(|_| OriginRejection::MalformedReferer)?;
            parse_web_origin(value, true).ok_or(OriginRejection::MalformedReferer)?
        };

        if self.allowed.contains(&origin) {
            Ok(())
        } else {
            Err(OriginRejection::NotAllowed)
        }
    }
}

/// Invalid origin-policy configuration, without the rejected configuration text.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum OriginPolicyError {
    /// At least one allowed origin must be supplied.
    #[error("at least one allowed origin is required")]
    EmptyOrigins,
    /// An entry is not an HTTP(S) origin in the supported form.
    #[error(
        "allowed origin at index {index} must be an HTTP(S) origin without credentials, path, query, or fragment"
    )]
    InvalidOrigin {
        /// Zero-based position of the invalid entry.
        index: usize,
    },
}

impl ClassifyError for OriginPolicyError {
    fn error_kind(&self) -> ErrorKind {
        ErrorKind::Validation
    }

    fn error_code(&self) -> ErrorCode {
        ErrorCode::internal(match self {
            Self::EmptyOrigins => "origin_policy_empty_origins",
            Self::InvalidOrigin { .. } => "origin_policy_invalid_origin",
        })
    }
}

/// A protected request did not establish an explicitly allowed browser origin.
///
/// Variants carry no input or source-parser errors. Applications decide how to
/// report rejection, typically as a fixed `403` Problem Details response.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum OriginRejection {
    /// Neither `Origin` nor `Referer` is present.
    #[error("request origin is missing")]
    Missing,
    /// More than one `Origin` header field is present.
    #[error("request contains repeated Origin fields")]
    RepeatedOrigin,
    /// `Origin` is not a single supported HTTP(S) origin.
    #[error("request Origin is malformed")]
    MalformedOrigin,
    /// `Origin: null` cannot identify an allowed origin.
    #[error("opaque request origins are not permitted")]
    OpaqueOrigin,
    /// More than one `Referer` field is present when `Origin` is absent.
    #[error("request contains repeated Referer fields")]
    RepeatedReferer,
    /// The selected `Referer` is not a supported absolute HTTP(S) URL.
    #[error("request Referer is malformed")]
    MalformedReferer,
    /// The source origin does not appear in the allowlist.
    #[error("request origin is not permitted")]
    NotAllowed,
}

impl ClassifyError for OriginRejection {
    fn error_kind(&self) -> ErrorKind {
        ErrorKind::Authorization
    }

    fn error_code(&self) -> ErrorCode {
        ErrorCode::internal(match self {
            Self::Missing => "request_origin_missing",
            Self::RepeatedOrigin => "request_origin_repeated",
            Self::MalformedOrigin => "request_origin_malformed",
            Self::OpaqueOrigin => "request_origin_opaque",
            Self::RepeatedReferer => "request_referer_repeated",
            Self::MalformedReferer => "request_referer_malformed",
            Self::NotAllowed => "request_origin_not_allowed",
        })
    }
}

fn single_header(
    headers: &HeaderMap,
    name: HeaderName,
) -> Result<Option<&axum::http::HeaderValue>, ()> {
    let mut values = headers.get_all(name).iter();
    let first = values.next();
    if values.next().is_some() {
        Err(())
    } else {
        Ok(first)
    }
}

fn parse_web_origin(value: &str, allow_path: bool) -> Option<Origin> {
    // Reject inputs the WHATWG parser would repair before checking their origin.
    if !value.is_ascii()
        || value
            .bytes()
            .any(|byte| byte.is_ascii_control() || byte.is_ascii_whitespace() || byte == b'\\')
    {
        return None;
    }
    let (scheme, rest) = value.split_once("://")?;
    if !scheme.eq_ignore_ascii_case("http") && !scheme.eq_ignore_ascii_case("https") {
        return None;
    }
    let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
    let authority = &rest[..authority_end];
    if authority.is_empty()
        || authority.contains(['@', '%', '*'])
        || authority.ends_with(':')
        || (!allow_path && authority_end != rest.len())
    {
        return None;
    }
    let url = Url::parse(value).ok()?;
    if url.host().is_none() || url.fragment().is_some() {
        return None;
    }
    Some(url.origin())
}