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

OpenTelemetry W3C Baggage Ingress Sanitization and Boundary Mutation Fencing

Enforces strict allowlist validation, key-length constraints, and PII redaction on OpenTelemetry W3C Baggage headers at untrusted network and service boundaries. Prevents unbounded metric cardinality explosion, memory bloat, and cross-tenant data exfiltration across downstream microservice call graphs. Guarantees that only explicitly declared, schema-validated operational context is propagated through distributed trace contexts.

Prohibited Anti-Pattern: Blind Ingress Baggage Extraction and Propagation Allowing Metric Explosion and Context Tainting

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry W3C Baggage Ingress Sanitization and Boundary Mutation Fencing - Enforces strict allowlist validation, key-length constraints, and PII redaction on OpenTelemetry W3C Baggage headers at untrusted network and service boundaries. Prevents unbounded metric cardinality explosion, memory bloat, and cross-tenant data exfiltration across downstream microservice call graphs. Guarantees that only explicitly declared, schema-validated operational context is propagated through distributed trace contexts.
globs: src/middleware/**/*.{ts,js}, src/gateway/**/*.{ts,js}, src/telemetry/**/*.{ts,js}, src/plugins/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-w3c-baggage-scrubbing-production-standard"
---

# OpenTelemetry W3C Baggage Ingress Sanitization and Boundary Mutation Fencing

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Blind Ingress Baggage Extraction and Propagation Allowing Metric Explosion and Context Tainting

## System Constraints
You are a Principal Software Architect and Systems Reliability Engineer specializing in distributed tracing, telemetry pipeline security, and OpenTelemetry standards. You mandate that untrusted W3C Baggage headers received at ingress boundaries must never be propagated downstream verbatim. You strictly enforce schema-based allowlists, value truncation, metadata filtering, and sanitization fences before injecting baggage into root request contexts to protect downstream telemetry storage and avoid PII leaks.

## Strict Guidelines
- Services MUST NOT propagate raw, unparsed, or untrusted W3C `baggage` HTTP headers directly to downstream RPC or HTTP calls.
- Ingress gateways MUST sanitize baggage using an explicit key allowlist; any baggage key not present in the allowlist MUST be discarded immediately at the edge.
- Engineers MUST enforce length limits on baggage keys (maximum 32 ASCII characters) and values (maximum 128 ASCII characters) to prevent header-bloat amplification and downstream OOM conditions.
- Telemetry contexts MUST NEVER store PII (such as emails, IP addresses, user IDs, or auth tokens) within baggage entries; baggage is reserved strictly for operational routing and multi-tenant partitioning metadata.
- Baggage mutations at service boundaries MUST create a new, immutable `Context` object rather than mutating existing baggage or trace context in-place.
- Propagator middleware MUST log or increment a dropped-baggage metric counter whenever incoming baggage items violate schema rules or cardinality constraints.

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

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly propagating untrusted headers via `propagation.extract` accepts unbounded baggage entries. Malicious actors or upstream misconfigurations can inject hundreds of high-cardinality keys, personal identifying information, or arbitrary payload blobs that downstream spans inherit, degrading downstream collector performance and causing massive log/metric cost explosions.
```typescript
import { Request, Response, NextFunction } from 'express';
import { context, propagation } from '@opentelemetry/api';

// ANTI-PATTERN: Blindly extracts untrusted upstream baggage and attaches to active context
export function telemetryMiddleware(req: Request, _res: Response, next: NextFunction) {
  const extractedContext = propagation.extract(context.active(), req.headers);
  // Raw user inputs, PII, and massive arbitrary key-value pairs are propagated downstream verbatim
  context.with(extractedContext, () => {
    next();
  });
}
```

