This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: axum-stream-decompression-bounded-buffer-limits

Axum 0.8 Decompression Zip-Bomb & Bounded Buffer Guardrail

Enforces strict dual-stage bounded limits on wire transfers and decompressed streams in Axum 0.8 applications. Prevents catastrophic memory exhaustion and worker thread panics caused by decompression bombs (zip-bombs) and unmetered HTTP chunked transfer encodings.

Prohibited Anti-Pattern: Unbounded Decompressed Body Collection and Misordered Tower Layers Permitting Zip-Bomb OOM

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Decompression Zip-Bomb & Bounded Buffer Guardrail - Enforces strict dual-stage bounded limits on wire transfers and decompressed streams in Axum 0.8 applications. Prevents catastrophic memory exhaustion and worker thread panics caused by decompression bombs (zip-bombs) and unmetered HTTP chunked transfer encodings.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-stream-decompression-bounded-buffer-limits"
---

# Axum 0.8 Decompression Zip-Bomb & Bounded Buffer Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Decompressed Body Collection and Misordered Tower Layers Permitting Zip-Bomb OOM

## System Constraints
You are a Principal Rust Architect enforcing Axum 0.8 stream decompression and bounded memory safety standards. Mandate strict memory limits on both compressed wire frames and post-decompression streams. Reject unbounded in-memory aggregations, improper Tower layer ordering, and naive body conversions that expose services to decompression bombs and memory exhaustion attacks.

## Strict Guidelines
- Engineers MUST ALWAYS enforce explicit bounded limits on decompressed request bodies using `axum::body::to_bytes(body, MAX_DECOMPRESSED_BYTES)` rather than reading decompressed streams to completion.
- Engineers MUST NOT place `RequestBodyLimitLayer` solely before `RequestDecompressionLayer`, as raw wire byte limits do not constrain the decompressed payload volume.
- Services MUST implement two-tier limits: a strict wire-level transfer limit (e.g., 2MB) and an absolute ceiling on the post-decompression payload (e.g., 10MB) to mitigate expansion factor attacks.
- Code SHOULD leverage `http_body_util::Limited` or Axum's `DefaultBodyLimit::disable()` alongside granular per-route extractor limits when processing streamable payloads.
- Components NEVER collect unmetered chunked incoming streams directly into `Vec<u8>` or `String` without validating total consumed byte counts against a defined upper limit.

## Bad vs Good Implementations
### Vulnerable Decompression Pipeline vs. Two-Tier Bounded Stream Decompression

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The RequestBodyLimitLayer is applied to the raw wire body before decompression, allowing a tiny, highly compressed payload (e.g., 1MB gzip bomb) to pass the layer limit. The handler then collects the decompressed stream using usize::MAX as the limit, allowing unrestricted memory allocation and crashing the microservice via OOM.
```rust
use axum::{routing::post, Router, extract::Request, body::Body};
use tower_http::decompression::RequestDecompressionLayer;
use tower_http::limit::RequestBodyLimitLayer;

// VULNERABILITY: Wire limit is 2MB, but RequestDecompressionLayer executes
// AFTER the limit check (or inside the handler without bounds). A 1.5MB gzip payload
// can decompress into multiple gigabytes, causing an immediate OOM crash.
pub fn insecure_app() -> Router {
    Router::new()
        .route("/upload", post(insecure_handler))
        .layer(RequestDecompressionLayer::new())
        .layer(RequestBodyLimitLayer::new(2 * 1024 * 1024)) // Only bounds raw wire bytes!
}

async fn insecure_handler(request: Request<Body>) -> &'static str {
    // In Axum 0.8, passing usize::MAX removes backpressure and decompressed safeguards
    let body = request.into_body();
    let bytes = axum::body::to_bytes(body, usize::MAX).await.unwrap();
    println!("Payload size: {}", bytes.len());
    "OK"
}
```

