Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: avoid setting content-length before middleware (backport) #3031

Merged
merged 3 commits into from
Nov 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 17 additions & 11 deletions axum/src/routing/route.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use std::{
task::{Context, Poll},
};
use tower::{
util::{BoxCloneService, MapErrLayer, MapRequestLayer, MapResponseLayer, Oneshot},
util::{BoxCloneService, MapErrLayer, MapResponseLayer, Oneshot},
ServiceExt,
};
use tower_layer::Layer;
Expand Down Expand Up @@ -73,7 +73,6 @@ impl<E> Route<E> {
NewError: 'static,
{
let layer = (
MapRequestLayer::new(|req: Request<_>| req.map(Body::new)),
MapErrLayer::new(Into::into),
MapResponseLayer::new(IntoResponse::into_response),
layer,
Expand Down Expand Up @@ -113,7 +112,7 @@ where
#[inline]
fn call(&mut self, req: Request<B>) -> Self::Future {
let req = req.map(Body::new);
RouteFuture::from_future(self.oneshot_inner(req))
RouteFuture::from_future(self.oneshot_inner(req)).not_top_level()
}
}

Expand All @@ -124,6 +123,7 @@ pin_project! {
kind: RouteFutureKind<E>,
strip_body: bool,
allow_header: Option<Bytes>,
top_level: bool,
}
}

Expand Down Expand Up @@ -151,6 +151,7 @@ impl<E> RouteFuture<E> {
kind: RouteFutureKind::Future { future },
strip_body: false,
allow_header: None,
top_level: true,
}
}

Expand All @@ -163,6 +164,11 @@ impl<E> RouteFuture<E> {
self.allow_header = Some(allow_header);
self
}

pub(crate) fn not_top_level(mut self) -> Self {
self.top_level = false;
self
}
}

impl<E> Future for RouteFuture<E> {
Expand All @@ -183,16 +189,16 @@ impl<E> Future for RouteFuture<E> {
}
};

set_allow_header(res.headers_mut(), this.allow_header);
if *this.top_level {
set_allow_header(res.headers_mut(), this.allow_header);

// make sure to set content-length before removing the body
set_content_length(res.size_hint(), res.headers_mut());
// make sure to set content-length before removing the body
set_content_length(res.size_hint(), res.headers_mut());

let res = if *this.strip_body {
res.map(|_| Body::empty())
} else {
res
};
if *this.strip_body {
*res.body_mut() = Body::empty();
}
}

Poll::Ready(Ok(res))
}
Expand Down
19 changes: 19 additions & 0 deletions axum/src/routing/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1087,3 +1087,22 @@ async fn locks_mutex_very_little() {
assert_eq!(num, 1);
}
}

#[crate::test]
async fn middleware_adding_body() {
let app = Router::new()
.route("/", get(()))
.layer(MapResponseLayer::new(|mut res: Response| -> Response {
// If there is a content-length header, its value will be zero and axum will avoid
// overwriting it. But this means our content-length doesn't match the length of the
// body, which leads to panics in Hyper. Thus we have to ensure that axum doesn't add
// on content-length headers until after middleware has been run.
assert!(!res.headers().contains_key("content-length"));
*res.body_mut() = "…".into();
res
}));

let client = TestClient::new(app);
let res = client.get("/").await;
assert_eq!(res.text().await, "…");
}
Loading