From 1b751a8cacb8175388adbb52eac3e45c36094622 Mon Sep 17 00:00:00 2001 From: Dessalines Date: Wed, 25 Oct 2023 10:46:34 -0400 Subject: [PATCH] Adding cors_origin to settings. Fixes #3665 (#4095) * Adding cors_origin to settings. Fixes #3665 * Fix result to option. * Forgot to update config defaults. * Setting a cors origin doku default. * Adding comments for CORS. --- config/defaults.hjson | 3 +++ crates/utils/src/settings/structs.rs | 5 +++++ src/lib.rs | 7 +++++-- 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/config/defaults.hjson b/config/defaults.hjson index 4b616f677..46e4e0a41 100644 --- a/config/defaults.hjson +++ b/config/defaults.hjson @@ -86,4 +86,7 @@ bind: "127.0.0.1" port: 10002 } + # 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: "*" } diff --git a/crates/utils/src/settings/structs.rs b/crates/utils/src/settings/structs.rs index c7d0cd3e6..4c39e08aa 100644 --- a/crates/utils/src/settings/structs.rs +++ b/crates/utils/src/settings/structs.rs @@ -49,6 +49,11 @@ pub struct Settings { #[default(None)] #[doku(example = "Some(Default::default())")] pub prometheus: Option, + /// 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 = "*")] + pub cors_origin: Option, } #[derive(Debug, Deserialize, Serialize, Clone, SmartDefault, Document)] diff --git a/src/lib.rs b/src/lib.rs index 774857b95..6e62a6803 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -282,11 +282,14 @@ fn create_http_server( let context: LemmyContext = federation_config.deref().clone(); let rate_limit_cell = federation_config.rate_limit_cell().clone(); let self_origin = settings.get_protocol_and_hostname(); + let cors_origin_setting = settings.cors_origin; // Create Http server with websocket support let server = HttpServer::new(move || { - let cors_origin = env::var("LEMMY_CORS_ORIGIN"); + let cors_origin = env::var("LEMMY_CORS_ORIGIN") + .ok() + .or(cors_origin_setting.clone()); let cors_config = match (cors_origin, cfg!(debug_assertions)) { - (Ok(origin), false) => Cors::default() + (Some(origin), false) => Cors::default() .allowed_origin(&origin) .allowed_origin(&self_origin), _ => Cors::default()