Fixing cors origin wildcard. (#5194)

* Fixing cors origin wildcard.

- Fixes #5185

* Add other allows to specified origin block.

* Fix clippy.
This commit is contained in:
Dessalines 2024-11-13 03:45:17 -05:00 committed by Felix Ableitner
parent 005f4d53c8
commit f8f035f384
3 changed files with 18 additions and 10 deletions

View file

@ -122,5 +122,5 @@
} }
# Sets a response Access-Control-Allow-Origin CORS header # Sets a response Access-Control-Allow-Origin CORS header
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
cors_origin: "*" cors_origin: "lemmy.tld"
} }

View file

@ -52,7 +52,7 @@ pub struct Settings {
/// Sets a response Access-Control-Allow-Origin CORS header /// Sets a response Access-Control-Allow-Origin CORS header
/// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin /// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
#[default(None)] #[default(None)]
#[doku(example = "*")] #[doku(example = "lemmy.tld")]
cors_origin: Option<String>, cors_origin: Option<String>,
} }

View file

@ -353,24 +353,32 @@ fn create_http_server(
fn cors_config(settings: &Settings) -> Cors { fn cors_config(settings: &Settings) -> Cors {
let self_origin = settings.get_protocol_and_hostname(); let self_origin = settings.get_protocol_and_hostname();
let cors_origin_setting = settings.cors_origin(); let cors_origin_setting = settings.cors_origin();
match (cors_origin_setting.clone(), cfg!(debug_assertions)) {
(Some(origin), false) => { // A default setting for either wildcard, or None
// Need to call send_wildcard() explicitly, passing this into allowed_origin() results in let cors_default = Cors::default()
// error
if cors_origin_setting.as_deref() == Some("*") {
Cors::default().allow_any_origin().send_wildcard()
} else {
Cors::default()
.allowed_origin(&origin)
.allowed_origin(&self_origin)
}
}
_ => Cors::default()
.allow_any_origin() .allow_any_origin()
.allow_any_method() .allow_any_method()
.allow_any_header() .allow_any_header()
.expose_any_header() .expose_any_header()
.max_age(3600), .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 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,
} }
} }