Skip to content

Commit

Permalink
Change CORS layer construction to allow wildcard (#538)
Browse files Browse the repository at this point in the history
  • Loading branch information
JMicheli authored Dec 26, 2024
1 parent 2dc4fef commit 9459fb7
Showing 1 changed file with 39 additions and 22 deletions.
61 changes: 39 additions & 22 deletions apps/server/src/config/cors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,47 @@ fn merge_origins(origins: &[&str], local_origins: Vec<String>) -> Vec<HeaderValu
pub fn get_cors_layer(config: StumpConfig) -> CorsLayer {
let is_debug = config.is_debug();

let mut allowed_origins = Vec::new();
for origin in config.allowed_origins {
if let Ok(val) = origin.parse::<HeaderValue>() {
allowed_origins.push(val)
} else {
tracing::error!("Failed to parse allowed origin: {:?}", origin);
}
// Create CORS layer
let mut cors_layer = CorsLayer::new();
cors_layer = cors_layer
.allow_methods([
Method::GET,
Method::PUT,
Method::POST,
Method::PATCH,
Method::DELETE,
Method::OPTIONS,
Method::CONNECT,
])
.allow_headers([ACCEPT, AUTHORIZATION, CONTENT_TYPE])
.allow_credentials(true);

// If allowed origins include the general wildcard ("*") then we can return a permissive CORS layer and exit early.
if config.allowed_origins.contains(&"*".to_string()) {
cors_layer = cors_layer.allow_origin(AllowOrigin::any());

#[cfg(debug_assertions)]
tracing::trace!(
?cors_layer,
"Cors configuration completed (allowing any origin)"
);

return cors_layer;
}

// Convert allowed origins from config into `HeaderValue`s for CORS layer.
let allowed_origins: Vec<_> = config
.allowed_origins
.into_iter()
.filter_map(|origin| match origin.parse::<HeaderValue>() {
Ok(val) => Some(val),
Err(e) => {
tracing::error!("Failed to parse allowed origin: {origin:?}: {e}");
None
},
})
.collect();

let local_ip = local_ip()
.map_err(|e| {
tracing::error!("Failed to get local ip: {:?}", e);
Expand Down Expand Up @@ -70,8 +102,6 @@ pub fn get_cors_layer(config: StumpConfig) -> CorsLayer {
base
};

let mut cors_layer = CorsLayer::new();

let defaults = if is_debug {
DEBUG_ALLOWED_ORIGINS
} else {
Expand All @@ -87,19 +117,6 @@ pub fn get_cors_layer(config: StumpConfig) -> CorsLayer {
.collect::<Vec<HeaderValue>>(),
));

cors_layer = cors_layer
.allow_methods([
Method::GET,
Method::PUT,
Method::POST,
Method::PATCH,
Method::DELETE,
Method::OPTIONS,
Method::CONNECT,
])
.allow_headers([ACCEPT, AUTHORIZATION, CONTENT_TYPE])
.allow_credentials(true);

#[cfg(debug_assertions)]
tracing::trace!(?cors_layer, "Cors configuration complete");

Expand Down

0 comments on commit 9459fb7

Please sign in to comment.