From f8f035f3842a402476da3b18b17be87dc17e393d Mon Sep 17 00:00:00 2001 From: Dessalines Date: Wed, 13 Nov 2024 03:45:17 -0500 Subject: [PATCH] Fixing cors origin wildcard. (#5194) * Fixing cors origin wildcard. - Fixes #5185 * Add other allows to specified origin block. * Fix clippy. --- config/defaults.hjson | 2 +- crates/utils/src/settings/structs.rs | 2 +- src/lib.rs | 24 ++++++++++++++++-------- 3 files changed, 18 insertions(+), 10 deletions(-) diff --git a/config/defaults.hjson b/config/defaults.hjson index 96dc30b79..c12f879c7 100644 --- a/config/defaults.hjson +++ b/config/defaults.hjson @@ -122,5 +122,5 @@ } # Sets a response Access-Control-Allow-Origin CORS header # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin - cors_origin: "*" + cors_origin: "lemmy.tld" } diff --git a/crates/utils/src/settings/structs.rs b/crates/utils/src/settings/structs.rs index c95f66644..e8106d482 100644 --- a/crates/utils/src/settings/structs.rs +++ b/crates/utils/src/settings/structs.rs @@ -52,7 +52,7 @@ pub struct Settings { /// Sets a response Access-Control-Allow-Origin CORS header /// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin #[default(None)] - #[doku(example = "*")] + #[doku(example = "lemmy.tld")] cors_origin: Option, } diff --git a/src/lib.rs b/src/lib.rs index 3c3633b75..921109ca9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -353,24 +353,32 @@ fn create_http_server( fn cors_config(settings: &Settings) -> Cors { let self_origin = settings.get_protocol_and_hostname(); let cors_origin_setting = settings.cors_origin(); + + // A default setting for either wildcard, or None + let cors_default = Cors::default() + .allow_any_origin() + .allow_any_method() + .allow_any_header() + .expose_any_header() + .max_age(3600); + match (cors_origin_setting.clone(), cfg!(debug_assertions)) { (Some(origin), false) => { // Need to call send_wildcard() explicitly, passing this into allowed_origin() results in // error - if cors_origin_setting.as_deref() == Some("*") { - Cors::default().allow_any_origin().send_wildcard() + if origin == "*" { + cors_default } else { Cors::default() .allowed_origin(&origin) .allowed_origin(&self_origin) + .allow_any_method() + .allow_any_header() + .expose_any_header() + .max_age(3600) } } - _ => Cors::default() - .allow_any_origin() - .allow_any_method() - .allow_any_header() - .expose_any_header() - .max_age(3600), + _ => cors_default, } }