CORS fixes

* The Safari extension apparently now uses the origin `file://` and expects
  that to be returned (see bitwarden/browser#1311, bitwarden/server#800).

* The `Access-Control-Allow-Origin` header was reflecting the value of the
  `Origin` header without checking whether the origin was actually allowed.
  This effectively allows any origin to interact with the server, which
  defeats the purpose of CORS.
This commit is contained in:
Jeremy Lin 2021-03-07 00:35:08 -08:00
parent dad1b1bee9
commit 7d0e234b34
1 changed files with 14 additions and 8 deletions

View File

@ -48,10 +48,16 @@ impl CORS {
} }
} }
fn valid_url(url: String) -> String { // Check a request's `Origin` header against the list of allowed origins.
match url.as_ref() { // If a match exists, return it. Otherwise, return None.
"file://" => "*".to_string(), fn get_allowed_origin(headers: &HeaderMap) -> Option<String> {
_ => url, let origin = CORS::get_header(headers, "Origin");
let domain_origin = CONFIG.domain_origin();
let safari_extension_origin = "file://";
if origin == domain_origin || origin == safari_extension_origin {
Some(origin)
} else {
None
} }
} }
} }
@ -67,11 +73,11 @@ impl Fairing for CORS {
fn on_response(&self, request: &Request, response: &mut Response) { fn on_response(&self, request: &Request, response: &mut Response) {
let req_headers = request.headers(); let req_headers = request.headers();
// We need to explicitly get the Origin header for Access-Control-Allow-Origin if let Some(origin) = CORS::get_allowed_origin(req_headers) {
let req_allow_origin = CORS::valid_url(CORS::get_header(req_headers, "Origin")); response.set_header(Header::new("Access-Control-Allow-Origin", origin));
}
response.set_header(Header::new("Access-Control-Allow-Origin", req_allow_origin));
// Preflight request
if request.method() == Method::Options { if request.method() == Method::Options {
let req_allow_headers = CORS::get_header(req_headers, "Access-Control-Request-Headers"); let req_allow_headers = CORS::get_header(req_headers, "Access-Control-Request-Headers");
let req_allow_method = CORS::get_header(req_headers, "Access-Control-Request-Method"); let req_allow_method = CORS::get_header(req_headers, "Access-Control-Request-Method");