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

OpenTelemetry W3C Baggage Sanitization and Propagation Isolation Standard

Enforces strict input validation, key allowlisting, and byte-budget limits on OpenTelemetry W3C Baggage propagation across distributed systems. Prevents header injection (CRLF), HTTP 431 (Request Header Fields Too Large) outages, and multi-tenant context leakage across trust boundaries.

Prohibited Anti-Pattern: Unbounded, Raw Baggage Injection and Forwarding Across Untrusted Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry W3C Baggage Sanitization and Propagation Isolation Standard - Enforces strict input validation, key allowlisting, and byte-budget limits on OpenTelemetry W3C Baggage propagation across distributed systems. Prevents header injection (CRLF), HTTP 431 (Request Header Fields Too Large) outages, and multi-tenant context leakage across trust boundaries.
globs: src/**/telemetry/**/*.{ts,js}, src/**/middleware/**/*.{ts,js}, src/**/tracing/**/*.{ts,js}, src/**/http/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-w3c-baggage-propagation-isolation-standard"
---

# OpenTelemetry W3C Baggage Sanitization and Propagation Isolation Standard

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unbounded, Raw Baggage Injection and Forwarding Across Untrusted Boundaries

## System Constraints
You are a Principal Software Architect enforcing the OpenTelemetry W3C Baggage Propagation Isolation Standard. You must ensure that all incoming and outgoing W3C baggage entries are strictly validated against an approved key allowlist, checked for RFC 7230/RFC 2616 token compliance, stripped of CRLF and control characters, and constrained within strict byte quotas (maximum 2048 bytes total aggregate size, maximum 64 bytes per key, and maximum 256 bytes per value) to prevent header injection, HTTP 431 cascading failures, and multi-tenant data leaks.

## Strict Guidelines
- Engineers MUST ALWAYS validate baggage keys against a deterministic allowlist before propagation across network boundaries.
- Engineers MUST NOT forward raw, unvalidated incoming HTTP baggage headers directly to downstream services.
- Code SHOULD enforce strict RFC-compliant regex validation (`/^[a-zA-Z0-9!#$%&'*+-.^_`|~]+$/`) on baggage keys and percent-encoded values to prevent CRLF header injection.
- Services MUST enforce hard byte-size quotas: total baggage payload <= 2048 bytes, keys <= 64 bytes, values <= 256 bytes, and a maximum of 32 total entries.
- Components NEVER store sensitive PII, authentication tokens, credentials, or untrusted user input directly in Baggage context.

## Bad vs Good Implementations
### Unsafe Raw Baggage Propagation vs. Isolated Allowlisted Baggage Sanitizer

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accepts user-controlled input and raw baggage headers without size checks, regex validation, or tenant validation. Allows arbitrary keys, CRLF injection through raw values, and HTTP 431 cascades caused by header bloat.
```typescript
import { context, propagation } from '@opentelemetry/api';
import { Request, Response, NextFunction } from 'express';

// ANTI-PATTERN: Blindly accepting incoming baggage and user-controlled
// headers without size limits, character validation, or key allowlisting.
export function telemetryMiddleware(req: Request, _res: Response, next: NextFunction): void {
  const userSuppliedTenant = req.headers['x-tenant-override'] as string;
  const rawBaggage = req.headers['baggage'] as string;

  // VULNERABLE: Direct CRLF injection vector and potential multi-tenant spoofing
  let activeContext = propagation.extract(context.active(), req.headers);
  if (userSuppliedTenant) {
    activeContext = propagation.setBaggage(
      activeContext,
      propagation.createBaggage({ 'tenant.id': { value: userSuppliedTenant } })
    );
  }

  // Unbounded propagation can cause downstream HTTP 431 Header Overflow
  context.with(activeContext, () => next());
}
```

#### Production Standard (Correct)
> **Standard**: Implements an explicit key allowlist, restricts maximum entry counts and byte lengths, prevents CRLF injection via strict character validation, and mitigates HTTP 431 header-size DoS attacks.
```typescript
import { context, propagation, Baggage, BaggageEntry } from '@opentelemetry/api';
import { Request, Response, NextFunction } from 'express';

