This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: otel-baggage-sanitization-sizing-guardrail

OpenTelemetry W3C Baggage Ingress Sanitization and Size Bounding Protocol

Mandates strict byte-length ceilings, key-cardinality limits, and allowlist-based redaction for incoming W3C Baggage headers at ingress proxies. Prevents memory-exhaustion header-stuffing DoS attacks and stops sensitive credential or PII leakage across zero-trust network boundaries.

Prohibited Anti-Pattern: Unbounded, Transparent Ingress Baggage Propagation and Deserialization

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry W3C Baggage Ingress Sanitization and Size Bounding Protocol - Mandates strict byte-length ceilings, key-cardinality limits, and allowlist-based redaction for incoming W3C Baggage headers at ingress proxies. Prevents memory-exhaustion header-stuffing DoS attacks and stops sensitive credential or PII leakage across zero-trust network boundaries.
globs: src/middleware/**/*.{ts,js,go,py}, src/telemetry/**/*.{ts,js,go,py}, src/gateway/**/*.{ts,js,go,py}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/otel-baggage-sanitization-sizing-guardrail"
---

# OpenTelemetry W3C Baggage Ingress Sanitization and Size Bounding Protocol

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unbounded, Transparent Ingress Baggage Propagation and Deserialization

## System Constraints
You are a Principal Software Architect enforcing zero-trust OpenTelemetry tracing security. You must ensure all W3C Baggage headers arriving at ingress gateways are strictly length-capped, member-limited, character-validated, and allowlist-filtered prior to context extraction and downstream propagation to thwart header-stuffing DoS vectors and PII exfiltration.

## Strict Guidelines
- Services MUST enforce a strict byte-size ceiling on raw W3C baggage headers (maximum 8192 bytes aggregate total, maximum 4096 bytes per member) before parsing.
- Ingress proxies MUST reject or drop incoming baggage with HTTP 431 if aggregate header length exceeds configured safety limits, and MUST NOT allocate memory dynamically for unbounded baggage values.
- Engineers MUST NOT allow default, transparent pass-through of external W3C baggage across zero-trust perimeter boundaries without explicit key allowlisting.
- Components MUST filter baggage members against an immutable allowlist of authorized non-sensitive operational keys (e.g., tenant_id, request_origin) before extracting into OpenTelemetry context.
- Engineers MUST NEVER propagate credentials, authorization tokens, session cookies, personally identifiable information (PII), or internal network topology via baggage.
- Services MUST validate baggage key-value syntax against RFC 7230 token specifications and drop invalid percent-encoded entries without throwing unhandled exceptions.
- Downstream HTTP clients MUST limit outbound baggage member count to prevent baggage header bloat cascades across service meshes.

## Bad vs Good Implementations
### Ingress OpenTelemetry Baggage Sanitization & Sizing Middleware

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly extracting baggage from untrusted incoming headers without size checks or key filtering allows attackers to cause HTTP 431 / memory exhaustion crashes downstream. It also allows untrusted callers to inject arbitrary baggage that leaks across internal microservices.
```typescript
import { Request, Response, NextFunction } from 'express';
import { context, propagation } from '@opentelemetry/api';

// ANTI-PATTERN: Blindly extracts untrusted, unbounded baggage into active context.
// Vulnerable to memory-exhaustion DoS (header stuffing) and PII/token propagation.
export function telemetryMiddleware(req: Request, res: Response, next: NextFunction): void {
  const activeContext = propagation.extract(context.active(), req.headers);
  context.with(activeContext, () => {
    next();
  });
}
```

#### Production Standard (Correct)
> **Standard**: Bounds total header byte size to 8192 bytes, enforces a maximum of 32 members, validates key tokens against RFC syntax, and strips all baggage members that are not explicitly present in the immutable allowlist before extraction.
```typescript
import { Request, Response, NextFunction } from 'express';
import { context, propagation, baggageUtils } from '@opentelemetry/api';

const MAX_BAGGAGE_BYTES = 8192;
const MAX_BAGGAGE_MEMBERS = 32;
const ALLOWED_BAGGAGE_KEYS = new Set(['tenant_id', 'client_version', 'trace_origin']);
const TOKEN_KEY_REGEX = /^[!#$%&'*+\-.^_`|~0-9a-zA-Z]+$/;