#### Production Standard (Correct)
> **Standard**: The good pattern extracts trace context but completely reconstructs baggage through an explicit allowlist and size fence. Malicious, malformed, or high-cardinality entries are filtered out before downstream calls inherit the context, guaranteeing stable metrics and eliminating PII leakage.
```typescript
import { Request, Response, NextFunction } from 'express';
import { context, propagation, baggageEntryMetadataSymbol } from '@opentelemetry/api';
import { getBaggage, setBaggage, createBaggage } from '@opentelemetry/api';

const ALLOWED_BAGGAGE_KEYS = new Set(['tenant.id', 'routing.tier', 'client.env']);
const MAX_KEY_LENGTH = 32;
const MAX_VALUE_LENGTH = 128;

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

  let sanitizedBaggage = createBaggage();

  if (currentBaggage) {
    for (const [key, entry] of currentBaggage.getAllEntries()) {
      // Validate against strict allowlist and size thresholds
      if (
        ALLOWED_BAGGAGE_KEYS.has(key) &&
        key.length <= MAX_KEY_LENGTH &&
        typeof entry.value === 'string' &&
        entry.value.length <= MAX_VALUE_LENGTH &&
        !/[\r\n;]/.test(entry.value) // Prevent header injection
      ) {
        sanitizedBaggage = sanitizedBaggage.setEntry(key, {
          value: entry.value,
          metadata: entry.metadata,
        });
      }
    }
  }

  // Clear legacy/dirty baggage and bind strictly sanitized context
  const cleanContext = setBaggage(extractedContext, sanitizedBaggage);
  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 Ingress Sanitization and Boundary Mutation Fencing

OpenTelemetry W3C Baggage Ingress Sanitization and Boundary Mutation Fencing defines an industrial-grade behavioral standard for devops engineering. Enforces strict allowlist validation, key-length constraints, and PII redaction on OpenTelemetry W3C Baggage headers at untrusted network and service boundaries. Prevents unbounded metric cardinality explosion, memory bloat, and cross-tenant data exfiltration across downstream microservice call graphs. Guarantees that only explicitly declared, schema-validated operational context is propagated through distributed trace contexts. 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 Ingress Baggage Extraction and Propagation Allowing Metric Explosion and Context Tainting 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 Ingress Baggage Extraction and Propagation Allowing Metric Explosion and Context TaintingCritical
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

Services MUST NOT propagate raw, unparsed, or untrusted W3C `baggage` HTTP headers directly to downstream RPC or HTTP calls.

Services MUST NOT propagate raw, unparsed, or untrusted W3C `baggage` HTTP headers directly to downstream RPC or HTTP 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.
2

Ingress gateways MUST sanitize baggage using an explicit key allowlist

Ingress gateways MUST sanitize baggage using an explicit key allowlist; any baggage key not present in the allowlist MUST be discarded immediately at the edge.

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

Engineers MUST enforce length limits on baggage keys (maximum 32 ASCII characters) and values (maximum 128 ASCII characters) to prevent header-bloat amplification and downstream OOM conditions.

Engineers MUST enforce length limits on baggage keys (maximum 32 ASCII characters) and values (maximum 128 ASCII characters) to prevent header-bloat amplification and downstream OOM conditions.

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

Telemetry contexts MUST NEVER store PII (such as emails, IP addresses, user IDs, or auth tokens) within baggage entries

Telemetry contexts MUST NEVER store PII (such as emails, IP addresses, user IDs, or auth tokens) within baggage entries; baggage is reserved strictly for operational routing and multi-tenant partitioning metadata.

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

Baggage mutations at service boundaries MUST create a new, immutable `Context` object rather than mutating existing baggage or trace context in-place.

Baggage mutations at service boundaries MUST create a new, immutable `Context` object rather than mutating existing baggage or trace context in-place.

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

Propagator middleware MUST log or increment a dropped-baggage metric counter whenever incoming baggage items violate schema rules or cardinality constraints.

Propagator middleware MUST log or increment a dropped-baggage metric counter whenever incoming baggage items violate schema rules or cardinality constraints.

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

Enforces strict allowlist validation, key-length constraints, and PII redaction on OpenTelemetry W3C Baggage headers at untrusted network and service boundaries. Prevents unbounded metric cardinality explosion, memory bloat, and cross-tenant data exfiltration across downstream microservice call graphs. Guarantees that only explicitly declared, schema-validated operational context is propagated through distributed trace contexts. 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 Ingress Baggage Extraction and Propagation Allowing Metric Explosion and Context Tainting) 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