const MAX_TOTAL_BYTES = 2048;
const MAX_KEY_LEN = 64;
const MAX_VAL_LEN = 256;
const MAX_ENTRIES = 32;
const RFC_TOKEN_REGEX = /^[a-zA-Z0-9!#$%&'*+-.^_`|~]+$/;

const ALLOWED_BAGGAGE_KEYS = new Set<string>([
  'tenant.id',
  'environment',
  'region',
  'request.priority'
]);

export function sanitizeAndIsolateBaggage(incoming: Baggage): Baggage {
  let totalBytes = 0;
  let entryCount = 0;
  const sanitizedEntries: Record<string, BaggageEntry> = {};

  for (const [key, entry] of incoming.getAllEntries()) {
    if (entryCount >= MAX_ENTRIES) break;
    if (!ALLOWED_BAGGAGE_KEYS.has(key)) continue;
    if (key.length > MAX_KEY_LEN || !RFC_TOKEN_REGEX.test(key)) continue;

    const value = entry.value;
    if (!value || value.length > MAX_VAL_LEN) continue;
    // Prohibit CRLF and non-printable control characters
    if (/[\r\n\x00-\x1F\x7F]/.test(value)) continue;

    const entryByteCost = key.length + value.length + 2; // key=value;
    if (totalBytes + entryByteCost > MAX_TOTAL_BYTES) break;

    totalBytes += entryByteCost;
    entryCount++;
    sanitizedEntries[key] = { value, metadata: entry.metadata };
  }

  return propagation.createBaggage(sanitizedEntries);
}

export function safeTelemetryMiddleware(req: Request, _res: Response, next: NextFunction): void {
  const extractedCtx = propagation.extract(context.active(), req.headers);
  const incomingBaggage = propagation.getBaggage(extractedCtx);

  const safeBaggage = incomingBaggage
    ? sanitizeAndIsolateBaggage(incomingBaggage)
    : propagation.createBaggage();

  const cleanContext = propagation.setBaggage(extractedCtx, safeBaggage);
  context.with(cleanContext, () => 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 Sanitization and Propagation Isolation Standard

OpenTelemetry W3C Baggage Sanitization and Propagation Isolation Standard defines an industrial-grade behavioral standard for devops engineering. Enforces strict input validation, key allowlisting, and byte-budget limits on OpenTelemetry W3C Baggage propagation across distributed systems. Prevents header injection (CRLF), HTTP 431 (Request Header Fields Too Large) outages, and multi-tenant context leakage across trust 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, Raw Baggage Injection and Forwarding Across Untrusted Boundaries 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, Raw Baggage Injection and Forwarding Across Untrusted BoundariesCritical
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 validate baggage keys against a deterministic allowlist before propagation across network boundaries.

Engineers MUST ALWAYS validate baggage keys against a deterministic allowlist before propagation across network 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 forward raw, unvalidated incoming HTTP baggage headers directly to downstream services.

Engineers MUST NOT forward raw, unvalidated incoming HTTP baggage headers directly to downstream services.

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

Code SHOULD enforce strict RFC-compliant regex validation (`/^[a-zA-Z0-9!#$%&'*+-.^_`|~]+$/`) on baggage keys and percent-encoded values to prevent CRLF header injection.

Code SHOULD enforce strict RFC-compliant regex validation (`/^[a-zA-Z0-9!#$%&'*+-.^_`|~]+$/`) on baggage keys and percent-encoded values to prevent CRLF header injection.

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 hard byte-size quotas

Services MUST enforce hard byte-size quotas: total baggage payload <= 2048 bytes, keys <= 64 bytes, values <= 256 bytes, and a maximum of 32 total entries.

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 sensitive PII, authentication tokens, credentials, or untrusted user input directly in Baggage context.

Components NEVER store sensitive PII, authentication tokens, credentials, or untrusted user input directly in 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.
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 Sanitization and Propagation Isolation Standard critical for AI coding assistants?

Enforces strict input validation, key allowlisting, and byte-budget limits on OpenTelemetry W3C Baggage propagation across distributed systems. Prevents header injection (CRLF), HTTP 431 (Request Header Fields Too Large) outages, and multi-tenant context leakage across trust 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, Raw Baggage Injection and Forwarding Across Untrusted Boundaries) 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