Fix Unrestricted Resource Consumption in Axum
Unrestricted Resource Consumption (CWE-400) in Axum typically manifests as memory exhaustion (OOM) or thread starvation. Because Axum extractors like 'String' or 'Bytes' buffer the entire request body into RAM, an attacker can send a multi-gigabyte payload to crash the service. By default, Axum provides a 2MB limit, but developers frequently disable it for 'file uploads' without implementing granular constraints, opening the door for DoS.
The Vulnerable Pattern
use ax_um::{routing::post, Router, extract::DefaultBodyLimit};// VULNERABILITY: Disabling the default limit globally without a replacement // allows an attacker to flood the heap until the OOM killer strikes. async fn vulnerable_handler(body: String) -> &‘static str { “Data received” }
pub fn app() -> Router { Router::new() .route(“/upload”, post(vulnerable_handler)) .layer(DefaultBodyLimit::disable()) }
The Secure Implementation
The fix involves a multi-layered defense: 1. Re-enable or decrease the 'DefaultBodyLimit' to a sane value for your business logic. 2. Use 'RequestBodyLimitLayer' from tower-http to enforce hard limits at the middleware level before the extractor even attempts to buffer the data. 3. Implement 'TimeoutLayer' to ensure that slow-post attacks cannot hold connections open indefinitely, consuming file descriptors and worker threads. Always prefer streaming extractors (BodyStream) for large files instead of buffering them into a String or Vec
use ax_um::{routing::post, Router, extract::DefaultBodyLimit}; use tower_http::{limit::RequestBodyLimitLayer, timeout::TimeoutLayer}; use std::time::Duration;async fn secure_handler(body: String) -> &‘static str { “Data received safely” }
pub fn app() -> Router { Router::new() .route(“/upload”, post(secure_handler)) // 1. Set a strict global limit (e.g., 1MB) .layer(DefaultBodyLimit::max(1024 * 1024)) // 2. Use RequestBodyLimitLayer for specific route granular control if needed .layer(RequestBodyLimitLayer::new(1024 * 1024)) // 3. Add a timeout to prevent Slowloris-style resource hanging .layer(TimeoutLayer::new(Duration::from_secs(10))) }
Your Axum API
might be exposed to Unrestricted Resource Consumption
74% of Axum apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.