Skip to content

Commit

Permalink
cors: Don't overwrite vary header set by the inner service
Browse files Browse the repository at this point in the history
  • Loading branch information
jplatte committed Jan 13, 2024
1 parent 503217c commit b07c731
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
7 changes: 7 additions & 0 deletions tower-http/src/cors/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -681,6 +681,13 @@ where
match self.project().inner.project() {
KindProj::CorsCall { future, headers } => {
let mut response: Response<B> = ready!(future.poll(cx))?;

// 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);
}
// extend will overwrite previous headers of remaining names
response.headers_mut().extend(headers.drain());

Poll::Ready(Ok(response))
Expand Down
33 changes: 33 additions & 0 deletions tower-http/src/cors/tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use std::convert::Infallible;

use http::{header, HeaderValue, Request, Response};
use hyper::Body;
use tower::{service_fn, util::ServiceExt, Layer};

use crate::cors::CorsLayer;

#[tokio::test]
#[allow(
clippy::declare_interior_mutable_const,
clippy::borrow_interior_mutable_const
)]
async fn vary_set_by_inner_service() {
const CUSTOM_VARY_HEADERS: HeaderValue = HeaderValue::from_static("accept, accept-encoding");
const PERMISSIVE_CORS_VARY_HEADERS: HeaderValue = HeaderValue::from_static(
"origin, access-control-request-method, access-control-request-headers",
);

async fn inner_svc(_: Request<Body>) -> Result<Response<Body>, Infallible> {
Ok(Response::builder()
.header(header::VARY, CUSTOM_VARY_HEADERS)
.body(Body::empty())
.unwrap())
}

let svc = CorsLayer::permissive().layer(service_fn(inner_svc));
let res = svc.oneshot(Request::new(Body::empty())).await.unwrap();
let mut vary_headers = res.headers().get_all(header::VARY).into_iter();
assert_eq!(vary_headers.next(), Some(&CUSTOM_VARY_HEADERS));
assert_eq!(vary_headers.next(), Some(&PERMISSIVE_CORS_VARY_HEADERS));
assert_eq!(vary_headers.next(), None);
}

0 comments on commit b07c731

Please sign in to comment.