export function secureTelemetryMiddleware(req: Request, res: Response, next: NextFunction): void {
  const rawBaggage = req.headers['baggage'];
  
  if (typeof rawBaggage === 'string') {
    if (Buffer.byteLength(rawBaggage, 'utf8') > MAX_BAGGAGE_BYTES) {
      res.status(431).json({ error: 'Request Header Fields Too Large: Baggage exceeds size limit' });
      return;
    }

    const rawEntries = rawBaggage.split(',');
    if (rawEntries.length > MAX_BAGGAGE_MEMBERS) {
      res.status(431).json({ error: 'Request Header Fields Too Large: Too many baggage members' });
      return;
    }

    // Filter and reconstruct sanitized baggage containing only allowlisted keys
    const sanitizedEntries: string[] = [];
    for (const entry of rawEntries) {
      const [rawKey, ...valParts] = entry.split('=');
      const key = rawKey?.trim();
      const val = valParts.join('=').trim();

      if (key && TOKEN_KEY_REGEX.test(key) && ALLOWED_BAGGAGE_KEYS.has(key)) {
        sanitizedEntries.push(`${key}=${val}`);
      }
    }

    req.headers['baggage'] = sanitizedEntries.length > 0 ? sanitizedEntries.join(',') : undefined;
  } else if (Array.isArray(rawBaggage)) {
    delete req.headers['baggage']; // Reject ambiguous multiple header lines
  }

  const sanitizedContext = propagation.extract(context.active(), req.headers);
  context.with(sanitizedContext, () => {
    next();
  });
}
```

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: OpenTelemetry W3C Baggage Ingress Sanitization and Size Bounding Protocol

OpenTelemetry W3C Baggage Ingress Sanitization and Size Bounding Protocol defines an industrial-grade behavioral standard for devops engineering. Mandates strict byte-length ceilings, key-cardinality limits, and allowlist-based redaction for incoming W3C Baggage headers at ingress proxies. Prevents memory-exhaustion header-stuffing DoS attacks and stops sensitive credential or PII leakage across zero-trust network boundaries. 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, Transparent Ingress Baggage Propagation and Deserialization 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, Transparent Ingress Baggage Propagation and DeserializationCritical
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

Services MUST enforce a strict byte-size ceiling on raw W3C baggage headers (maximum 8192 bytes aggregate total, maximum 4096 bytes per member) before parsing.

Services MUST enforce a strict byte-size ceiling on raw W3C baggage headers (maximum 8192 bytes aggregate total, maximum 4096 bytes per member) before parsing.

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

Ingress proxies MUST reject or drop incoming baggage with HTTP 431 if aggregate header length exceeds configured safety limits, and MUST NOT allocate memory dynamically for unbounded baggage values.

Ingress proxies MUST reject or drop incoming baggage with HTTP 431 if aggregate header length exceeds configured safety limits, and MUST NOT allocate memory dynamically for unbounded baggage values.

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

Engineers MUST NOT allow default, transparent pass-through of external W3C baggage across zero-trust perimeter boundaries without explicit key allowlisting.

Engineers MUST NOT allow default, transparent pass-through of external W3C baggage across zero-trust perimeter boundaries without explicit key allowlisting.

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

Components MUST filter baggage members against an immutable allowlist of authorized non-sensitive operational keys (e.g., tenant_id, request_origin) before extracting into OpenTelemetry context.

Components MUST filter baggage members against an immutable allowlist of authorized non-sensitive operational keys (e.g., tenant_id, request_origin) before extracting into OpenTelemetry context.

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

Engineers MUST NEVER propagate credentials, authorization tokens, session cookies, personally identifiable information (PII), or internal network topology via baggage.

Engineers MUST NEVER propagate credentials, authorization tokens, session cookies, personally identifiable information (PII), or internal network topology via baggage.

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

Services MUST validate baggage key-value syntax against RFC 7230 token specifications and drop invalid percent-encoded entries without throwing unhandled exceptions.

Services MUST validate baggage key-value syntax against RFC 7230 token specifications and drop invalid percent-encoded entries without throwing unhandled exceptions.

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.
7

Downstream HTTP clients MUST limit outbound baggage member count to prevent baggage header bloat cascades across service meshes.

Downstream HTTP clients MUST limit outbound baggage member count to prevent baggage header bloat cascades across service meshes.

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 OpenTelemetry W3C Baggage Ingress Sanitization and Size Bounding Protocol critical for AI coding assistants?

Mandates strict byte-length ceilings, key-cardinality limits, and allowlist-based redaction for incoming W3C Baggage headers at ingress proxies. Prevents memory-exhaustion header-stuffing DoS attacks and stops sensitive credential or PII leakage across zero-trust network boundaries. 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, Transparent Ingress Baggage Propagation and Deserialization) 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

OpenTelemetry