use std::fmt;
use std::time::Duration;
use crate::{
AllowCredentials, AllowHeaders, AllowMethods, AllowOrigin, ExposeHeaders, MaxAge, Vary,
};
#[derive(Clone, Debug, Eq, PartialEq)]
#[must_use]
pub struct ConfigError {
message: &'static str,
}
impl ConfigError {
fn new(message: &'static str) -> Self {
Self { message }
}
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Invalid CORS configuration: {}", self.message)
}
}
impl std::error::Error for ConfigError {}
#[derive(Clone, Debug)]
#[must_use]
#[allow(clippy::struct_excessive_bools)]
pub struct CorsBuilder {
pub(crate) allow_origin: AllowOrigin,
pub(crate) allow_credentials: AllowCredentials,
pub(crate) allow_methods: AllowMethods,
pub(crate) allow_headers: AllowHeaders,
pub(crate) expose_headers: ExposeHeaders,
pub(crate) max_age: MaxAge,
pub(crate) vary: Vary,
pub(crate) vary_pinned: bool,
pub(crate) deliver_preflight: bool,
pub(crate) deliver_non_allowed_origin: bool,
pub(crate) deliver_non_allowed_origin_websocket_upgrade: bool,
pub(crate) rejection_status: http::StatusCode,
}
impl Default for CorsBuilder {
fn default() -> Self {
Self {
allow_origin: AllowOrigin::default(),
allow_credentials: AllowCredentials::default(),
allow_methods: AllowMethods::default(),
allow_headers: AllowHeaders::default(),
expose_headers: ExposeHeaders::default(),
max_age: MaxAge::default(),
vary: Vary::default(),
vary_pinned: false,
deliver_preflight: false,
deliver_non_allowed_origin: true,
deliver_non_allowed_origin_websocket_upgrade: false,
rejection_status: http::StatusCode::BAD_REQUEST,
}
}
}
impl CorsBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn allow_origin<T>(mut self, allow_origin: T) -> Self
where
T: Into<AllowOrigin>,
{
self.allow_origin = allow_origin.into();
self
}
pub fn allow_credentials<T>(mut self, allow_credentials: T) -> Self
where
T: Into<AllowCredentials>,
{
self.allow_credentials = allow_credentials.into();
self
}
pub fn allow_methods<T>(mut self, allow_methods: T) -> Self
where
T: Into<AllowMethods>,
{
self.allow_methods = allow_methods.into();
self
}
pub fn allow_headers<T>(mut self, allow_headers: T) -> Self
where
T: Into<AllowHeaders>,
{
self.allow_headers = allow_headers.into();
self
}
pub fn expose_headers<T>(mut self, expose_headers: T) -> Self
where
T: Into<ExposeHeaders>,
{
self.expose_headers = expose_headers.into();
self
}
pub fn max_age(mut self, max_age: Duration) -> Self {
self.max_age = MaxAge::exact(max_age);
self
}
pub fn vary<T>(mut self, headers: T) -> Self
where
T: Into<Vary>,
{
self.vary = headers.into();
self.vary_pinned = true;
self
}
pub fn deliver_preflight(mut self, deliver: bool) -> Self {
self.deliver_preflight = deliver;
self
}
pub fn deliver_non_allowed_origin(mut self, deliver: bool) -> Self {
self.deliver_non_allowed_origin = deliver;
self
}
pub fn deliver_non_allowed_origin_websocket_upgrade(mut self, deliver: bool) -> Self {
self.deliver_non_allowed_origin_websocket_upgrade = deliver;
self
}
pub fn rejection_status(mut self, status: http::StatusCode) -> Self {
self.rejection_status = status;
self
}
pub fn build<S>(self, inner: S) -> crate::Cors<S> {
match self.try_build(inner) {
Ok(cors) => cors,
Err(e) => panic!("{e}"),
}
}
pub fn try_build<S>(self, inner: S) -> Result<crate::Cors<S>, ConfigError> {
self.validate()?;
let mut me = self;
me.update_vary();
Ok(crate::Cors::from_parts(inner, me))
}
fn validate(&self) -> Result<(), ConfigError> {
if !self.allow_credentials.is_true() {
return Ok(());
}
if self.allow_origin.is_wildcard() {
return Err(ConfigError::new(
"cannot combine `Access-Control-Allow-Credentials: true` \
with `Access-Control-Allow-Origin: *`. Echo the request origin instead.",
));
}
if self.allow_methods.is_wildcard() {
return Err(ConfigError::new(
"cannot combine `Access-Control-Allow-Credentials: true` \
with `Access-Control-Allow-Methods: *`.",
));
}
if self.allow_headers.is_wildcard() {
return Err(ConfigError::new(
"cannot combine `Access-Control-Allow-Credentials: true` \
with `Access-Control-Allow-Headers: *`.",
));
}
if self.expose_headers.is_wildcard() {
return Err(ConfigError::new(
"cannot combine `Access-Control-Allow-Credentials: true` \
with `Access-Control-Expose-Headers: *`.",
));
}
Ok(())
}
pub(crate) fn update_vary(&mut self) {
if self.vary_pinned {
return;
}
let vary_method = self.allow_methods.varies_with_request_method();
let vary_headers = self.allow_headers.varies_with_request_headers();
let mut names = Vec::with_capacity(3);
names.push(http::header::ORIGIN);
if vary_method {
names.push(http::header::ACCESS_CONTROL_REQUEST_METHOD);
}
if vary_headers {
names.push(http::header::ACCESS_CONTROL_REQUEST_HEADERS);
}
self.vary = Vary::list(names);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn origin() -> AllowOrigin {
AllowOrigin::exact(http::HeaderValue::from_static("https://app.example.com"))
}
#[test]
fn try_build_succeeds_for_default_config() {
let builder = CorsBuilder::new();
let result: Result<crate::Cors<()>, ConfigError> = builder.try_build(());
assert!(result.is_ok());
}
#[test]
fn try_build_succeeds_for_credentials_with_concrete_origin_and_headers() {
let builder = CorsBuilder::new()
.allow_credentials(AllowCredentials::yes())
.allow_origin(origin());
let result: Result<crate::Cors<()>, ConfigError> = builder.try_build(());
assert!(result.is_ok());
}
#[test]
fn try_build_rejects_credentials_with_wildcard_origin() {
let builder = CorsBuilder::new()
.allow_credentials(AllowCredentials::yes())
.allow_origin(crate::Any);
let err = builder
.try_build::<()>(())
.expect_err("wildcard origin must be rejected");
assert!(err.to_string().contains("Allow-Origin: *"));
}
#[test]
fn try_build_rejects_credentials_with_wildcard_methods() {
let builder = CorsBuilder::new()
.allow_credentials(AllowCredentials::yes())
.allow_origin(origin())
.allow_methods(crate::AllowMethods::any());
let err = builder
.try_build::<()>(())
.expect_err("wildcard methods must be rejected");
assert!(err.to_string().contains("Allow-Methods: *"));
}
#[test]
fn try_build_rejects_credentials_with_wildcard_headers() {
let builder = CorsBuilder::new()
.allow_credentials(AllowCredentials::yes())
.allow_origin(origin())
.allow_headers(crate::AllowHeaders::any());
let err = builder
.try_build::<()>(())
.expect_err("wildcard headers must be rejected");
assert!(err.to_string().contains("Allow-Headers: *"));
}
#[test]
fn try_build_rejects_credentials_with_wildcard_expose_headers() {
let builder = CorsBuilder::new()
.allow_credentials(AllowCredentials::yes())
.allow_origin(origin())
.expose_headers(crate::ExposeHeaders::any());
let err = builder
.try_build::<()>(())
.expect_err("wildcard expose-headers must be rejected");
assert!(err.to_string().contains("Expose-Headers: *"));
}
#[test]
fn build_still_panics_on_incompatible_config() {
let builder = CorsBuilder::new()
.allow_credentials(AllowCredentials::yes())
.allow_origin(crate::Any);
let result =
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| builder.build::<()>(())));
assert!(result.is_err(), "build must panic on wildcard origin");
}
}