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

OpenTelemetry W3C Baggage Ingress Sanitization and Size Limits

Enforces strict byte ceilings (maximum 8192 bytes total, 64 entries) and regex-based sensitive key/PII redaction on incoming W3C Baggage headers at edge and ingress proxies. Prevents distributed Denial of Service (DoS) from header-induced memory amplification and blocks accidental leakage of authorization tokens, passwords, and PII across downstream trace propagators.

Prohibited Anti-Pattern: Blind Downstream Propagation of Unbounded, Unsanitized W3C Baggage Context Headers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry W3C Baggage Ingress Sanitization and Size Limits - Enforces strict byte ceilings (maximum 8192 bytes total, 64 entries) and regex-based sensitive key/PII redaction on incoming W3C Baggage headers at edge and ingress proxies. Prevents distributed Denial of Service (DoS) from header-induced memory amplification and blocks accidental leakage of authorization tokens, passwords, and PII across downstream trace propagators.
globs: src/middleware/**/*.{ts,js}, src/telemetry/**/*.{ts,js}, src/gateway/**/*.{ts,js}, src/plugins/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/otel-baggage-sanitization-guardrail"
---

# OpenTelemetry W3C Baggage Ingress Sanitization and Size Limits

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Blind Downstream Propagation of Unbounded, Unsanitized W3C Baggage Context Headers

## System Constraints
You are a Principal Software Architect enforcing OpenTelemetry Baggage Payload Sanitization & Size Guardrails. Mandate invariants that strictly govern W3C Baggage context propagation at ingress boundaries: enforce total header payload size limits (<= 8192 bytes), cap individual member sizes, filter out blocked keys (auth tokens, passwords, session cookies, PII), validate percent-encoding, and ensure downstream baggage propagation preserves only verified metadata.

## Strict Guidelines
- Engineers MUST ALWAYS enforce total W3C Baggage byte limits (<= 8192 bytes total, <= 4096 bytes per key-value pair) at the ingress proxy or API edge before propagation.
- Engineers MUST NEVER propagate raw, unsanitized Baggage headers directly into downstream OpenTelemetry context propagation (`propagation.extract` or outbound HTTP headers).
- Services MUST drop or redact baggage entries matching sensitive key patterns (e.g., `/token|jwt|auth|secret|key|password|credential|cookie|ssn|email|phone/i`) and values containing high-entropy hashes or JWT structures (`/^[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}$/`).
- Services MUST enforce a hard maximum of 64 distinct baggage list-members per request in compliance with the W3C Baggage specification.
- Engineers MUST emit drop/redaction telemetry metrics (`otel.baggage.redacted_entries_total`, `otel.baggage.oversized_payloads_total`) to monitor ingress abuse or upstream misconfiguration without leaking payload contents in log messages.

## Bad vs Good Implementations
### Ingress Baggage Header Parser & Sanitizer Middleware

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accepting incoming Baggage headers without byte limits or key validation allows malicious actors to inject gigabytes of arbitrary distributed state, causing microservice memory exhaustion (Baggage travels downstream across every RPC hop) and propagating leaked bearer tokens into tracing spans and log drains.
```typescript
import { Request, Response, NextFunction } from 'express';
import { propagation, context } from '@opentelemetry/api';

export function otelContextMiddleware(req: Request, res: Response, next: NextFunction): void {
  // Anti-Pattern: Blindly propagating arbitrary untrusted baggage headers directly
  // into the OpenTelemetry context. Allows memory-exhaustion attacks, propagation of
  // raw Bearer tokens, JWTs, and arbitrary PII downstream across all internal microservices.
  const incomingBaggage = req.headers['baggage'];
  if (incomingBaggage) {
    const activeContext = propagation.extract(context.active(), req.headers);
    context.with(activeContext, () => {
      next();
    });
  } else {
    next();
  }
}
```