#### Production Standard (Correct)
> **Standard**: The good pattern enforces defense-in-depth: network-level transfer is limited to 2MB by RequestBodyLimitLayer, while the post-decompression stream is strictly constrained to 8MB via axum::body::to_bytes(body, MAX_DECOMPRESSED_BYTES). Any zip-bomb attempting to expand beyond 8MB terminates immediately with HTTP 413.
```rust
use axum::{
    body::Body,
    extract::Request,
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::post,
    Router,
};
use tower_http::decompression::RequestDecompressionLayer;
use tower_http::limit::RequestBodyLimitLayer;

const MAX_WIRE_BYTES: usize = 2 * 1024 * 1024;        // 2 MB raw network payload
const MAX_DECOMPRESSED_BYTES: usize = 8 * 1024 * 1024; // 8 MB decompressed ceiling

pub fn secure_app() -> Router {
    Router::new()
        .route("/upload", post(secure_handler))
        // Decompress first, but enforce post-decompression size limit in handler
        .layer(RequestDecompressionLayer::new())
        // Outer layer limits raw ingress network transfer
        .layer(RequestBodyLimitLayer::new(MAX_WIRE_BYTES))
}

async fn secure_handler(request: Request<Body>) -> Result<&'static str, Response> {
    let body = request.into_body();
    
    // Invariant: Enforce explicit post-decompression buffer limit
    let bytes = axum::body::to_bytes(body, MAX_DECOMPRESSED_BYTES)
        .await
        .map_err(|_| {
            (StatusCode::PAYLOAD_TOO_LARGE, "Decompressed payload exceeds buffer limit").into_response()
        })?;

    // Safe to process strictly bounded bytes
    println!("Decompressed safe size: {} bytes", bytes.len());
    Ok("OK")
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Axum 0.8 Decompression Zip-Bomb & Bounded Buffer Guardrail

Axum 0.8 Decompression Zip-Bomb & Bounded Buffer Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict dual-stage bounded limits on wire transfers and decompressed streams in Axum 0.8 applications. Prevents catastrophic memory exhaustion and worker thread panics caused by decompression bombs (zip-bombs) and unmetered HTTP chunked transfer encodings. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Unbounded Decompressed Body Collection and Misordered Tower Layers Permitting Zip-Bomb OOM Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftUnbounded Decompressed Body Collection and Misordered Tower Layers Permitting Zip-Bomb OOMCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS enforce explicit bounded limits on decompressed request bodies using `axum

Engineers MUST ALWAYS enforce explicit bounded limits on decompressed request bodies using `axum::body::to_bytes(body, MAX_DECOMPRESSED_BYTES)` rather than reading decompressed streams to completion.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT place `RequestBodyLimitLayer` solely before `RequestDecompressionLayer`, as raw wire byte limits do not constrain the decompressed payload volume.

Engineers MUST NOT place `RequestBodyLimitLayer` solely before `RequestDecompressionLayer`, as raw wire byte limits do not constrain the decompressed payload volume.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Services MUST implement two-tier limits

Services MUST implement two-tier limits: a strict wire-level transfer limit (e.g., 2MB) and an absolute ceiling on the post-decompression payload (e.g., 10MB) to mitigate expansion factor attacks.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Code SHOULD leverage `http_body_util

Code SHOULD leverage `http_body_util::Limited` or Axum's `DefaultBodyLimit::disable()` alongside granular per-route extractor limits when processing streamable payloads.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER collect unmetered chunked incoming streams directly into `Vec<u8>` or `String` without validating total consumed byte counts against a defined upper limit.

Components NEVER collect unmetered chunked incoming streams directly into `Vec<u8>` or `String` without validating total consumed byte counts against a defined upper limit.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Axum 0.8 Decompression Zip-Bomb & Bounded Buffer Guardrail critical for AI coding assistants?

Enforces strict dual-stage bounded limits on wire transfers and decompressed streams in Axum 0.8 applications. Prevents catastrophic memory exhaustion and worker thread panics caused by decompression bombs (zip-bombs) and unmetered HTTP chunked transfer encodings. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Unbounded Decompressed Body Collection and Misordered Tower Layers Permitting Zip-Bomb OOM) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

Axum