From 31b7504c08d108fbd7764be8fe1a52974ba52648 Mon Sep 17 00:00:00 2001 From: Zak Nesler Date: Tue, 23 Apr 2024 20:10:02 -0400 Subject: [PATCH] allow all origins by default --- crates/blend-config/stubs/default.toml | 2 +- crates/blend-web/src/lib.rs | 31 ++++++++++++++------------ 2 files changed, 18 insertions(+), 15 deletions(-) diff --git a/crates/blend-config/stubs/default.toml b/crates/blend-config/stubs/default.toml index 94acbcd6..7a1c880b 100644 --- a/crates/blend-config/stubs/default.toml +++ b/crates/blend-config/stubs/default.toml @@ -3,7 +3,7 @@ debug = true [web] host = "127.0.0.1" port = 4000 -allowed_origins = ["http://localhost:4000"] +allowed_origins = ["*"] [database] file = "blend.db" diff --git a/crates/blend-web/src/lib.rs b/crates/blend-web/src/lib.rs index c30e27cf..5ebea4fd 100644 --- a/crates/blend-web/src/lib.rs +++ b/crates/blend-web/src/lib.rs @@ -3,7 +3,7 @@ use axum::http::{header, HeaderValue, Method}; use context::Context; use tokio::net::TcpListener; use tower_cookies::CookieManagerLayer; -use tower_http::{cors::CorsLayer, trace::TraceLayer}; +use tower_http::{cors, trace::TraceLayer}; pub mod context; pub mod error; @@ -19,20 +19,23 @@ pub async fn serve(ctx: Context) -> WebResult<()> { ctx.blend.config.web.port, ); - let allowed_origins = ctx - .blend - .config - .web - .allowed_origins - .iter() - .map(|origin| origin.parse::().map_err(|err| err.into())) - .collect::>>()?; - - let cors = CorsLayer::new() + let mut cors = cors::CorsLayer::new() .allow_methods([Method::GET, Method::POST, Method::PATCH, Method::DELETE]) - .allow_headers([header::AUTHORIZATION, header::ACCEPT, header::CONTENT_TYPE]) - .allow_origin(allowed_origins) - .allow_credentials(true); + .allow_headers([header::AUTHORIZATION, header::ACCEPT, header::CONTENT_TYPE]); + + let origins = &ctx.blend.config.web.allowed_origins; + if origins.contains(&"*".to_string()) { + cors = cors.allow_origin(cors::Any) + } else { + cors = cors + .allow_origin( + origins + .iter() + .map(|origin| origin.parse::().map_err(|err| err.into())) + .collect::>>()?, + ) + .allow_credentials(true); + } let app = crate::router::router(ctx.clone()) .layer(TraceLayer::new_for_http())