This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: opentelemetry-w3c-baggage-boundary-limiting-standard

OpenTelemetry W3C Baggage Boundary Filtering & Amplification Guardrail

Enforces strict boundary filtering, size-capping, and character validation on OpenTelemetry W3C Baggage headers across ingress and egress boundaries. Mitigates downstream header amplification attacks (HTTP 431 exploits), sensitive context leakage, and delimiter injection vulnerabilities by mandating explicit key allowlists and hard memory limits.

Prohibited Anti-Pattern: Unbounded Propagation of Raw W3C Baggage Injecting Sensitive Context and Triggering HTTP 431 Denial-of-Service

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry W3C Baggage Boundary Filtering & Amplification Guardrail - Enforces strict boundary filtering, size-capping, and character validation on OpenTelemetry W3C Baggage headers across ingress and egress boundaries. Mitigates downstream header amplification attacks (HTTP 431 exploits), sensitive context leakage, and delimiter injection vulnerabilities by mandating explicit key allowlists and hard memory limits.
globs: src/**/tracing*.ts, src/**/telemetry*.ts, src/**/middleware/*.ts, src/**/instrumentation/*.ts, src/**/http-client*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-w3c-baggage-boundary-limiting-standard"
---

# OpenTelemetry W3C Baggage Boundary Filtering & Amplification Guardrail

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unbounded Propagation of Raw W3C Baggage Injecting Sensitive Context and Triggering HTTP 431 Denial-of-Service

## System Constraints
You are a Principal Software Architect enforcing the OpenTelemetry W3C Baggage Header Boundary Limiting & Injection Prevention Standard. You must reject any direct, unfiltered serialization or propagation of untrusted baggage across network and trust boundaries. Mandate strict allowlisting of baggage keys, limit total header size to prevent amplification attacks (HTTP 431), sanitize delimiters to avoid header injection, and isolate internal baggage from external egress calls.

