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

OpenTelemetry W3C Baggage Ingress Sanitization and Boundary Defense

Ingress reverse proxies and edge gateways must strictly validate, filter, and sanitize incoming W3C baggage headers prior to propagating trace context downstream. Unsanitized baggage propagation allows external attackers to inject arbitrary metadata, causing log forgery, sensitive context poisoning, and high-cardinality metric denial of service across distributed telemetry backends.

Prohibited Anti-Pattern: Blind Downstream Propagation of Untrusted External W3C Baggage Headers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry W3C Baggage Ingress Sanitization and Boundary Defense - Ingress reverse proxies and edge gateways must strictly validate, filter, and sanitize incoming W3C baggage headers prior to propagating trace context downstream. Unsanitized baggage propagation allows external attackers to inject arbitrary metadata, causing log forgery, sensitive context poisoning, and high-cardinality metric denial of service across distributed telemetry backends.
globs: src/middleware/**/*.{ts,js}, src/gateway/**/*.{ts,js}, src/tracing/**/*.{ts,js}, src/ingress/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/otel-w3c-baggage-ingress-sanitization"
---

# OpenTelemetry W3C Baggage Ingress Sanitization and Boundary Defense

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Blind Downstream Propagation of Untrusted External W3C Baggage Headers

## System Constraints
You are a Principal Software Architect enforcing enterprise-grade OpenTelemetry boundary sanitization. External clients must never have unmediated control over propagated distributed baggage. Enforce strict allowlists, RFC-compliant format enforcement, character validation, and header stripping at the outer edge before W3C context is extracted into downstream spans.

## Strict Guidelines
- Edge middleware MUST NEVER extract and forward raw W3C `baggage` headers without validation against an explicit allowlist of authorized keys.
- Engineers MUST strip all unauthenticated external `baggage` headers at edge ingress proxies and initialize a fresh, empty W3C baggage context.
- Allowed baggage keys MUST match strict alphanumeric patterns (e.g., `^[a-z0-9_.-]{1,64}$`) and values MUST be URL-decoded and validated against injection payloads (CRLF, terminal escapes, format strings).
- Baggage entry limits MUST enforce strict payload boundaries: maximum 32 key-value pairs, individual value length <= 256 bytes, and overall header length <= 8192 bytes.
- Sensitive tokens, PII, session identifiers, and authorization credentials MUST NEVER be stored in or propagated via W3C baggage headers.
- Engineers MUST configure the OpenTelemetry `W3CBaggagePropagator` with a custom getter/sanitizer or mutate the carrier headers prior to invoking `propagation.extract()`.

## Bad vs Good Implementations
### W3C Baggage Edge Middleware Sanitization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly calling propagation.extract on unvalidated incoming headers allows external clients to inject arbitrary key-value pairs into OpenTelemetry Baggage, which downstream services will log or propagate without trust checks.
```typescript
import { Request, Response, NextFunction } from 'express';
import { context, propagation } from '@opentelemetry/api';

export function telemetryMiddleware(req: Request, res: Response, next: NextFunction) {
  // VULNERABLE: Blindly extracts untrusted external W3C baggage
  // Allows log injection, memory exhaustion, and telemetry poisoning
  const extractedContext = propagation.extract(context.active(), req.headers);
  
  context.with(extractedContext, () => {
    next();
  });
}
```

