Skip to main content

Module body_limiter

Module body_limiter 

Source
Expand description

Request body size limiter layer

Rejects incoming requests whose advertised Content-Length exceeds a configured maximum, before the body is read. The check is O(1) and does not buffer anything, so it preserves streaming for legitimate requests.

§Scope

The limit is enforced from the Content-Length header. A chunked request that omits Content-Length is not capped by this layer.

§Hard guarantee on chunked bodies

For a hard cap that also covers requests without a Content-Length (chunked / streamed uploads), stack this layer on top of the re-exported RequestBodyLimitLayer. BodyLimiterLayer rejects the common honest-client case early with a JSON 413, while RequestBodyLimitLayer wraps the body and enforces the same limit as it is read, backstopping the chunked case (with tower-http’s plain 413):

use api_tools::server::axum::layers::body_limiter::{
    BodyLimiterConfig, BodyLimiterLayer, RequestBodyLimitLayer,
};
use tower::ServiceBuilder;

const MAX: usize = 2 * 1024 * 1024; // 2 MiB

let _layers = ServiceBuilder::new()
    .layer(BodyLimiterLayer::new(&BodyLimiterConfig { body_max_size: MAX }))
    .layer(RequestBodyLimitLayer::new(MAX));

Structs§

BodyLimiterConfig
Configuration for the BodyLimiterLayer
BodyLimiterLayer
BodyLimiterMiddleware
RequestBodyLimitLayer
Layer that applies the RequestBodyLimit middleware that intercepts requests with body lengths greater than the configured limit and converts them into 413 Payload Too Large responses.