Skip to content

Commit ce947f9

Browse files
committed
Fix CORS behaviour if there is no origin header
The CORS origin header handling fell back to an empty header value. This value is considered valid for `Origin::Any` (wildcard origin). However, if the CORS middleware is restricted to a whitelist of origins, the `is_valid_origin` check correctly fails for an empty origin header value. Though, since we fell back to an empty value when there is no origin header at all, we fail the validation and consequentially respond with a 403 (forbidden) to such requests. The CORS specifications stats the following for simple cross-origin requests, actual requests and preflight requests: > If the Origin header is not present terminate this set of steps. The > request is outside the scope of this specification. This commit therefore updates the CORS middleware to ignore requests that have no origin header set.
1 parent a31b69e commit ce947f9

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

src/middleware/cors.rs

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -149,13 +149,16 @@ impl Cors {
149149
impl<State: Send + Sync + 'static> Middleware<State> for Cors {
150150
fn handle<'a>(&'a self, req: Request<State>, next: Next<'a, State>) -> BoxFuture<'a, Response> {
151151
Box::pin(async move {
152-
let origins = req
153-
.header(&headers::ORIGIN)
154-
.cloned()
155-
.unwrap_or_else(|| vec!["".parse::<HeaderValue>().unwrap()]);
152+
let origins = req.header(&headers::ORIGIN).cloned().unwrap_or_default();
156153

157154
// TODO: how should multiple origin values be handled?
158-
let origin = &origins[0];
155+
let origin = match origins.first() {
156+
Some(origin) => origin,
157+
None => {
158+
// This is not a CORS request if there is no Origin header
159+
return next.run(req).await;
160+
}
161+
};
159162

160163
if !self.is_valid_origin(origin) {
161164
return http_types::Response::new(StatusCode::Unauthorized).into();
@@ -395,7 +398,7 @@ mod test {
395398
#[test]
396399
fn not_set_origin_header() {
397400
let mut app = app();
398-
app.middleware(Cors::new());
401+
app.middleware(Cors::new().allow_origin(ALLOW_ORIGIN));
399402

400403
let request = http_types::Request::new(http_types::Method::Get, endpoint_url());
401404

0 commit comments

Comments
 (0)