Skip to content

Commit b942481

Browse files
jplattedavidpdrsn
andauthored
Add RequestExt::{with_limited_body, into_limited_body} (#1420)
* Move RequestExt and RequestPartsExt into axum-core * Add RequestExt::into_limited_body … and use it for Bytes extraction. * Add RequestExt::with_limited_body … and use it for Multipart extraction. Co-authored-by: David Pedersen <david.pdrsn@gmail.com>
1 parent be54583 commit b942481

10 files changed

Lines changed: 87 additions & 44 deletions

File tree

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,34 @@
11
pub(crate) mod request;
22
pub(crate) mod request_parts;
3-
pub(crate) mod service;
43

54
#[cfg(test)]
65
mod tests {
76
use std::convert::Infallible;
87

8+
use crate::extract::{FromRef, FromRequestParts};
99
use async_trait::async_trait;
10-
use axum_core::extract::{FromRef, FromRequestParts};
1110
use http::request::Parts;
1211

12+
#[derive(Debug, Default, Clone, Copy)]
13+
pub(crate) struct State<S>(pub(crate) S);
14+
15+
#[async_trait]
16+
impl<OuterState, InnerState> FromRequestParts<OuterState> for State<InnerState>
17+
where
18+
InnerState: FromRef<OuterState>,
19+
OuterState: Send + Sync,
20+
{
21+
type Rejection = Infallible;
22+
23+
async fn from_request_parts(
24+
_parts: &mut Parts,
25+
state: &OuterState,
26+
) -> Result<Self, Self::Rejection> {
27+
let inner_state = InnerState::from_ref(state);
28+
Ok(Self(inner_state))
29+
}
30+
}
31+
1332
// some extractor that requires the state, such as `SignedCookieJar`
1433
pub(crate) struct RequiresState(pub(crate) String);
1534

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
use axum_core::extract::{FromRequest, FromRequestParts};
1+
use crate::extract::{DefaultBodyLimitKind, FromRequest, FromRequestParts};
22
use futures_util::future::BoxFuture;
33
use http::Request;
4+
use http_body::Limited;
45

56
mod sealed {
67
pub trait Sealed<B> {}
@@ -48,6 +49,16 @@ pub trait RequestExt<B>: sealed::Sealed<B> + Sized {
4849
where
4950
E: FromRequestParts<S> + 'static,
5051
S: Send + Sync;
52+
53+
/// Apply the [default body limit](crate::extract::DefaultBodyLimit).
54+
///
55+
/// If it is disabled, return the request as-is in `Err`.
56+
fn with_limited_body(self) -> Result<Request<Limited<B>>, Request<B>>;
57+
58+
/// Consumes the request, returning the body wrapped in [`Limited`] if a
59+
/// [default limit](crate::extract::DefaultBodyLimit) is in place, or not wrapped if the
60+
/// default limit is disabled.
61+
fn into_limited_body(self) -> Result<Limited<B>, B>;
5162
}
5263

5364
impl<B> RequestExt<B> for Request<B>
@@ -105,14 +116,36 @@ where
105116
result
106117
})
107118
}
119+
120+
fn with_limited_body(self) -> Result<Request<Limited<B>>, Request<B>> {
121+
// update docs in `axum-core/src/extract/default_body_limit.rs` and
122+
// `axum/src/docs/extract.md` if this changes
123+
const DEFAULT_LIMIT: usize = 2_097_152; // 2 mb
124+
125+
match self.extensions().get::<DefaultBodyLimitKind>().copied() {
126+
Some(DefaultBodyLimitKind::Disable) => Err(self),
127+
Some(DefaultBodyLimitKind::Limit(limit)) => {
128+
Ok(self.map(|b| http_body::Limited::new(b, limit)))
129+
}
130+
None => Ok(self.map(|b| http_body::Limited::new(b, DEFAULT_LIMIT))),
131+
}
132+
}
133+
134+
fn into_limited_body(self) -> Result<Limited<B>, B> {
135+
self.with_limited_body()
136+
.map(Request::into_body)
137+
.map_err(Request::into_body)
138+
}
108139
}
109140

