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 GitHub
parent f916309df8
commit faf62de4e3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 18 additions and 10 deletions

View file

@ -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"
}

View file

@ -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<String>,
}

View file

@ -339,23 +339,31 @@ 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,
}
}