## Strict Guidelines
- Engineers MUST ALWAYS enforce an explicit key allowlist for baggage entry acceptance and propagation across perimeter boundaries.
- Engineers MUST NOT blindly deserialize, append, or re-transmit external W3C baggage headers without size and character validation.
- Services MUST enforce strict length constraints: maximum 64 bytes per key, maximum 256 bytes per value, maximum 16 total baggage entries, and maximum 1024 bytes for the entire serialized baggage header.
- Code SHOULD validate that all baggage keys conform to the W3C token production regex (/^[a-zA-Z0-9!#$%&'*+-.^_`|~]+$/) and reject keys containing whitespace, CR, LF, commas, or semicolons.
- Components NEVER propagate internal infrastructure baggage (such as tenant-internal routing keys, auth identities, or debug flags) to unauthenticated or external third-party egress calls.

## Bad vs Good Implementations
### Insecure Baggage Injection vs. Bounded Allowlist Propagator

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The code extracts incoming W3C baggage without filtering or validation and allows unbounded user query parameters to be set as baggage entries. An attacker can transmit thousands of bytes of baggage or inject control characters, causing HTTP 431 (Request Header Fields Too Large) crashes in downstream microservices or leaking internal context.
```typescript
import { context, propagation, trace } from '@opentelemetry/api';
import { Request, Response, NextFunction } from 'express';

// ANTI-PATTERN: Blindly accepting any baggage from upstream and blindly passing
// raw user inputs into the active context without size checks or key boundaries.
export function unsafeBaggageMiddleware(req: Request, _res: Response, next: NextFunction): void {
  const rawBaggage = req.headers['baggage'];
  // Unbounded upstream baggage accepted without inspection
  const extractedContext = propagation.extract(context.active(), req.headers);

  // Arbitrary untrusted user input injected directly into baggage
  const userInputKey = req.query.debugKey as string;
  const userInputValue = req.query.debugValue as string;

  if (userInputKey && userInputValue) {
    // Vulnerable: CRLF injection, header amplification, PII/secret pollution
    const updatedBaggage = propagation.createBaggage({
      [userInputKey]: { value: userInputValue },
    });
    const activeWithBaggage = propagation.setBaggage(extractedContext, updatedBaggage);
    context.with(activeWithBaggage, next);
  } else {
    context.with(extractedContext, next);
  }
}
```

#### Production Standard (Correct)
> **Standard**: The bounded middleware enforces strict size limits (max 1024 bytes total header, max 8 entries, max 64 byte keys, max 256 byte values), uses a strict key allowlist, validates keys against the RFC-compliant token regex, strips control delimiters (CR, LF, comma, semicolon) to neutralize injection, and drops malicious payloads before downstream propagation.
```typescript
import { context, propagation, Baggage, BaggageEntry, Context, TextMapPropagator, TextMapSetter, TextMapGetter } from '@opentelemetry/api';
import { Request, Response, NextFunction } from 'express';

const ALLOWED_BAGGAGE_KEYS = new Set(['tenant_id', 'transaction_tier', 'client_version']);
const KEY_REGEX = /^[a-zA-Z0-9!#$%&'*+\-.^_`|~]{1,64}$/;
const MAX_VALUE_LENGTH = 256;
const MAX_TOTAL_ENTRIES = 8;
const MAX_TOTAL_HEADER_BYTES = 1024;

function sanitizeBaggageEntry(key: string, entry: BaggageEntry): BaggageEntry | null {
  if (!ALLOWED_BAGGAGE_KEYS.has(key)) return null;
  if (!KEY_REGEX.test(key)) return null;
  if (typeof entry.value !== 'string' || entry.value.length === 0 || entry.value.length > MAX_VALUE_LENGTH) {
    return null;
  }
  // Strip carriage returns, newlines, and unencoded control characters to prevent header injection
  if (/[\r\n;,]/.test(entry.value)) {
    return null;
  }
  return { value: entry.value, metadata: entry.metadata };
}

export function boundedBaggageMiddleware(req: Request, _res: Response, next: NextFunction): void {
  const rawHeader = req.headers['baggage'];
  if (typeof rawHeader === 'string' && Buffer.byteLength(rawHeader, 'utf8') > MAX_TOTAL_HEADER_BYTES) {
    // Drop oversized upstream baggage entirely to prevent amplification attacks
    delete req.headers['baggage'];
  }

  const extractedContext = propagation.extract(context.active(), req.headers);
  const currentBaggage = propagation.getBaggage(extractedContext);

  if (!currentBaggage) {
    return context.with(extractedContext, next);
  }

  let filteredBaggage = propagation.createBaggage();
  let entryCount = 0;

  for (const [key, entry] of currentBaggage.getAllEntries()) {
    if (entryCount >= MAX_TOTAL_ENTRIES) break;
    const sanitized = sanitizeBaggageEntry(key, entry);
    if (sanitized) {
      filteredBaggage = filteredBaggage.setEntry(key, sanitized);
      entryCount++;
    }
  }

  const cleanContext = propagation.setBaggage(extractedContext, filteredBaggage);
  context.with(cleanContext, next);
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenTelemetry W3C Baggage Boundary Filtering & Amplification Guardrail

OpenTelemetry W3C Baggage Boundary Filtering & Amplification Guardrail defines an industrial-grade behavioral standard for devops engineering. Enforces strict boundary filtering, size-capping, and character validation on OpenTelemetry W3C Baggage headers across ingress and egress boundaries. Mitigates downstream header amplification attacks (HTTP 431 exploits), sensitive context leakage, and delimiter injection vulnerabilities by mandating explicit key allowlists and hard memory limits. 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 Propagation of Raw W3C Baggage Injecting Sensitive Context and Triggering HTTP 431 Denial-of-Service 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 Propagation of Raw W3C Baggage Injecting Sensitive Context and Triggering HTTP 431 Denial-of-ServiceCritical
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 an explicit key allowlist for baggage entry acceptance and propagation across perimeter boundaries.

Engineers MUST ALWAYS enforce an explicit key allowlist for baggage entry acceptance and propagation across perimeter boundaries.

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 blindly deserialize, append, or re-transmit external W3C baggage headers without size and character validation.

Engineers MUST NOT blindly deserialize, append, or re-transmit external W3C baggage headers without size and character 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

Services MUST enforce strict length constraints

Services MUST enforce strict length constraints: maximum 64 bytes per key, maximum 256 bytes per value, maximum 16 total baggage entries, and maximum 1024 bytes for the entire serialized baggage header.

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 validate that all baggage keys conform to the W3C token production regex (/^[a-zA-Z0-9!#$%&'*+-.^_`|~]+$/) and reject keys containing whitespace, CR, LF, commas, or semicolons.

Code SHOULD validate that all baggage keys conform to the W3C token production regex (/^[a-zA-Z0-9!#$%&'*+-.^_`|~]+$/) and reject keys containing whitespace, CR, LF, commas, or semicolons.

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 propagate internal infrastructure baggage (such as tenant-internal routing keys, auth identities, or debug flags) to unauthenticated or external third-party egress calls.

Components NEVER propagate internal infrastructure baggage (such as tenant-internal routing keys, auth identities, or debug flags) to unauthenticated or external third-party egress calls.

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 Boundary Filtering & Amplification Guardrail critical for AI coding assistants?

Enforces strict boundary filtering, size-capping, and character validation on OpenTelemetry W3C Baggage headers across ingress and egress boundaries. Mitigates downstream header amplification attacks (HTTP 431 exploits), sensitive context leakage, and delimiter injection vulnerabilities by mandating explicit key allowlists and hard memory limits. 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 Propagation of Raw W3C Baggage Injecting Sensitive Context and Triggering HTTP 431 Denial-of-Service) 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