#### Production Standard (Correct)
> **Standard**: Implements strict RFC-compliant boundaries: enforces total byte ceiling (8192 bytes), entry count cap (64), blocked sensitive key names, individual value length ceilings, and regex-based JWT token detection prior to propagating into OpenTelemetry tracing context.
```typescript
import { Request, Response, NextFunction } from 'express';
import { propagation, context, baggageUtils, BaggageEntry } from '@opentelemetry/api';

const MAX_TOTAL_BAGGAGE_BYTES = 8192;
const MAX_MEMBER_COUNT = 64;
const MAX_VALUE_BYTES = 4096;
const BLOCKED_KEY_REGEX = /^(authorization|cookie|session|jwt|token|secret|password|bearer|auth|ssn|credit_card)$/i;
const JWT_VALUE_REGEX = /^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.[A-Za-z0-9-_.+/=]*$/;

export function otelContextMiddleware(req: Request, res: Response, next: NextFunction): void {
  const rawBaggage = req.headers['baggage'];
  const safeHeaders: Record<string, string | string[] | undefined> = { ...req.headers };

  if (typeof rawBaggage === 'string') {
    const totalBytes = Buffer.byteLength(rawBaggage, 'utf8');
    if (totalBytes > MAX_TOTAL_BAGGAGE_BYTES) {
      delete safeHeaders['baggage'];
      req.headers['baggage'] = undefined;
    } else {
      const sanitizedEntries: Record<string, BaggageEntry> = {};
      const parsed = baggageUtils.parseKeyPairsIntoRecord(rawBaggage);
      let count = 0;

      for (const [key, value] of Object.entries(parsed)) {
        if (count >= MAX_MEMBER_COUNT) break;
        if (BLOCKED_KEY_REGEX.test(key)) continue;
        if (Buffer.byteLength(value, 'utf8') > MAX_VALUE_BYTES) continue;
        if (JWT_VALUE_REGEX.test(value)) continue;

        sanitizedEntries[key] = { value };
        count++;
      }

      const serialized = baggageUtils.serializeKeyPairs(sanitizedEntries);
      safeHeaders['baggage'] = serialized.length > 0 ? serialized : undefined;
      req.headers['baggage'] = safeHeaders['baggage'];
    }
  }

  const extractedContext = propagation.extract(context.active(), safeHeaders);
  context.with(extractedContext, () => {
    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 Limits

OpenTelemetry W3C Baggage Ingress Sanitization and Size Limits defines an industrial-grade behavioral standard for devops engineering. Enforces strict byte ceilings (maximum 8192 bytes total, 64 entries) and regex-based sensitive key/PII redaction on incoming W3C Baggage headers at edge and ingress proxies. Prevents distributed Denial of Service (DoS) from header-induced memory amplification and blocks accidental leakage of authorization tokens, passwords, and PII across downstream trace propagators. 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: Blind Downstream Propagation of Unbounded, Unsanitized W3C Baggage Context Headers 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 DriftBlind Downstream Propagation of Unbounded, Unsanitized W3C Baggage Context HeadersCritical
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 total W3C Baggage byte limits (<= 8192 bytes total, <= 4096 bytes per key-value pair) at the ingress proxy or API edge before propagation.

Engineers MUST ALWAYS enforce total W3C Baggage byte limits (<= 8192 bytes total, <= 4096 bytes per key-value pair) at the ingress proxy or API edge before propagation.

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 NEVER propagate raw, unsanitized Baggage headers directly into downstream OpenTelemetry context propagation (`propagation.extract` or outbound HTTP headers).

Engineers MUST NEVER propagate raw, unsanitized Baggage headers directly into downstream OpenTelemetry context propagation (`propagation.extract` or outbound HTTP headers).

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 drop or redact baggage entries matching sensitive key patterns (e.g., `/token|jwt|auth|secret|key|password|credential|cookie|ssn|email|phone/i`) and values containing high-entropy hashes or JWT structures (`/^[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}$/`).

Services MUST drop or redact baggage entries matching sensitive key patterns (e.g., `/token|jwt|auth|secret|key|password|credential|cookie|ssn|email|phone/i`) and values containing high-entropy hashes or JWT structures (`/^[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}$/`).

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 enforce a hard maximum of 64 distinct baggage list-members per request in compliance with the W3C Baggage specification.

Services MUST enforce a hard maximum of 64 distinct baggage list-members per request in compliance with the W3C Baggage specification.

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 emit drop/redaction telemetry metrics (`otel.baggage.redacted_entries_total`, `otel.baggage.oversized_payloads_total`) to monitor ingress abuse or upstream misconfiguration without leaking payload contents in log messages.

Engineers MUST emit drop/redaction telemetry metrics (`otel.baggage.redacted_entries_total`, `otel.baggage.oversized_payloads_total`) to monitor ingress abuse or upstream misconfiguration without leaking payload contents in log messages.

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 Limits critical for AI coding assistants?

Enforces strict byte ceilings (maximum 8192 bytes total, 64 entries) and regex-based sensitive key/PII redaction on incoming W3C Baggage headers at edge and ingress proxies. Prevents distributed Denial of Service (DoS) from header-induced memory amplification and blocks accidental leakage of authorization tokens, passwords, and PII across downstream trace propagators. 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 (Blind Downstream Propagation of Unbounded, Unsanitized W3C Baggage Context Headers) 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