axum_core/extract/
default_body_limit.rs

1use self::private::DefaultBodyLimitService;
2use tower_layer::Layer;
3
4/// Layer for configuring the default request body limit.
5///
6/// For security reasons, [`Bytes`] will, by default, not accept bodies larger than 2MB. This also
7/// applies to extractors that uses [`Bytes`] internally such as `String`, [`Json`], and [`Form`].
8///
9/// This middleware provides ways to configure that.
10///
11/// Note that if an extractor consumes the body directly with [`Body::poll_frame`], or similar, the
12/// default limit is _not_ applied.
13///
14/// # Difference between `DefaultBodyLimit` and [`RequestBodyLimit`]
15///
16/// `DefaultBodyLimit` and [`RequestBodyLimit`] serve similar functions but in different ways.
17///
18/// `DefaultBodyLimit` is local in that it only applies to [`FromRequest`] implementations that
19/// explicitly apply it (or call another extractor that does). You can apply the limit with
20/// [`RequestExt::with_limited_body`] or [`RequestExt::into_limited_body`]
21///
22/// [`RequestBodyLimit`] is applied globally to all requests, regardless of which extractors are
23/// used or how the body is consumed.
24///
25/// # Example
26///
27/// ```
28/// use axum::{
29///     Router,
30///     routing::post,
31///     body::Body,
32///     extract::{Request, DefaultBodyLimit},
33/// };
34///
35/// let app = Router::new()
36///     .route("/", post(|request: Request| async {}))
37///     // change the default limit
38///     .layer(DefaultBodyLimit::max(1024));
39/// # let _: Router = app;
40/// ```
41///
42/// In general using `DefaultBodyLimit` is recommended but if you need to use third party
43/// extractors and want to make sure a limit is also applied there then [`RequestBodyLimit`] should
44/// be used.
45///
46/// # Different limits for different routes
47///
48/// `DefaultBodyLimit` can also be selectively applied to have different limits for different
49/// routes:
50///
51/// ```
52/// use axum::{
53///     Router,
54///     routing::post,
55///     body::Body,
56///     extract::{Request, DefaultBodyLimit},
57/// };
58///
59/// let app = Router::new()
60///     // this route has a different limit
61///     .route("/", post(|request: Request| async {}).layer(DefaultBodyLimit::max(1024)))
62///     // this route still has the default limit
63///     .route("/foo", post(|request: Request| async {}));
64/// # let _: Router = app;
65/// ```
66///
67/// [`Body::poll_frame`]: http_body::Body::poll_frame
68/// [`Bytes`]: bytes::Bytes
69/// [`Json`]: https://docs.rs/axum/0.8/axum/struct.Json.html
70/// [`Form`]: https://docs.rs/axum/0.8/axum/struct.Form.html
71/// [`FromRequest`]: crate::extract::FromRequest
72/// [`RequestBodyLimit`]: tower_http::limit::RequestBodyLimit
73/// [`RequestExt::with_limited_body`]: crate::RequestExt::with_limited_body
74/// [`RequestExt::into_limited_body`]: crate::RequestExt::into_limited_body
75#[derive(Debug, Clone, Copy)]
76#[must_use]
77pub struct DefaultBodyLimit {
78    kind: DefaultBodyLimitKind,
79}
80
81#[derive(Debug, Clone, Copy)]
82pub(crate) enum DefaultBodyLimitKind {
83    Disable,
84    Limit(usize),
85}
86
87impl DefaultBodyLimit {
88    /// Disable the default request body limit.
89    ///
90    /// This must be used to receive bodies larger than the default limit of 2MB using [`Bytes`] or
91    /// an extractor built on it such as `String`, [`Json`], [`Form`].
92    ///
93    /// Note that if you're accepting data from untrusted remotes it is recommend to add your own
94    /// limit such as [`tower_http::limit`].
95    ///
96    /// # Example
97    ///
98    /// ```
99    /// use axum::{
100    ///     Router,
101    ///     routing::get,
102    ///     body::{Bytes, Body},
103    ///     extract::DefaultBodyLimit,
104    /// };
105    /// use tower_http::limit::RequestBodyLimitLayer;
106    ///
107    /// let app: Router<()> = Router::new()
108    ///     .route("/", get(|body: Bytes| async {}))
109    ///     // Disable the default limit
110    ///     .layer(DefaultBodyLimit::disable())
111    ///     // Set a different limit
112    ///     .layer(RequestBodyLimitLayer::new(10 * 1000 * 1000));
113    /// ```
114    ///
115    /// [`Bytes`]: bytes::Bytes
116    /// [`Json`]: https://docs.rs/axum/0.8/axum/struct.Json.html
117    /// [`Form`]: https://docs.rs/axum/0.8/axum/struct.Form.html
118    pub const fn disable() -> Self {
119        Self {
120            kind: DefaultBodyLimitKind::Disable,
121        }
122    }
123
124    /// Set the default request body limit.
125    ///
126    /// By default the limit of request body sizes that [`Bytes::from_request`] (and other
127    /// extractors built on top of it such as `String`, [`Json`], and [`Form`]) is 2MB. This method
128    /// can be used to change that limit.
129    ///
130    /// # Example
131    ///
132    /// ```
133    /// use axum::{
134    ///     Router,
135    ///     routing::get,
136    ///     body::{Bytes, Body},
137    ///     extract::DefaultBodyLimit,
138    /// };
139    ///
140    /// let app: Router<()> = Router::new()
141    ///     .route("/", get(|body: Bytes| async {}))
142    ///     // Replace the default of 2MB with 1024 bytes.
143    ///     .layer(DefaultBodyLimit::max(1024));
144    /// ```
145    ///
146    /// [`Bytes::from_request`]: bytes::Bytes
147    /// [`Json`]: https://docs.rs/axum/0.8/axum/struct.Json.html
148    /// [`Form`]: https://docs.rs/axum/0.8/axum/struct.Form.html
149    pub const fn max(limit: usize) -> Self {
150        Self {
151            kind: DefaultBodyLimitKind::Limit(limit),
152        }
153    }
154}
155
156impl<S> Layer<S> for DefaultBodyLimit {
157    type Service = DefaultBodyLimitService<S>;
158
159    fn layer(&self, inner: S) -> Self::Service {
160        DefaultBodyLimitService {
161            inner,
162            kind: self.kind,
163        }
164    }
165}
166
167mod private {
168    use super::DefaultBodyLimitKind;
169    use http::Request;
170    use std::task::Context;
171    use tower_service::Service;
172
173    #[derive(Debug, Clone, Copy)]
174    pub struct DefaultBodyLimitService<S> {
175        pub(super) inner: S,
176        pub(super) kind: DefaultBodyLimitKind,
177    }
178
179    impl<B, S> Service<Request<B>> for DefaultBodyLimitService<S>
180    where
181        S: Service<Request<B>>,
182    {
183        type Response = S::Response;
184        type Error = S::Error;
185        type Future = S::Future;
186
187        #[inline]
188        fn poll_ready(&mut self, cx: &mut Context<'_>) -> std::task::Poll<Result<(), Self::Error>> {
189            self.inner.poll_ready(cx)
190        }
191
192        #[inline]
193        fn call(&mut self, mut req: Request<B>) -> Self::Future {
194            req.extensions_mut().insert(self.kind);
195            self.inner.call(req)
196        }
197    }
198}