FAQ - Help and questions

How do I limit the request body size in axum?

#axum#security#limits#uploadspublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Add DefaultBodyLimit::max(bytes) as a layer. Body extractors such as String, Json and Form then refuse larger bodies with 413 Payload Too Large. Set the limit per route when only one endpoint, such as an upload, needs a bigger value.

Checked with rustc 1.93.0, axum 0.8.9, tokio 1.54.1, tower 0.5.3, Windows 11; handlers called in-process with tower's oneshot

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

A server that accepts any size of body can be made to use all its memory by one client. DefaultBodyLimit sets the ceiling for the extractors that read the body.

src/main.rsrust
use axum::{body::{to_bytes, Body}, extract::DefaultBodyLimit, http::Request, routing::post, Router};
use tower::ServiceExt;

async fn upload(body: String) -> String { format!("received {} bytes", body.len()) }

#[tokio::main]
async fn main() {
    let app = Router::new().route("/upload", post(upload)).layer(DefaultBodyLimit::max(1024));
    for size in [1000usize, 1024, 1025, 5000] {
        let req = Request::post("/upload").body(Body::from("x".repeat(size))).unwrap();
        let res = app.clone().oneshot(req).await.unwrap();
        let status = res.status().as_u16();
        let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
        println!("{size} bytes -> {status} {}", String::from_utf8_lossy(&body));
    }
}
text
1000 bytes -> 200 received 1000 bytes
1024 bytes -> 200 received 1024 bytes
1025 bytes -> 413 Failed to buffer the request body: length limit exceeded
5000 bytes -> 413 Failed to buffer the request body: length limit exceeded

A body of exactly 1024 bytes passed and one byte more was refused with 413. In the axum documentation the default limit for Multipart is 2 MB; set your own limit explicitly so it is visible in the code.

Common mistakes#

  • Raising the limit for the whole router because one upload route needs it. Apply a bigger DefaultBodyLimit to that route only.
  • Checking only the Content-Length header yourself. Clients can send a wrong value or none (chunked bodies); the extractor counts the bytes it really reads.

Does the limit apply to file uploads?#

Yes. See the thread on uploads with Multipart, where a 20,000 byte file is refused under a 10,000 byte limit.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet