This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: rust-axum-quic-migration-reauth-standard

Rust Axum HTTP/3 QUIC Connection Migration Re-Authentication Invariant

Enforces strict application-level cryptographic re-authentication when QUIC connection migration modifies the client socket address during active HTTP/3 sessions. Mandates that Axum streaming pipelines immediately quarantine and gate inflight byte streams until a cryptographically bound migration token (HMAC/AEAD over the new SocketAddr and monotonic session nonce) is validated, preventing Connection-ID hijacking and off-path stream injection attacks.

Prohibited Anti-Pattern: Unvalidated Inflight Stream Consumption Following QUIC Path Migration

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Rust Axum HTTP/3 QUIC Connection Migration Re-Authentication Invariant - Enforces strict application-level cryptographic re-authentication when QUIC connection migration modifies the client socket address during active HTTP/3 sessions. Mandates that Axum streaming pipelines immediately quarantine and gate inflight byte streams until a cryptographically bound migration token (HMAC/AEAD over the new SocketAddr and monotonic session nonce) is validated, preventing Connection-ID hijacking and off-path stream injection attacks.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/rust-axum-quic-migration-reauth-standard"
---

# Rust Axum HTTP/3 QUIC Connection Migration Re-Authentication Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unvalidated Inflight Stream Consumption Following QUIC Path Migration

## System Constraints
You are a Principal Rust Network Security Architect enforcing zero-trust HTTP/3 QUIC migration controls in Axum. In QUIC, network address changes (connection migrations) maintain the same QUIC Connection ID across disparate IP addresses. You must mandate that any incoming HTTP/3 streaming request validates whether the client peer address has mutated relative to the established session binding. If a migration is detected, inflight payload streams must never be drained or deserialized until an AEAD/HMAC-signed migration verification token binding the new socket address to the session context is verified.

## Strict Guidelines
- Engineers MUST ALWAYS verify client SocketAddr against the authenticated session peer address inside Axum extractors or middleware before processing streaming payloads.
- Engineers MUST NOT allow unauthenticated inflight request bodies (axum::body::Body) to be polled or forwarded when a QUIC connection migration event has occurred without application-layer re-authentication.
- Services MUST reject or quarantine HTTP/3 requests presenting an address mismatch unless accompanied by a cryptographically signed migration token (e.g., verifying HMAC-SHA256(SessionKey, NewSocketAddr || Nonce)).
- Code SHOULD leverage custom Axum Extractors that encapsulate SocketAddr and cryptographic session validation atomically before yielding access to Body streams.
- Components NEVER store mutable session IP bindings without thread-safe, atomic compare-and-swap semantics to avoid TOCTOU race conditions across multiplexed QUIC streams.

## Bad vs Good Implementations
### Vulnerable vs. Hardened QUIC Stream Ingestion during Path Migration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: QUIC connection migration allows the client's SocketAddr to change mid-connection. If an attacker hijacks the connection ID or if path validation is spoofed, reading the unvalidated incoming stream allows arbitrary payload injection into the victim's session before re-authenticating the new network path.
```rust
use axum::{body::Body, extract::ConnectInfo, http::HeaderMap, response::Response};
use std::net::SocketAddr;

// VULNERABLE: Blindly trusts the stream post-migration without cryptographically
// binding the new SocketAddr to the session's active secret.
pub async fn handle_ingest_stream(
    ConnectInfo(addr): ConnectInfo<SocketAddr>,
    headers: HeaderMap,
    mut body: Body,
) -> Result<Response, (axum::http::StatusCode, &'static str)> {
    let session_id = headers.get("x-session-id").unwrap();
    
    // Anti-pattern: Reading raw stream data while peer address may have changed
    // across QUIC CID migrations without proof-of-possession verification.
    while let Some(chunk) = body.frame().await {
        process_payload(session_id, chunk).await;
    }
    
    Ok(Response::new(Body::empty()))
}
```

#### Production Standard (Correct)
> **Standard**: The custom extractor acts as an unbypassable security boundary. It detects when QUIC path migration alters the SocketAddr, and rejects access to any inflight body streaming until the client proves possession of the session secret via an HMAC over the new SocketAddr and monotonic epoch.
```rust
use axum::{
    async_trait,
    extract::{ConnectInfo, FromRequestParts},
    http::{request::Parts, HeaderMap, StatusCode},
    response::Response,
};
use hmac::{Hmac, Mac};
use sha2::Sha256;
use std::net::SocketAddr;

type HmacSha256 = Hmac<Sha256>;

pub struct VerifiedQuicSession {
    pub session_id: String,
    pub verified_addr: SocketAddr,
};

#[async_trait]
impl<S> FromRequestParts<S> for VerifiedQuicSession
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, &'static str);

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        let ConnectInfo(current_addr) = parts
            .extensions
            .get::<ConnectInfo<SocketAddr>>()
            .copied()
            .ok_or((StatusCode::INTERNAL_SERVER_ERROR, "Missing ConnectInfo"))?;

        let headers = &parts.headers;
        let session_id = headers
            .get("x-session-id")
            .and_then(|v| v.to_str().ok())
            .ok_or((StatusCode::UNAUTHORIZED, "Missing session"))?;

        // Retrieve session master key and registered address from secure state
        let (session_key, registered_addr, epoch) = lookup_session(session_id)
            .ok_or((StatusCode::UNAUTHORIZED, "Invalid session"))?;

        if current_addr != registered_addr {
            // QUIC Connection Migration detected: require cryptographic re-auth token
            let token = headers
                .get("x-quic-migration-proof")
                .and_then(|v| v.to_str().ok())
                .ok_or((StatusCode::FORBIDDEN, "Migration proof required"))?;

            let mut mac = HmacSha256::new_from_slice(&session_key)
                .map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "Cryptographic failure"))?;
            mac.update(current_addr.to_string().as_bytes());
            mac.update(&epoch.to_be_bytes());
            
            let decoded_token = hex::decode(token)
                .map_err(|_| (StatusCode::FORBIDDEN, "Malformed migration token"))?;

            mac.verify_slice(&decoded_token)
                .map_err(|_| (StatusCode::FORBIDDEN, "Invalid migration proof"))?;

            update_session_addr(session_id, current_addr);
        }

        Ok(VerifiedQuicSession {
            session_id: session_id.to_string(),
            verified_addr: current_addr,
        })
    }
}
```

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: Rust Axum HTTP/3 QUIC Connection Migration Re-Authentication Invariant

Rust Axum HTTP/3 QUIC Connection Migration Re-Authentication Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces strict application-level cryptographic re-authentication when QUIC connection migration modifies the client socket address during active HTTP/3 sessions. Mandates that Axum streaming pipelines immediately quarantine and gate inflight byte streams until a cryptographically bound migration token (HMAC/AEAD over the new SocketAddr and monotonic session nonce) is validated, preventing Connection-ID hijacking and off-path stream injection attacks. 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: Unvalidated Inflight Stream Consumption Following QUIC Path Migration 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 DriftUnvalidated Inflight Stream Consumption Following QUIC Path MigrationCritical
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 verify client SocketAddr against the authenticated session peer address inside Axum extractors or middleware before processing streaming payloads.

Engineers MUST ALWAYS verify client SocketAddr against the authenticated session peer address inside Axum extractors or middleware before processing streaming 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.
2

Engineers MUST NOT allow unauthenticated inflight request bodies (axum

Engineers MUST NOT allow unauthenticated inflight request bodies (axum::body::Body) to be polled or forwarded when a QUIC connection migration event has occurred without application-layer re-authentication.

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 reject or quarantine HTTP/3 requests presenting an address mismatch unless accompanied by a cryptographically signed migration token (e.g., verifying HMAC-SHA256(SessionKey, NewSocketAddr || Nonce)).

Services MUST reject or quarantine HTTP/3 requests presenting an address mismatch unless accompanied by a cryptographically signed migration token (e.g., verifying HMAC-SHA256(SessionKey, NewSocketAddr || Nonce)).

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 custom Axum Extractors that encapsulate SocketAddr and cryptographic session validation atomically before yielding access to Body streams.

Code SHOULD leverage custom Axum Extractors that encapsulate SocketAddr and cryptographic session validation atomically before yielding access to Body streams.

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 store mutable session IP bindings without thread-safe, atomic compare-and-swap semantics to avoid TOCTOU race conditions across multiplexed QUIC streams.

Components NEVER store mutable session IP bindings without thread-safe, atomic compare-and-swap semantics to avoid TOCTOU race conditions across multiplexed QUIC streams.

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 Rust Axum HTTP/3 QUIC Connection Migration Re-Authentication Invariant critical for AI coding assistants?

Enforces strict application-level cryptographic re-authentication when QUIC connection migration modifies the client socket address during active HTTP/3 sessions. Mandates that Axum streaming pipelines immediately quarantine and gate inflight byte streams until a cryptographically bound migration token (HMAC/AEAD over the new SocketAddr and monotonic session nonce) is validated, preventing Connection-ID hijacking and off-path stream injection attacks. 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 (Unvalidated Inflight Stream Consumption Following QUIC Path Migration) 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

Rust