From 71d534dadb8ee0f8593469aeaf00e5a278916e26 Mon Sep 17 00:00:00 2001 From: Nikolay Kim Date: Sat, 20 Jan 2018 16:36:57 -0800 Subject: [PATCH] CORS middleware: allowed_headers is defaulting to None #50 --- CHANGES.md | 1 + src/httpresponse.rs | 4 ++-- src/middleware/cors.rs | 17 ++++++++++++----- src/server/h1.rs | 11 ----------- 4 files changed, 15 insertions(+), 18 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 019e6bc5..61af4ba8 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -6,6 +6,7 @@ * Can't have multiple Applications on a single server with different state #49 +* CORS middleware: allowed_headers is defaulting to None #50 ## 0.3.1 (2018-01-13) diff --git a/src/httpresponse.rs b/src/httpresponse.rs index e356aad3..0293ee32 100644 --- a/src/httpresponse.rs +++ b/src/httpresponse.rs @@ -423,8 +423,8 @@ impl HttpResponseBuilder { } /// This method calls provided closure with builder reference if value is Some. - pub fn if_some(&mut self, value: Option<&T>, f: F) -> &mut Self - where F: FnOnce(&T, &mut HttpResponseBuilder) + pub fn if_some(&mut self, value: Option, f: F) -> &mut Self + where F: FnOnce(T, &mut HttpResponseBuilder) { if let Some(val) = value { f(val, self); diff --git a/src/middleware/cors.rs b/src/middleware/cors.rs index c495a31e..ad5f295c 100644 --- a/src/middleware/cors.rs +++ b/src/middleware/cors.rs @@ -295,16 +295,23 @@ impl Middleware for Cors { self.validate_allowed_method(req)?; self.validate_allowed_headers(req)?; + // allowed headers + let headers = if let Some(headers) = self.headers.as_ref() { + Some(HeaderValue::try_from(&headers.iter().fold( + String::new(), |s, v| s + "," + v.as_str()).as_str()[1..]).unwrap()) + } else if let Some(hdr) = req.headers().get(header::ACCESS_CONTROL_REQUEST_HEADERS) { + Some(hdr.clone()) + } else { + None + }; + Ok(Started::Response( HTTPOk.build() .if_some(self.max_age.as_ref(), |max_age, resp| { let _ = resp.header( header::ACCESS_CONTROL_MAX_AGE, format!("{}", max_age).as_str());}) - .if_some(self.headers.as_ref(), |headers, resp| { - let _ = resp.header( - header::ACCESS_CONTROL_ALLOW_HEADERS, - &headers.iter().fold( - String::new(), |s, v| s + "," + v.as_str()).as_str()[1..]);}) + .if_some(headers, |headers, resp| { + let _ = resp.header(header::ACCESS_CONTROL_ALLOW_HEADERS, headers); }) .if_true(self.origins.is_all(), |resp| { if self.send_wildcard { resp.header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*"); diff --git a/src/server/h1.rs b/src/server/h1.rs index 1b5b3baf..a6affe4c 100644 --- a/src/server/h1.rs +++ b/src/server/h1.rs @@ -1201,17 +1201,6 @@ mod tests { } else { panic!("Error"); } - - let mut buf = Buffer::new( - "GET /test HTTP/1.1\r\n\ - transfer-encoding: chunked\r\n\r\n"); - let req = parse_ready!(&mut buf); - - if let Ok(val) = req.chunked() { - assert!(!val); - } else { - panic!("Error"); - } } #[test]