This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: axum-tower-body-framing-trailer-integrity-guardrail

Axum 0.8 Tower Service Body Framing and Chunked Trailer Integrity Guardrail

Enforces deterministic byte-budget limits and cryptographic checksum verifications across HTTP/2 and HTTP/3 chunked trailer streams within Tower middleware. Eliminates streaming DoS exploits, memory exhaustion from trailer bombs, and untrusted side-effect execution prior to payload integrity verification.

Prohibited Anti-Pattern: Unbounded Stream Ingestion and Post-Consumption Trailer Verification Permitting Streaming DoS and Integrity Bypass

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Tower Service Body Framing and Chunked Trailer Integrity Guardrail - Enforces deterministic byte-budget limits and cryptographic checksum verifications across HTTP/2 and HTTP/3 chunked trailer streams within Tower middleware. Eliminates streaming DoS exploits, memory exhaustion from trailer bombs, and untrusted side-effect execution prior to payload integrity verification.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-tower-body-framing-trailer-integrity-guardrail"
---

# Axum 0.8 Tower Service Body Framing and Chunked Trailer Integrity Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Stream Ingestion and Post-Consumption Trailer Verification Permitting Streaming DoS and Integrity Bypass

## System Constraints
You are a Principal Engineer enforcing Axum 0.8 Tower Service Body Framing and Chunked Trailer Integrity Guardrails. Mandate strict byte-budget bounding, incremental cryptographic digests, and deterministic trailer validation on all HTTP/2 and HTTP/3 streaming endpoints.

## Strict Guidelines
- Engineers MUST ALWAYS bound request bodies with deterministic byte-budgets using `http_body_util::Limited` or custom Tower frame inspectors before stream polling.
- Engineers MUST NOT rely on raw `axum::body::to_bytes` without an explicit size limit or stream directly into persistent state before trailer checksum validation.
- Code MUST incrementally compute streaming cryptographic digests (e.g., SHA-256) per incoming `Frame::Data` chunk rather than buffering the entire payload into RAM.
- Services MUST validate the final computed digest against the HTTP trailer `Frame::Trailers` (such as `x-checksum-sha256` or `digest`) before yielding downstream completion or committing database transactions.
- Components NEVER accept trailer headers exceeding strict maximum header size boundaries (e.g., 8 KiB) to prevent trailer-stuffing amplification attacks.
- Middleware MUST short-circuit and emit HTTP 413 (Payload Too Large) or HTTP 400 (Bad Request) immediately upon frame limit violation or checksum mismatch.

## Bad vs Good Implementations
### Securing Axum 0.8 Request Stream with Tower Service Body Framing and Trailer Checksum

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Consuming raw `Body::collect()` without `Limited` allows infinite streaming DoS (OOM). It fails to inspect individual `Frame` variants, ignores HTTP/2 and HTTP/3 trailers containing integrity hashes, and processes state before validating stream authenticity.
```rust
use axum::{body::Body, extract::Request, http::StatusCode, response::Response};
use http_body_util::BodyExt;

pub async fn insecure_upload_handler(req: Request<Body>) -> Result<Response, StatusCode> {
    // ANTI-PATTERN: Unbounded body collection into RAM.
    // An attacker sending an infinite HTTP/2 DATA stream causes OOM.
    // Trailers are either ignored or checked after full memory consumption.
    let body = req.into_body();
    let bytes = body.collect().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?.to_bytes();

    // Business logic executed with unverified payload integrity
    println!("Processed {} bytes", bytes.len());
    Ok(Response::new(Body::from("Upload accepted")))
}
```

