glacier-web 0.3.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Cross-origin requests, as rack-cors answers them: preflight `OPTIONS`
//! requests get the allowed methods and headers, and responses to allowed
//! origins say who may read them.
//!
//! ```
//! use glacier::middleware::Cors;
//! let cors = Cors::any_origin()
//!     .methods(["GET", "POST", "PUT", "PATCH", "OPTIONS", "DELETE"])
//!     .expose(["Authorization", "Content-Disposition"]);
//! ```
//!
//! Register it on the app (`App::middleware`), not in a pipeline, so
//! preflight requests are answered before routing.

use http::{HeaderValue, Method, StatusCode, header};

use crate::context::Context;
use crate::handler::BoxFuture;
use crate::middleware::{Middleware, Next};
use crate::response::Response;

/// CORS for an app. Requests without an `Origin` pass through, with
/// `Vary: Origin` so caches keep them apart.
#[derive(Debug, Clone)]
pub struct Cors {
    /// `None`: any origin (`*`).
    origins: Option<Vec<String>>,
    methods: Vec<String>,
    expose: Vec<String>,
    credentials: bool,
    max_age: u64,
}

impl Cors {
    /// Any origin may call the API, as rack-cors' `origins "*"`.
    pub fn any_origin() -> Self {
        Self {
            origins: None,
            methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]
                .map(String::from)
                .to_vec(),
            expose: Vec::new(),
            credentials: false,
            max_age: 7200,
        }
    }

    /// Only these origins (`https://app.example.com`) may.
    pub fn origins<S: Into<String>>(origins: impl IntoIterator<Item = S>) -> Self {
        Self {
            origins: Some(origins.into_iter().map(Into::into).collect()),
            ..Self::any_origin()
        }
    }

    /// The methods allowed, in the order to list them.
    #[must_use]
    pub fn methods<S: Into<String>>(mut self, methods: impl IntoIterator<Item = S>) -> Self {
        self.methods = methods
            .into_iter()
            .map(|m| m.into().to_uppercase())
            .collect();
        self
    }

    /// Response headers a browser may show the page (`Authorization`).
    #[must_use]
    pub fn expose<S: Into<String>>(mut self, headers: impl IntoIterator<Item = S>) -> Self {
        self.expose = headers.into_iter().map(Into::into).collect();
        self
    }

    /// Lets requests carry cookies; the origin is then named, never `*`.
    #[must_use]
    pub fn credentials(mut self) -> Self {
        self.credentials = true;
        self
    }

    /// How long a browser may cache a preflight answer (default 2 hours).
    #[must_use]
    pub fn max_age(mut self, seconds: u64) -> Self {
        self.max_age = seconds;
        self
    }

    /// The `Access-Control-Allow-Origin` for `origin`, if it's allowed.
    fn allow_origin(&self, origin: &str) -> Option<String> {
        match &self.origins {
            None if !self.credentials => Some("*".to_owned()),
            None => Some(origin.to_owned()),
            Some(list) => list.iter().any(|o| o == origin).then(|| origin.to_owned()),
        }
    }

    fn add_headers(&self, response: &mut Response, allow_origin: &str) {
        let mut set = |name: &str, value: String| {
            if let (Ok(name), Ok(value)) = (
                header::HeaderName::try_from(name),
                HeaderValue::try_from(value),
            ) {
                response.headers_mut().insert(name, value);
            }
        };
        set("access-control-allow-origin", allow_origin.to_owned());
        set("access-control-allow-methods", self.methods.join(", "));
        if !self.expose.is_empty() {
            set("access-control-expose-headers", self.expose.join(", "));
        }
        set("access-control-max-age", self.max_age.to_string());
        if self.credentials {
            set("access-control-allow-credentials", "true".to_owned());
        }
    }
}

impl Middleware for Cors {
    fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
        let cors = self.clone();
        Box::pin(async move {
            let origin = ctx.header(header::ORIGIN).map(str::to_owned);
            let requested = ctx
                .header(header::ACCESS_CONTROL_REQUEST_METHOD)
                .map(str::to_uppercase);
            if *ctx.method() == Method::OPTIONS
                && let (Some(origin), Some(requested)) = (&origin, &requested)
            {
                let mut response = Response::head(StatusCode::OK);
                let allowed = cors.methods.iter().any(|m| m == requested);
                if let Some(allow) = cors.allow_origin(origin).filter(|_| allowed) {
                    cors.add_headers(&mut response, &allow);
                    if let Some(headers) = ctx.header(header::ACCESS_CONTROL_REQUEST_HEADERS)
                        && let Ok(value) = HeaderValue::try_from(headers)
                    {
                        response
                            .headers_mut()
                            .insert(header::ACCESS_CONTROL_ALLOW_HEADERS, value);
                    }
                }
                return response;
            }
            let mut response = next.run(ctx).await;
            if let Some(allow) = origin.as_deref().and_then(|o| cors.allow_origin(o)) {
                cors.add_headers(&mut response, &allow);
            }
            let vary = match response
                .headers()
                .get(header::VARY)
                .and_then(|v| v.to_str().ok())
            {
                Some(existing)
                    if existing
                        .split(',')
                        .any(|v| v.trim().eq_ignore_ascii_case("origin")) =>
                {
                    None
                }
                Some(existing) => Some(format!("{existing}, Origin")),
                None => Some("Origin".to_owned()),
            };
            if let Some(vary) = vary.and_then(|v| HeaderValue::try_from(v).ok()) {
                response.headers_mut().insert(header::VARY, vary);
            }
            response
        })
    }
}