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

OpenTelemetry W3C Baggage Ingress Boundary Sanitization & Schema Filtering

Enforces strict allowlist validation, key-name regex filtering, and byte-length caps on incoming W3C Baggage headers at API gateways and service ingress boundaries. Prevents cross-tenant context injection, downstream PII/credential leaks into telemetry sinks, and HTTP 431 header bloat attacks.

Prohibited Anti-Pattern: Unvalidated W3C Baggage Ingestion Permitting PII Propagation and Header Bloat

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry W3C Baggage Ingress Boundary Sanitization & Schema Filtering - Enforces strict allowlist validation, key-name regex filtering, and byte-length caps on incoming W3C Baggage headers at API gateways and service ingress boundaries. Prevents cross-tenant context injection, downstream PII/credential leaks into telemetry sinks, and HTTP 431 header bloat attacks.
globs: src/telemetry/**/*.{ts,js}, src/middleware/**/*.{ts,js}, src/ingress/**/*.{ts,js}, src/instrumentation/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-baggage-boundary-sanitization-production-standard"
---

# OpenTelemetry W3C Baggage Ingress Boundary Sanitization & Schema Filtering

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unvalidated W3C Baggage Ingestion Permitting PII Propagation and Header Bloat

## System Constraints
You are a Principal Software Architect enforcing the OpenTelemetry W3C Baggage Boundary Sanitization Invariant. Mandate strict schema-driven allowlisting, length limits, and regex constraints on all inbound Baggage context to prevent telemetry pollution, PII leaks, and header-based DoS vulnerabilities.

## Strict Guidelines
- Engineers MUST ALWAYS sanitize or regenerate W3C Baggage headers at external ingress boundaries before context propagation to downstream services.
- Engineers MUST NOT blindly forward incoming `baggage` headers without allowlist key matching and value schema validation.
- Services MUST enforce an explicit schema allowlist (e.g., regex `^[a-z0-9_\-.]{1,32}$` for keys) and reject or drop keys associated with PII, secrets, or internal auth tokens.
- Code SHOULD enforce a maximum aggregate byte limit (e.g., 2048 bytes) and individual entry limit (e.g., 256 bytes) on baggage items to prevent HTTP 431 Request Header Fields Too Large downstream.
- Components NEVER store sensitive attributes such as session tokens, emails, SSNs, credit card numbers, or tenant credentials in baggage entries.

## Bad vs Good Implementations
### Ingress Baggage Sanitization Middleware

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly extracting context from raw HTTP headers permits unverified client-supplied baggage items to enter the distributed tracing context. This allows malicious actors to inject arbitrary key-value pairs (e.g., spoofed tenant IDs), pollute trace storage, leak PII into observability sinks, and cause HTTP 431 header overflow errors in downstream RPCs.
```typescript
import { context, propagation, defaultTextMapGetter } from '@opentelemetry/api';
import { Request, Response, NextFunction } from 'express';

export function telemetryMiddleware(req: Request, res: Response, next: NextFunction) {
  // VULNERABILITY: Raw propagation extraction blindly accepts all external baggage,
  // allowing attackers to inject forged tenant IDs, PII, or massive header payloads
  // that leak into downstream logs, traces, and HTTP calls.
  const activeContext = propagation.extract(context.active(), req.headers, defaultTextMapGetter);
  
  context.with(activeContext, () => {
    next();
  });
}
```

