Skip to content

Commit 023bb02

Browse files
committed
Add RequestExt::with_limited_body
… and use it for Multipart extraction.
1 parent 5fa0894 commit 023bb02

3 files changed

Lines changed: 21 additions & 11 deletions

File tree

axum-core/src/ext_traits/request.rs

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,11 @@ pub trait RequestExt<B>: sealed::Sealed<B> + Sized {
5050
E: FromRequestParts<S> + 'static,
5151
S: Send + Sync;
5252

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+
5358
/// Consumes the request, returning the body wrapped in [`Limited`] if a
5459
/// [default limit](crate::extract::DefaultBodyLimit) is in place, or not wrapped if the
5560
/// default limit is disabled.
@@ -112,19 +117,25 @@ where
112117
})
113118
}
114119

115-
fn into_limited_body(self) -> Result<Limited<B>, B> {
120+
fn with_limited_body(self) -> Result<Request<Limited<B>>, Request<B>> {
116121
// update docs in `axum-core/src/extract/default_body_limit.rs` and
117122
// `axum/src/docs/extract.md` if this changes
118123
const DEFAULT_LIMIT: usize = 2_097_152; // 2 mb
119124

120125
match self.extensions().get::<DefaultBodyLimitKind>().copied() {
121-
Some(DefaultBodyLimitKind::Disable) => Err(self.into_body()),
126+
Some(DefaultBodyLimitKind::Disable) => Err(self),
122127
Some(DefaultBodyLimitKind::Limit(limit)) => {
123-
Ok(http_body::Limited::new(self.into_body(), limit))
128+
Ok(self.map(|b| http_body::Limited::new(b, limit)))
124129
}
125-
None => Ok(http_body::Limited::new(self.into_body(), DEFAULT_LIMIT)),
130+
None => Ok(self.map(|b| http_body::Limited::new(b, DEFAULT_LIMIT))),
126131
}
127132
}
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+
}
128139
}
129140

130141
#[cfg(test)]

axum/CHANGELOG.md

Lines changed: 1 addition & 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
4344

4445
[#1368]: https://github.com/tokio-rs/axum/pull/1368
4546
[#1371]: https://github.com/tokio-rs/axum/pull/1371

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
}

0 commit comments

Comments
 (0)