From 4263574a589e04f17d76313e70bbac1522decabb Mon Sep 17 00:00:00 2001 From: Nikolay Kim Date: Sat, 10 Mar 2018 08:31:20 -0800 Subject: [PATCH] fix panic in cors if request does not contain origin header and send_wildcard is not set --- CHANGES.md | 2 ++ src/middleware/cors.rs | 22 ++++++++++++++++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 2f07ca78d..8a9d029f7 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -4,6 +4,8 @@ * Fix client cookie handling +* Fix CORS middleware #117 + * Optimize websockets stream support diff --git a/src/middleware/cors.rs b/src/middleware/cors.rs index 25ae747ce..387cc8d2e 100644 --- a/src/middleware/cors.rs +++ b/src/middleware/cors.rs @@ -349,8 +349,7 @@ impl Middleware for Cors { if self.send_wildcard { resp.headers_mut().insert( header::ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*")); - } else { - let origin = req.headers().get(header::ORIGIN).unwrap(); + } else if let Some(origin) = req.headers().get(header::ORIGIN) { resp.headers_mut().insert( header::ACCESS_CONTROL_ALLOW_ORIGIN, origin.clone()); } @@ -807,6 +806,25 @@ mod tests { assert!(cors.start(&mut req).unwrap().is_done()); } + #[test] + fn test_no_origin_response() { + let cors = Cors::build().finish().unwrap(); + + let mut req = TestRequest::default().method(Method::GET).finish(); + let resp: HttpResponse = HttpOk.into(); + let resp = cors.response(&mut req, resp).unwrap().response(); + assert!(resp.headers().get(header::ACCESS_CONTROL_ALLOW_ORIGIN).is_none()); + + let mut req = TestRequest::with_header( + "Origin", "https://www.example.com") + .method(Method::OPTIONS) + .finish(); + let resp = cors.response(&mut req, resp).unwrap().response(); + assert_eq!( + &b"https://www.example.com"[..], + resp.headers().get(header::ACCESS_CONTROL_ALLOW_ORIGIN).unwrap().as_bytes()); + } + #[test] fn test_response() { let cors = Cors::build()