110141
#[cfg(test)]
111142
mod tests {
112143
use super::*;
113-
use crate::{ext_traits::tests::RequiresState, extract::State};
144+
use crate::{
145+
ext_traits::tests::{RequiresState, State},
146+
extract::FromRef,
147+
};
114148
use async_trait::async_trait;
115-
use axum_core::extract::FromRef;
116149
use http::Method;
117150
use hyper::Body;
118151

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use axum_core::extract::FromRequestParts;
1+
use crate::extract::FromRequestParts;
22
use futures_util::future::BoxFuture;
33
use http::request::Parts;
44

@@ -53,9 +53,11 @@ mod tests {
5353
use std::convert::Infallible;
5454

5555
use super::*;
56-
use crate::{ext_traits::tests::RequiresState, extract::State};
56+
use crate::{
57+
ext_traits::tests::{RequiresState, State},
58+
extract::FromRef,
59+
};
5760
use async_trait::async_trait;
58-
use axum_core::extract::FromRef;
5961
use http::{Method, Request};
6062

6163
#[tokio::test]
@@ -73,7 +75,10 @@ mod tests {
7375

7476
let state = "state".to_owned();
7577

76-
let State(extracted_state): State<String> = parts.extract_with_state(&state).await.unwrap();
78+
let State(extracted_state): State<String> = parts
79+
.extract_with_state::<State<String>, String>(&state)
80+
.await
81+
.unwrap();
7782

7883
assert_eq!(extracted_state, state);
7984
}

axum-core/src/extract/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ mod from_ref;
1616
mod request_parts;
1717
mod tuple;
1818

19+
pub(crate) use self::default_body_limit::DefaultBodyLimitKind;
1920
pub use self::{default_body_limit::DefaultBodyLimit, from_ref::FromRef};
2021

2122
mod private {

axum-core/src/extract/request_parts.rs

Lines changed: 7 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
1-
use super::{
2-
default_body_limit::DefaultBodyLimitKind, rejection::*, FromRequest, FromRequestParts,
3-
};
4-
use crate::BoxError;
1+
use super::{rejection::*, FromRequest, FromRequestParts};
2+
use crate::{BoxError, RequestExt};
53
use async_trait::async_trait;
64
use bytes::Bytes;
75
use http::{request::Parts, HeaderMap, Method, Request, Uri, Version};
@@ -84,27 +82,13 @@ where
8482
type Rejection = BytesRejection;
8583

8684
async fn from_request(req: Request<B>, _: &S) -> Result<Self, Self::Rejection> {
87-
// update docs in `axum-core/src/extract/default_body_limit.rs` and
88-
// `axum/src/docs/extract.md` if this changes
89-
const DEFAULT_LIMIT: usize = 2_097_152; // 2 mb
90-
91-
let limit_kind = req.extensions().get::<DefaultBodyLimitKind>().copied();
92-
let bytes = match limit_kind {
93-
Some(DefaultBodyLimitKind::Disable) => crate::body::to_bytes(req.into_body())
85+
let bytes = match req.into_limited_body() {
86+
Ok(limited_body) => crate::body::to_bytes(limited_body)
87+
.await
88+
.map_err(FailedToBufferBody::from_err)?,
89+
Err(unlimited_body) => crate::body::to_bytes(unlimited_body)
9490
.await
9591
.map_err(FailedToBufferBody::from_err)?,
96-
Some(DefaultBodyLimitKind::Limit(limit)) => {
97-
let body = http_body::Limited::new(req.into_body(), limit);
98-
crate::body::to_bytes(body)
99-
.await
100-
.map_err(FailedToBufferBody::from_err)?
101-
}
102-
None => {
103-
let body = http_body::Limited::new(req.into_body(), DEFAULT_LIMIT);
104-
crate::body::to_bytes(body)
105-
.await
106-
.map_err(FailedToBufferBody::from_err)?
107-
}
10892
};
10993

11094
Ok(bytes)

axum-core/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@
5252
pub(crate) mod macros;
5353

5454
mod error;
55+
mod ext_traits;
5556
pub use self::error::Error;
5657

5758
pub mod body;
@@ -60,3 +61,5 @@ pub mod response;
6061

6162
/// Alias for a type-erased error type.
6263
pub type BoxError = Box<dyn std::error::Error + Send + Sync>;
64+
65+
pub use self::ext_traits::{request::RequestExt, request_parts::RequestPartsExt};

axum/CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
4040
you likely need to re-enable the `tokio` feature ([#1382])
4141
- **breaking:** `handler::{WithState, IntoService}` are merged into one type,
4242
named `HandlerService` ([#1418])
43+
- **changed:** The default body limit now applies to the `Multipart` extractor ([#1420])
4344
- **added:** String and binary `From` impls have been added to `extract::ws::Message`
4445
to be more inline with `tungstenite` ([#1421])
4546

@@ -54,6 +55,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
5455
[#1408]: https://github.com/tokio-rs/axum/pull/1408
5556
[#1414]: https://github.com/tokio-rs/axum/pull/1414
5657
[#1418]: https://github.com/tokio-rs/axum/pull/1418
58+
[#1420]: https://github.com/tokio-rs/axum/pull/1420
5759
[#1421]: https://github.com/tokio-rs/axum/pull/1421
5860

5961
# 0.6.0-rc.2 (10. September, 2022)

axum/src/extract/multipart.rs

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use super::{BodyStream, FromRequest};
66
use crate::body::{Bytes, HttpBody};
77
use crate::BoxError;
88
use async_trait::async_trait;
9+
use axum_core::RequestExt;
910
use futures_util::stream::Stream;
1011
use http::header::{HeaderMap, CONTENT_TYPE};
1112
use http::Request;
@@ -47,10 +48,6 @@ use std::{
4748
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
4849
/// # };
4950
/// ```
50-
///
51-
/// For security reasons it's recommended to combine this with
52-
/// [`RequestBodyLimitLayer`](tower_http::limit::RequestBodyLimitLayer)
53-
/// to limit the size of the request payload.
5451
#[cfg_attr(docsrs, doc(cfg(feature = "multipart")))]
5552
#[derive(Debug)]
5653
pub struct Multipart {
@@ -69,10 +66,11 @@ where
6966

7067
async fn from_request(req: Request<B>, state: &S) -> Result<Self, Self::Rejection> {
7168
let boundary = parse_boundary(req.headers()).ok_or(InvalidBoundary)?;
72-
let stream = match BodyStream::from_request(req, state).await {
73-
Ok(stream) => stream,
74-
Err(err) => match err {},
69+
let stream_result = match req.with_limited_body() {
70+
Ok(limited) => BodyStream::from_request(limited, state).await,
71+
Err(unlimited) => BodyStream::from_request(unlimited, state).await,
7572
};
73+
let stream = stream_result.unwrap_or_else(|err| match err {});
7674
let multipart = multer::Multipart::new(stream, boundary);
7775
Ok(Self { inner: multipart })
7876
}

axum/src/lib.rs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -434,12 +434,12 @@
434434
#[macro_use]
435435
pub(crate) mod macros;
436436

437-
mod ext_traits;
438437
mod extension;
439438
#[cfg(feature = "form")]
440439
mod form;
441440
#[cfg(feature = "json")]
442441
mod json;
442+
mod service_ext;
443443
#[cfg(feature = "headers")]
444444
mod typed_header;
445445
mod util;
@@ -483,11 +483,9 @@ pub use self::typed_header::TypedHeader;
483483
pub use self::form::Form;
484484

485485
#[doc(inline)]
486-
pub use axum_core::{BoxError, Error};
486+
pub use axum_core::{BoxError, Error, RequestExt, RequestPartsExt};
487487

488488
#[cfg(feature = "macros")]
489489
pub use axum_macros::debug_handler;
490490

491-
pub use self::ext_traits::{
492-
request::RequestExt, request_parts::RequestPartsExt, service::ServiceExt,
493-
};
491+
pub use self::service_ext::ServiceExt;

0 commit comments

Comments
 (0)