#### Production Standard (Correct)
> **Standard**: Wraps the incoming body in `http_body_util::Limited` to strictly enforce a 10 MiB byte budget against DoS attacks. Incrementally processes stream frames (`Frame::Data` vs `Frame::Trailers`), updates a cryptographic SHA-256 digest in constant memory, and cryptographically verifies the trailer digest in constant time prior to acknowledging success.
```rust
use axum::{body::Body, extract::Request, http::{HeaderMap, StatusCode}, response::Response};
use http_body_util::{BodyExt, Limited};
use sha2::{Digest, Sha256};

const MAX_PAYLOAD_LIMIT: usize = 10 * 1024 * 1024; // 10 MiB limit

pub async fn secure_upload_handler(req: Request<Body>) -> Result<Response, StatusCode> {
    let (parts, body) = req.into_parts();
    let mut limited_body = Limited::new(body, MAX_PAYLOAD_LIMIT);
    let mut hasher = Sha256::new();
    let mut trailer_map: Option<HeaderMap> = None;

    while let Some(frame_result) = limited_body.frame().await {
        let frame = frame_result.map_err(|err| {
            if err.downcast_ref::<http_body_util::LengthLimitError>().is_some() {
                StatusCode::PAYLOAD_TOO_LARGE
            } else {
                StatusCode::BAD_REQUEST
            }
        })?;

        if let Some(chunk) = frame.data_ref() {
            hasher.update(chunk);
        } else if let Some(trailers) = frame.trailers_ref() {
            trailer_map = Some(trailers.clone());
        }
    }

    let expected_hash = trailer_map
        .as_ref()
        .and_then(|t| t.get("x-checksum-sha256"))
        .and_then(|val| val.to_str().ok())
        .ok_or(StatusCode::BAD_REQUEST)?;

    let actual_hash = hex::encode(hasher.finalize());
    if !subtle::ConstantTimeEq::ct_eq(actual_hash.as_bytes(), expected_hash.as_bytes()).into() {
        return Err(StatusCode::UNPROCESSABLE_ENTITY);
    }

    Ok(Response::new(Body::from("Payload verified and accepted")))
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Axum 0.8 Tower Service Body Framing and Chunked Trailer Integrity Guardrail

Axum 0.8 Tower Service Body Framing and Chunked Trailer Integrity Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic byte-budget limits and cryptographic checksum verifications across HTTP/2 and HTTP/3 chunked trailer streams within Tower middleware. Eliminates streaming DoS exploits, memory exhaustion from trailer bombs, and untrusted side-effect execution prior to payload integrity verification. 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 Stream Ingestion and Post-Consumption Trailer Verification Permitting Streaming DoS and Integrity Bypass 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 Stream Ingestion and Post-Consumption Trailer Verification Permitting Streaming DoS and Integrity BypassCritical
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 bound request bodies with deterministic byte-budgets using `http_body_util

Engineers MUST ALWAYS bound request bodies with deterministic byte-budgets using `http_body_util::Limited` or custom Tower frame inspectors before stream polling.

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 rely on raw `axum

Engineers MUST NOT rely on raw `axum::body::to_bytes` without an explicit size limit or stream directly into persistent state before trailer checksum validation.

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

Code MUST incrementally compute streaming cryptographic digests (e.g., SHA-256) per incoming `Frame

Code MUST incrementally compute streaming cryptographic digests (e.g., SHA-256) per incoming `Frame::Data` chunk rather than buffering the entire payload into RAM.

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

Services MUST validate the final computed digest against the HTTP trailer `Frame

Services MUST validate the final computed digest against the HTTP trailer `Frame::Trailers` (such as `x-checksum-sha256` or `digest`) before yielding downstream completion or committing database transactions.

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 accept trailer headers exceeding strict maximum header size boundaries (e.g., 8 KiB) to prevent trailer-stuffing amplification attacks.

Components NEVER accept trailer headers exceeding strict maximum header size boundaries (e.g., 8 KiB) to prevent trailer-stuffing amplification 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.
6

Middleware MUST short-circuit and emit HTTP 413 (Payload Too Large) or HTTP 400 (Bad Request) immediately upon frame limit violation or checksum mismatch.

Middleware MUST short-circuit and emit HTTP 413 (Payload Too Large) or HTTP 400 (Bad Request) immediately upon frame limit violation or checksum mismatch.

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 Tower Service Body Framing and Chunked Trailer Integrity Guardrail critical for AI coding assistants?

Enforces deterministic byte-budget limits and cryptographic checksum verifications across HTTP/2 and HTTP/3 chunked trailer streams within Tower middleware. Eliminates streaming DoS exploits, memory exhaustion from trailer bombs, and untrusted side-effect execution prior to payload integrity verification. 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 Stream Ingestion and Post-Consumption Trailer Verification Permitting Streaming DoS and Integrity Bypass) 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