Ejemplo
axum 0.8.9: Configure request payload size limits in axum using DefaultBodyLimit to prevent automatic 413 Payload Too Large rejections on buffering extractors (Bytes, String, Json) at the default 2MB boundary, override limits per route or sub-router, and stream unbuffered raw requests without limits
Muestra verificada para cargo axum 0.8.9: Configure request payload size limits in axum using DefaultBodyLimit to prevent automatic 413 Payload Too Large…
sha256:adda974ec2d465cadc36ee9ef527ef98de16a608778e9bc8b0d096f4e2d504a3
Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido.
Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas.
MIT-0
Evidencia de ejecución
El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.
- Base de evidencia
- Contrato firmado aprobado
- Recibos de verificación
- 3
- Claves de firma que lo compilaron
- 2
Entorno declarado
rust linux x64 rust rust cargo
Entornos de las ejecuciones de verificación
| Entorno | Contrato | Etapas | Ejecución |
|---|---|---|---|
| rust 1 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · cargo@1 |
2026-08-16 |
| rust 1 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · cargo@1 |
2026-08-18 |
| rust 1 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | FAIL | compile:SKIPPED · contract:FAIL · load:SKIPPED · resolve:PASS CONTAINER_RUN · cargo@1rust:1-alpine@sha256:a10e64dd139b… |
2026-09-08 |
Caso
HOW- Objetivo
- Configure request payload size limits in axum using DefaultBodyLimit to prevent automatic 413 Payload Too Large rejections on buffering extractors (Bytes, String, Json) at the default 2MB boundary, override limits per route or sub-router, and stream unbuffered raw requests without limits
- Símbolos
-
- axum::extract::DefaultBodyLimit
- axum::extract::DefaultBodyLimit::max
- axum::extract::DefaultBodyLimit::disable
- axum::extract::Json
- axum::extract::Request
- axum::body::Bytes
- axum::Router::route
- axum::Router::layer
- axum::Router::nest
- Entorno
- rust
- Creado
- 2026-08-16T08:07:16Z
Contrato
- assert buffering extractors (Bytes, String, Json) enforce an implicit 2MB (2,097,152 bytes) limit by default
- assert a 2,097,152 byte payload succeeds with 200 OK on default routes
- assert a 2,097,153 byte payload fails with 413 PAYLOAD TOO LARGE on default routes
- assert malformed JSON exceeding 2MB returns 413 PAYLOAD TOO LARGE instead of 400 Bad Request or 422 Unprocessable Entity because body limit check precedes deserialization
- assert the 413 rejection returns Content-Type text/plain; charset=utf-8 with body 'Failed to buffer the request body: length limit exceeded'
- assert route-level DefaultBodyLimit::max overrides router-level limits to accept larger payloads
- assert route-level DefaultBodyLimit::disable allows arbitrary payload sizes without 413 rejection
- assert DefaultBodyLimit::max(0) accepts 0-byte bodies with 200 OK but rejects 1-byte bodies with 413
- assert unbuffered raw Request streaming extractors bypass DefaultBodyLimit without requiring disable()
- assert nested sub-routers enforce their own DefaultBodyLimit independently of parent router limits
Archivos
- Cargo.lock
- Cargo.toml
- NOTES.md
- csx.json
- src/lib.rs
Código fuente
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "atomic-waker"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
[[package]]
name = "axum"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
dependencies = [
"axum-core",
"bytes",
"form_urlencoded",
"futures-util",
"http",
"http-body",
"http-body-util",
"hyper",
"hyper-util",
"itoa",
"matchit",
"memchr",
"mime",
"percent-encoding",
"pin-project-lite",
"serde_core",
"serde_json",
"serde_path_to_error",
"serde_urlencoded",
"sync_wrapper",
"tokio",
"tower",
"tower-layer",
"tower-service",
"tracing",
]
[[package]]
name = "axum-core"
version = "0.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"
dependencies = [
"bytes",
"futures-core",
"http",
"http-body",
"http-body-util",
"mime",
"pin-project-lite",
"sync_wrapper",
"tower-layer",
"tower-service",
"tracing",
]
[[package]]
name = "bytes"
version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
[[package]]
name = "csx-sample-axum-body-limit"
version = "1.0.0"
dependencies = [
"axum",
"http-body-util",
"serde_json",
"tokio",
"tower",
]
[[package]]
name = "form_urlencoded"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
dependencies = [
"percent-encoding",
]
[[package]]
name = "futures-channel"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"
dependencies = [
"futures-core",
]
[[package]]
name = "futures-core"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
[[package]]
name = "futures-task"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
[[package]]
name = "futures-util"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
dependencies = [
"futures-core",
"futures-task",
"pin-project-lite",
"slab",
]
[[package]]
name = "http"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
dependencies = [
"bytes",
"itoa",
]
[[package]]
name = "http-body"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"
dependencies = [
"bytes",
"http",
]
[[package]]
name = "http-body-util"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c"
dependencies = [
"bytes",
"futures-core",
"http",
"http-body",
"pin-project-lite",
]
[[package]]
name = "httparse"
version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
[[package]]
name = "httpdate"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
[[package]]
name = "hyper"
version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d22053281f852e11534f5198498373cbb59295120a20771d90f7ed1897490a72"
dependencies = [
"atomic-waker",
"bytes",
"futures-channel",
"futures-core",
"http",
"http-body",
"httparse",
"httpdate",
"itoa",
"pin-project-lite",
"smallvec",
"tokio",
]
[[package]]
name = "hyper-util"
version = "0.1.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
dependencies = [
"bytes",
"http",
"http-body",
"hyper",
"pin-project-lite",
"tokio",
"tower-service",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "libc"
version = "0.2.189"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
[[package]]
name = "log"
version = "0.4.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
[[package]]
name = "matchit"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "mime"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
[[package]]
name = "mio"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427"
dependencies = [
"libc",
"wasi",
"windows-sys",
]
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "percent-encoding"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "pin-project-lite"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "ryu"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.151"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "serde_path_to_error"
version = "0.1.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
dependencies = [
"itoa",
"serde",
"serde_core",
]
[[package]]
name = "serde_urlencoded"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
dependencies = [
"form_urlencoded",
"itoa",
"ryu",
"serde",
]
[[package]]
name = "slab"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
[[package]]
name = "smallvec"
version = "1.15.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
[[package]]
name = "socket2"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "syn"
version = "3.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "sync_wrapper"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
[[package]]
name = "tokio"
version = "1.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed"
dependencies = [
"libc",
"mio",
"pin-project-lite",
"socket2",
"tokio-macros",
"windows-sys",
]
[[package]]
name = "tokio-macros"
version = "2.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tower"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
dependencies = [
"futures-core",
"futures-util",
"pin-project-lite",
"sync_wrapper",
"tokio",
"tower-layer",
"tower-service",
"tracing",
]
[[package]]
name = "tower-layer"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
[[package]]
name = "tower-service"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
[[package]]
name = "tracing"
version = "0.1.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
dependencies = [
"log",
"pin-project-lite",
"tracing-core",
]
[[package]]
name = "tracing-core"
version = "0.1.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
dependencies = [
"once_cell",
]
[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[package]
name = "csx-sample-axum-body-limit"
version = "1.0.0"
edition = "2021"
license = "MIT-0"
[dependencies]
axum = "0.8.9"
serde_json = "1.0.151"
tower = { version = "0.5.3", features = ["util"] }
tokio = { version = "1.53.1", features = ["rt", "macros"] }
http-body-util = "0.1.5"
# Notes on axum `DefaultBodyLimit` Configuration Trap
## 1. What `search_known_solution` answered
`search_known_solution` found published sample `sha256:ad2f9d5347cb52c3acc083de3c1608225248a42c41031bf843e1163d738b6e70` (testing `tower::ServiceExt::oneshot`, axum 0.8 `{id}` path captures, 400 vs 422 vs 415 error codes, and handler extractor argument order). This sample explores a distinct setting angle: `axum::extract::DefaultBodyLimit` configuration, route vs router scoping, streaming bypass, and body buffer rejection boundaries.
## 2. What a model would have written instead
A model would assume `axum::extract::Json` or `axum::body::Bytes` buffers payloads of arbitrary size in memory by default, or would add `tower_http::limit::RequestBodyLimitLayer` believing it raises payload limits (which fails because axum's built-in extractors still enforce their internal limit), or would expect payloads with invalid JSON syntax exceeding 2MB to return `400 Bad Request`.
## 3. How the wrong version fails
Loudly at runtime: any request payload exceeding 2,097,152 bytes (2MB) sent to a default route immediately receives HTTP `413 Payload Too Large` with response body `"Failed to buffer the request body: length limit exceeded"` before any handler code or JSON parser is reached.
{"case":{"caseId":"case:sha256:1b1ff16c6ee08a4db4bcf9616856f79d272864d89e1cee0d525de769821b15f1","contract":["assert buffering extractors (Bytes, String, Json) enforce an implicit 2MB (2,097,152 bytes) limit by default","assert a 2,097,152 byte payload succeeds with 200 OK on default routes","assert a 2,097,153 byte payload fails with 413 PAYLOAD TOO LARGE on default routes","assert malformed JSON exceeding 2MB returns 413 PAYLOAD TOO LARGE instead of 400 Bad Request or 422 Unprocessable Entity because body limit check precedes deserialization","assert the 413 rejection returns Content-Type text/plain; charset=utf-8 with body 'Failed to buffer the request body: length limit exceeded'","assert route-level DefaultBodyLimit::max overrides router-level limits to accept larger payloads","assert route-level DefaultBodyLimit::disable allows arbitrary payload sizes without 413 rejection","assert DefaultBodyLimit::max(0) accepts 0-byte bodies with 200 OK but rejects 1-byte bodies with 413","assert unbuffered raw Request streaming extractors bypass DefaultBodyLimit without requiring disable()","assert nested sub-routers enforce their own DefaultBodyLimit independently of parent router limits"],"goal":"Configure request payload size limits in axum using DefaultBodyLimit to prevent automatic 413 Payload Too Large rejections on buffering extractors (Bytes, String, Json) at the default 2MB boundary, override limits per route or sub-router, and stream unbuffered raw requests without limits","kind":"HOW","packages":["pkg:cargo/axum@0.8.9","pkg:cargo/tower@0.5.3","pkg:cargo/tokio@1.53.1","pkg:cargo/serde_json@1.0.151","pkg:cargo/http-body-util@0.1.5"],"schemaVersion":1,"symbols":["axum::extract::DefaultBodyLimit","axum::extract::DefaultBodyLimit::max","axum::extract::DefaultBodyLimit::disable","axum::extract::Json","axum::extract::Request","axum::body::Bytes","axum::Router::route","axum::Router::layer","axum::Router::nest"]},"contractCommand":["cargo","test","--offline"],"environment":{"arch":"x64","ecosystem":"cargo","executionContext":"rust","language":"rust","os":"linux","packageManager":"cargo","runtime":"rust","schemaVersion":1},"license":"MIT-0","packages":["pkg:cargo/axum@0.8.9","pkg:cargo/tower@0.5.3","pkg:cargo/tokio@1.53.1","pkg:cargo/serde_json@1.0.151","pkg:cargo/http-body-util@0.1.5"],"schemaVersion":1,"symbols":["axum::extract::DefaultBodyLimit","axum::extract::DefaultBodyLimit::max","axum::extract::DefaultBodyLimit::disable","axum::extract::Json","axum::extract::Request","axum::body::Bytes","axum::Router::route","axum::Router::layer","axum::Router::nest"],"verifierAdapter":"cargo@1"}
use axum::{
body::Body,
extract::{DefaultBodyLimit, Json, Request},
http::{header, Request as HttpRequest, StatusCode},
response::Response,
routing::post,
Router,
};
use http_body_util::BodyExt;
use serde_json::Value;
use tower::ServiceExt;
/// Creates an Axum router configured to demonstrate and prove DefaultBodyLimit behavior:
/// - Default 2MB limit on buffering extractors (Bytes, String, Json)
/// - Custom route-level overrides (higher limit, zero limit, disabled limit)
/// - Nested router limits
/// - Unbuffered streaming Request bypass
pub fn build_app() -> Router {
let sub = Router::new()
.route(
"/sub-upload",
post(|b: axum::body::Bytes| async move { format!("sub: {}", b.len()) }),
)
.layer(DefaultBodyLimit::max(300));
Router::new()
// Inherits default 2MB (2,097,152 bytes) limit
.route(
"/default-bytes",
post(|b: axum::body::Bytes| async move { format!("bytes: {}", b.len()) }),
)
.route(
"/default-string",
post(|s: String| async move { format!("string: {}", s.len()) }),
)
.route(
"/default-json",
post(|Json(v): Json<Value>| async move { format!("json: {}", v) }),
)
// Explicit route override to a higher limit (10 MB)
.route(
"/large-upload",
post(|b: axum::body::Bytes| async move { format!("large: {}", b.len()) })
.layer(DefaultBodyLimit::max(10 * 1024 * 1024)),
)
// Explicit route override with disabled limit
.route(
"/unlimited",
post(|b: axum::body::Bytes| async move { format!("unlimited: {}", b.len()) })
.layer(DefaultBodyLimit::disable()),
)
// Zero-byte limit: rejects any non-empty body
.route(
"/zero-limit",
post(|b: axum::body::Bytes| async move { format!("zero: {}", b.len()) })
.layer(DefaultBodyLimit::max(0)),
)
// Unbuffered raw Request extractor: bypasses DefaultBodyLimit
.route(
"/stream-raw",
post(|req: Request| async move {
let bytes = req.into_body().collect().await.unwrap().to_bytes();
format!("stream: {}", bytes.len())
}),
)
// Nest sub-router with its own 300-byte limit
.nest("/api", sub)
}
/// Helper to execute a single request against the router via ServiceExt::oneshot
pub async fn call(app: &Router, req: HttpRequest<Body>) -> (StatusCode, String, String) {
let res: Response = app.clone().oneshot(req).await.unwrap();
let status = res.status();
let content_type = res
.headers()
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.unwrap_or("")
.to_string();
let body_bytes = res.into_body().collect().await.unwrap().to_bytes();
let body_str = String::from_utf8(body_bytes.to_vec()).unwrap_or_default();
(status, content_type, body_str)
}
#[cfg(test)]
mod tests {
use super::*;
const TWO_MB: usize = 2 * 1024 * 1024; // 2,097,152 bytes
#[tokio::test]
async fn test_default_2mb_limit_boundary_bytes() {
let app = build_app();
// Exactly 2MB (2,097,152 bytes) succeeds
let req = HttpRequest::builder()
.uri("/default-bytes")
.method("POST")
.body(Body::from(vec![b'a'; TWO_MB]))
.unwrap();
let (status, _, body) = call(&app, req).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, format!("bytes: {TWO_MB}"));
// 2MB + 1 byte (2,097,153 bytes) is rejected with 413 Payload Too Large
let req = HttpRequest::builder()
.uri("/default-bytes")
.method("POST")
.body(Body::from(vec![b'a'; TWO_MB + 1]))
.unwrap();
let (status, content_type, body) = call(&app, req).await;
assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE);
assert_eq!(content_type, "text/plain; charset=utf-8");
assert_eq!(body, "Failed to buffer the request body: length limit exceeded");
}
#[tokio::test]
async fn test_default_2mb_limit_boundary_string() {
let app = build_app();
// Exactly 2MB UTF-8 string succeeds
let req = HttpRequest::builder()
.uri("/default-string")
.method("POST")
.body(Body::from(vec![b'x'; TWO_MB]))
.unwrap();
let (status, _, body) = call(&app, req).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, format!("string: {TWO_MB}"));
// 2MB + 1 byte UTF-8 string is rejected with 413
let req = HttpRequest::builder()
.uri("/default-string")
.method("POST")
.body(Body::from(vec![b'x'; TWO_MB + 1]))
.unwrap();
let (status, content_type, body) = call(&app, req).await;
assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE);
assert_eq!(content_type, "text/plain; charset=utf-8");
assert_eq!(body, "Failed to buffer the request body: length limit exceeded");
}
#[tokio::test]
async fn test_json_extractor_over_2mb_fails_with_413_not_400_or_422() {
let app = build_app();
// Syntactically malformed JSON that exceeds 2MB
// Naive models expect 400 Bad Request or 422 Unprocessable Entity,
// but Axum checks the body length limit BEFORE JSON parsing!
let malformed_large_json = vec![b'{'; TWO_MB + 100];
let req = HttpRequest::builder()
.uri("/default-json")
.method("POST")
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(malformed_large_json))
.unwrap();
let (status, content_type, body) = call(&app, req).await;
assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE);
assert_eq!(content_type, "text/plain; charset=utf-8");
assert_eq!(body, "Failed to buffer the request body: length limit exceeded");
}
#[tokio::test]
async fn test_route_level_limit_override_higher() {
let app = build_app();
// 5MB payload on /large-upload (configured with 10MB limit) succeeds
let five_mb = 5 * 1024 * 1024;
let req = HttpRequest::builder()
.uri("/large-upload")
.method("POST")
.body(Body::from(vec![b'c'; five_mb]))
.unwrap();
let (status, _, body) = call(&app, req).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, format!("large: {five_mb}"));
// 10MB + 1 byte on /large-upload fails with 413
let req = HttpRequest::builder()
.uri("/large-upload")
.method("POST")
.body(Body::from(vec![b'c'; 10 * 1024 * 1024 + 1]))
.unwrap();
let (status, _, body) = call(&app, req).await;
assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE);
assert_eq!(body, "Failed to buffer the request body: length limit exceeded");
}
#[tokio::test]
async fn test_route_level_limit_disabled() {
let app = build_app();
// 6MB payload on /unlimited (DefaultBodyLimit::disable()) succeeds
let six_mb = 6 * 1024 * 1024;
let req = HttpRequest::builder()
.uri("/unlimited")
.method("POST")
.body(Body::from(vec![b'd'; six_mb]))
.unwrap();
let (status, _, body) = call(&app, req).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, format!("unlimited: {six_mb}"));
}
#[tokio::test]
async fn test_zero_byte_limit() {
let app = build_app();
// Empty body (0 bytes) succeeds
let req = HttpRequest::builder()
.uri("/zero-limit")
.method("POST")
.body(Body::empty())
.unwrap();
let (status, _, body) = call(&app, req).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, "zero: 0");
// 1-byte body fails with 413
let req = HttpRequest::builder()
.uri("/zero-limit")
.method("POST")
.body(Body::from("x"))
.unwrap();
let (status, _, body) = call(&app, req).await;
assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE);
assert_eq!(body, "Failed to buffer the request body: length limit exceeded");
}
#[tokio::test]
async fn test_streaming_raw_request_bypasses_limit() {
let app = build_app();
// 4MB payload on /stream-raw (uses Request extractor instead of Bytes/Json)
// bypasses DefaultBodyLimit without requiring DefaultBodyLimit::disable()
let four_mb = 4 * 1024 * 1024;
let req = HttpRequest::builder()
.uri("/stream-raw")
.method("POST")
.body(Body::from(vec![b'e'; four_mb]))
.unwrap();
let (status, _, body) = call(&app, req).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, format!("stream: {four_mb}"));
}
#[tokio::test]
async fn test_nested_router_limit_isolation() {
let app = build_app();
// Nested route /api/sub-upload has a 300-byte limit
// 300 bytes succeeds
let req = HttpRequest::builder()
.uri("/api/sub-upload")
.method("POST")
.body(Body::from(vec![b'z'; 300]))
.unwrap();
let (status, _, body) = call(&app, req).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, "sub: 300");
// 301 bytes on nested route fails with 413
let req = HttpRequest::builder()
.uri("/api/sub-upload")
.method("POST")
.body(Body::from(vec![b'z'; 301]))
.unwrap();
let (status, _, body) = call(&app, req).await;
assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE);
assert_eq!(body, "Failed to buffer the request body: length limit exceeded");
// Meanwhile, root route /default-bytes still allows up to 2MB
let req = HttpRequest::builder()
.uri("/default-bytes")
.method("POST")
.body(Body::from(vec![b'z'; 1000]))
.unwrap();
let (status, _, body) = call(&app, req).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, "bytes: 1000");
}
}