#### Production Standard (Correct)
> **Standard**: Sanitizes and strips non-allowlisted baggage entries, validates key schemas, prevents CRLF injection via encoding checks, and limits total payload length prior to propagation context extraction.
```typescript
import { Request, Response, NextFunction } from 'express';
import { context, propagation, trace, baggage } from '@opentelemetry/api';

const ALLOWED_BAGGAGE_KEYS = new Set(['tenant_id', 'client_version', 'region']);
const KEY_REGEX = /^[a-z0-9_-]{1,64}$/;
const MAX_VALUE_LENGTH = 256;

function sanitizeBaggageHeader(rawBaggage: string | undefined): string | undefined {
  if (!rawBaggage || rawBaggage.length > 8192) return undefined;
  
  const safeEntries: string[] = [];
  const entries = rawBaggage.split(',');
  
  for (const entry of entries) {
    const [rawKey, ...valParts] = entry.split('=');
    const key = rawKey?.trim().toLowerCase();
    const val = valParts.join('=').trim();
    
    if (key && ALLOWED_BAGGAGE_KEYS.has(key) && KEY_REGEX.test(key)) {
      // Prevent CRLF injection and constrain length
      const cleanVal = encodeURIComponent(decodeURIComponent(val));
      if (cleanVal.length <= MAX_VALUE_LENGTH && !/[\r\n]/.test(cleanVal)) {
        safeEntries.push(`${key}=${cleanVal}`);
      }
    }
  }
  
  return safeEntries.length > 0 ? safeEntries.join(',') : undefined;
}

export function telemetryMiddleware(req: Request, res: Response, next: NextFunction) {
  const sanitizedHeaders = { ...req.headers };
  const rawBaggage = req.headers['baggage'];
  
  if (typeof rawBaggage === 'string') {
    const safeBaggage = sanitizeBaggageHeader(rawBaggage);
    if (safeBaggage) {
      sanitizedHeaders['baggage'] = safeBaggage;
    } else {
      delete sanitizedHeaders['baggage'];
    }
  } else {
    delete sanitizedHeaders['baggage'];
  }

  const extractedContext = propagation.extract(context.active(), sanitizedHeaders);
  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 Boundary Defense

OpenTelemetry W3C Baggage Ingress Sanitization and Boundary Defense defines an industrial-grade behavioral standard for devops engineering. Ingress reverse proxies and edge gateways must strictly validate, filter, and sanitize incoming W3C baggage headers prior to propagating trace context downstream. Unsanitized baggage propagation allows external attackers to inject arbitrary metadata, causing log forgery, sensitive context poisoning, and high-cardinality metric denial of service across distributed telemetry backends. 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 Untrusted External W3C Baggage 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 Untrusted External W3C Baggage 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

Edge middleware MUST NEVER extract and forward raw W3C `baggage` headers without validation against an explicit allowlist of authorized keys.

Edge middleware MUST NEVER extract and forward raw W3C `baggage` headers without validation against an explicit allowlist of authorized keys.

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 strip all unauthenticated external `baggage` headers at edge ingress proxies and initialize a fresh, empty W3C baggage context.

Engineers MUST strip all unauthenticated external `baggage` headers at edge ingress proxies and initialize a fresh, empty W3C baggage 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.
3

Allowed baggage keys MUST match strict alphanumeric patterns (e.g., `^[a-z0-9_.-]{1,64}$`) and values MUST be URL-decoded and validated against injection payloads (CRLF, terminal escapes, format strings).

Allowed baggage keys MUST match strict alphanumeric patterns (e.g., `^[a-z0-9_.-]{1,64}$`) and values MUST be URL-decoded and validated against injection payloads (CRLF, terminal escapes, format strings).

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

Baggage entry limits MUST enforce strict payload boundaries

Baggage entry limits MUST enforce strict payload boundaries: maximum 32 key-value pairs, individual value length <= 256 bytes, and overall header length <= 8192 bytes.

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

Sensitive tokens, PII, session identifiers, and authorization credentials MUST NEVER be stored in or propagated via W3C baggage headers.

Sensitive tokens, PII, session identifiers, and authorization credentials MUST NEVER be stored in or propagated via W3C baggage 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.
6

Engineers MUST configure the OpenTelemetry `W3CBaggagePropagator` with a custom getter/sanitizer or mutate the carrier headers prior to invoking `propagation.extract()`.

Engineers MUST configure the OpenTelemetry `W3CBaggagePropagator` with a custom getter/sanitizer or mutate the carrier headers prior to invoking `propagation.extract()`.

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

Ingress reverse proxies and edge gateways must strictly validate, filter, and sanitize incoming W3C baggage headers prior to propagating trace context downstream. Unsanitized baggage propagation allows external attackers to inject arbitrary metadata, causing log forgery, sensitive context poisoning, and high-cardinality metric denial of service across distributed telemetry backends. 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 Untrusted External W3C Baggage 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