#### Production Standard (Correct)
> **Standard**: The sanitized implementation filters all extracted baggage against an explicit allowlist and strict regex schema, rejects keys exceeding size bounds, prevents header bloat by enforcing an aggregate byte ceiling, and replaces the untrusted baggage with the sanitized instance before propagation.
```typescript
import { context, propagation, defaultTextMapGetter, baggageEntryMetadataSymbol, Baggage, BaggageEntry } from '@opentelemetry/api';
import { Request, Response, NextFunction } from 'express';

const ALLOWED_BAGGAGE_KEYS = new Map<string, RegExp>([
  ['tenant.id', /^[a-f0-9\-]{36}$/i],
  ['request.origin', /^[a-zA-Z0-9\-_]{1,32}$/],
  ['traffic.class', /^(standard|priority|bulk)$/]
]);

const MAX_BAGGAGE_BYTES = 2048;
const MAX_VALUE_LENGTH = 256;

export function telemetryMiddleware(req: Request, res: Response, next: NextFunction) {
  const extractedContext = propagation.extract(context.active(), req.headers, defaultTextMapGetter);
  const rawBaggage = propagation.getBaggage(extractedContext);

  let sanitizedContext = extractedContext;

  if (rawBaggage) {
    let currentSizeBytes = 0;
    const sanitizedEntries: [string, BaggageEntry][] = [];

    for (const [key, entry] of rawBaggage.getAllEntries()) {
      const validator = ALLOWED_BAGGAGE_KEYS.get(key);
      if (!validator || entry.value.length > MAX_VALUE_LENGTH) {
        continue;
      }

      if (!validator.test(entry.value)) {
        continue;
      }

      const entrySize = Buffer.byteLength(key, 'utf8') + Buffer.byteLength(entry.value, 'utf8');
      if (currentSizeBytes + entrySize > MAX_BAGGAGE_BYTES) {
        break;
      }

      currentSizeBytes += entrySize;
      sanitizedEntries.push([key, entry]);
    }

    const filteredBaggage: Baggage = propagation.createBaggage(
      Object.fromEntries(sanitizedEntries)
    );
    sanitizedContext = propagation.setBaggage(extractedContext, filteredBaggage);
  }

  context.with(sanitizedContext, () => {
    next();
  });
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenTelemetry W3C Baggage Ingress Boundary Sanitization & Schema Filtering

OpenTelemetry W3C Baggage Ingress Boundary Sanitization & Schema Filtering defines an industrial-grade behavioral standard for devops engineering. Enforces strict allowlist validation, key-name regex filtering, and byte-length caps on incoming W3C Baggage headers at API gateways and service ingress boundaries. Prevents cross-tenant context injection, downstream PII/credential leaks into telemetry sinks, and HTTP 431 header bloat attacks. 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: Unvalidated W3C Baggage Ingestion Permitting PII Propagation and Header Bloat 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 DriftUnvalidated W3C Baggage Ingestion Permitting PII Propagation and Header BloatCritical
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 sanitize or regenerate W3C Baggage headers at external ingress boundaries before context propagation to downstream services.

Engineers MUST ALWAYS sanitize or regenerate W3C Baggage headers at external ingress boundaries before context propagation 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.
2

Engineers MUST NOT blindly forward incoming `baggage` headers without allowlist key matching and value schema validation.

Engineers MUST NOT blindly forward incoming `baggage` headers without allowlist key matching and value schema 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 an explicit schema allowlist (e.g., regex `^[a-z0-9_\-.]{1,32}$` for keys) and reject or drop keys associated with PII, secrets, or internal auth tokens.

Services MUST enforce an explicit schema allowlist (e.g., regex `^[a-z0-9_\-.]{1,32}$` for keys) and reject or drop keys associated with PII, secrets, or internal auth tokens.

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 enforce a maximum aggregate byte limit (e.g., 2048 bytes) and individual entry limit (e.g., 256 bytes) on baggage items to prevent HTTP 431 Request Header Fields Too Large downstream.

Code SHOULD enforce a maximum aggregate byte limit (e.g., 2048 bytes) and individual entry limit (e.g., 256 bytes) on baggage items to prevent HTTP 431 Request Header Fields Too Large downstream.

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 attributes such as session tokens, emails, SSNs, credit card numbers, or tenant credentials in baggage entries.

Components NEVER store sensitive attributes such as session tokens, emails, SSNs, credit card numbers, or tenant credentials in baggage 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.
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 Boundary Sanitization & Schema Filtering critical for AI coding assistants?

Enforces strict allowlist validation, key-name regex filtering, and byte-length caps on incoming W3C Baggage headers at API gateways and service ingress boundaries. Prevents cross-tenant context injection, downstream PII/credential leaks into telemetry sinks, and HTTP 431 header bloat attacks. 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 (Unvalidated W3C Baggage Ingestion Permitting PII Propagation and Header Bloat) 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