From 18677a968230380ccc68ecf5fbed0c6699b2bb43 Mon Sep 17 00:00:00 2001 From: Glen De Cauwsemaecker Date: Thu, 22 Feb 2024 22:24:45 +0100 Subject: [PATCH] Fix vary header special-casing in CORS middleware --- tower-http/CHANGELOG.md | 3 +++ tower-http/src/cors/mod.rs | 9 +++++++-- tower-http/src/cors/tests.rs | 2 +- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/tower-http/CHANGELOG.md b/tower-http/CHANGELOG.md index 40492a89..852f77dc 100644 --- a/tower-http/CHANGELOG.md +++ b/tower-http/CHANGELOG.md @@ -14,9 +14,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## Fixed - **compression:** Skip compression for range requests ([#446]) +- **cors:** *Actually* keep Vary headers set by the inner service when setting response headers ([#473]) + - Version 0.5.1 intended to ship this, but the implementation was buggy and didn't actually do anything [#399]: https://github.com/tower-rs/tower-http/pull/399 [#446]: https://github.com/tower-rs/tower-http/pull/446 +[#473]: https://github.com/tower-rs/tower-http/pull/473 # 0.5.1 (January 14, 2024) diff --git a/tower-http/src/cors/mod.rs b/tower-http/src/cors/mod.rs index 0524122d..156576f2 100644 --- a/tower-http/src/cors/mod.rs +++ b/tower-http/src/cors/mod.rs @@ -74,6 +74,9 @@ mod expose_headers; mod max_age; mod vary; +#[cfg(test)] +mod tests; + pub use self::{ allow_credentials::AllowCredentials, allow_headers::AllowHeaders, allow_methods::AllowMethods, allow_origin::AllowOrigin, allow_private_network::AllowPrivateNetwork, @@ -682,13 +685,15 @@ where KindProj::CorsCall { future, headers } => { let mut response: Response = ready!(future.poll(cx))?; + let response_headers = response.headers_mut(); + // vary header can have multiple values, don't overwrite // previously-set value(s). if let Some(vary) = headers.remove(header::VARY) { - headers.append(header::VARY, vary); + response_headers.append(header::VARY, vary); } // extend will overwrite previous headers of remaining names - response.headers_mut().extend(headers.drain()); + response_headers.extend(headers.drain()); Poll::Ready(Ok(response)) } diff --git a/tower-http/src/cors/tests.rs b/tower-http/src/cors/tests.rs index 4eccc41c..8d95df2b 100644 --- a/tower-http/src/cors/tests.rs +++ b/tower-http/src/cors/tests.rs @@ -1,7 +1,7 @@ use std::convert::Infallible; +use crate::test_helpers::Body; use http::{header, HeaderValue, Request, Response}; -use hyper::Body; use tower::{service_fn, util::ServiceExt, Layer}; use crate::cors::CorsLayer;