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

OpenTelemetry W3C TraceContext and Baggage PII Sanitization Guardrail

Enforces strict allowlisting, redaction, and size boundaries on OpenTelemetry W3C Baggage propagation across service boundaries. Prevents severe regulatory compliance exposure (GDPR, HIPAA, CCPA) and downstream HTTP 431 header overflow cascades caused by unconstrained propagation of sensitive contextual data.

Prohibited Anti-Pattern: Blind Downstream Propagation of Unsanitized Baggage Headers Leaking PII and Inducing Header Bloat

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry W3C TraceContext and Baggage PII Sanitization Guardrail - Enforces strict allowlisting, redaction, and size boundaries on OpenTelemetry W3C Baggage propagation across service boundaries. Prevents severe regulatory compliance exposure (GDPR, HIPAA, CCPA) and downstream HTTP 431 header overflow cascades caused by unconstrained propagation of sensitive contextual data.
globs: src/telemetry/**/*.{ts,js}, src/tracing/**/*.{ts,js}, src/middleware/**/*.{ts,js}, src/infrastructure/observability/**/*.{ts,js}, src/common/http/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/otel-w3c-tracecontext-baggage-pii-sanitization-standard"
---

# OpenTelemetry W3C TraceContext and Baggage PII Sanitization Guardrail

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Blind Downstream Propagation of Unsanitized Baggage Headers Leaking PII and Inducing Header Bloat

## System Constraints
You are a Principal Observability & Security Architect enforcing strict OpenTelemetry W3C TraceContext and Baggage sanitization standards. You must reject any code pattern that implicitly forwards incoming baggage headers, injects personal identifiable information (PII) into baggage, or fails to enforce total header length and per-key allowlist restrictions prior to outbound network hops.

## Strict Guidelines
- Services MUST NEVER propagate incoming W3C Baggage headers downstream without passing through an explicit allowlist-based BaggageEntryFilter.
- Engineers MUST NEVER populate OpenTelemetry Baggage with plain-text PII (e.g., email, account owner names, IP addresses, JWT tokens, credit card tokens). Only non-reversible pseudo-anonymous identifiers (e.g., hashed tenant IDs) are permitted.
- Outbound HTTP clients MUST enforce total serialized W3C Baggage header byte limits (maximum 8192 bytes across all items, maximum 64 total entries) to prevent HTTP 431 Request Header Fields Too Large errors.
- Custom OpenTelemetry TextMapPropagator instances MUST wrap default W3C Baggage propagators to filter, sanitize, and truncate entries on inject() and extract() cycles.
- Telemetry interceptors MUST emit structured audit warning logs and drop keys whenever non-allowlisted or oversized baggage keys are detected.

## Bad vs Good Implementations
### Unsanitized Direct Baggage Forwarding vs. Allowlist-Gated Sanitized Propagator

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly injecting ambient context without an intermediary sanitization filter forwards all incoming baggage keys (including user emails, raw session tokens, and high-cardinality metadata), breaching privacy regulations and potentially causing downstream 431 Request Header Fields Too Large failures.
```typescript
import { context, baggage, propagation, TextMapSetter } from '@opentelemetry/api';
import axios, { AxiosRequestConfig } from 'axios';

// ANTI-PATTERN: Indiscriminately injects incoming context/baggage into outbound calls,
// propagating raw user emails, customer names, and arbitrary unbounded headers downstream.
export async function callDownstreamService(url: string, payload: unknown, incomingContext = context.active()): Promise<void> {
  const headers: Record<string, string> = {};
  
  // Blind injection forwards all W3C baggage entries without inspection
  propagation.inject(incomingContext, headers);
  
  const config: AxiosRequestConfig = {
    method: 'POST',
    url,
    data: payload,
    headers,
  };
  
  await axios(config);
}
```

#### Production Standard (Correct)
> **Standard**: Strictly gates baggage propagation through an immutable allowlist and calculates cumulative serialized byte sizes. Non-compliant keys and payloads that exceed the byte budget are discarded prior to downstream injection, upholding privacy compliance and eliminating header overflow cascades.
```typescript
import { context, baggage, propagation, Context, BaggageEntry } from '@opentelemetry/api';
import axios, { AxiosRequestConfig } from 'axios';

const ALLOWED_BAGGAGE_KEYS = new Set(['tenant.id', 'routing.region', 'client.version']);
const MAX_BAGGAGE_TOTAL_BYTES = 4096;

function getSanitizedBaggageContext(ctx: Context): Context {
  const activeBaggage = baggage.getBaggage(ctx);
  if (!activeBaggage) return ctx;

  let sanitized = baggage.createBaggage();
  let accumulatedBytes = 0;

  for (const [key, entry] of activeBaggage.getAllEntries()) {
    if (!ALLOWED_BAGGAGE_KEYS.has(key)) {
      continue; // Drop non-whitelisted keys containing potential PII or bloat
    }

    const entrySize = Buffer.byteLength(`${key}=${entry.value}`);
    if (accumulatedBytes + entrySize > MAX_BAGGAGE_TOTAL_BYTES) {
      break; // Enforce strict byte-size budget
    }

    sanitized = sanitized.setEntry(key, entry);
    accumulatedBytes += entrySize;
  }

  return baggage.setBaggage(ctx, sanitized);
}

export async function callDownstreamService(url: string, payload: unknown, incomingContext = context.active()): Promise<void> {
  const sanitizedContext = getSanitizedBaggageContext(incomingContext);
  const headers: Record<string, string> = {};
  
  propagation.inject(sanitizedContext, headers);
  
  const config: AxiosRequestConfig = {
    method: 'POST',
    url,
    data: payload,
    headers,
  };
  
  await axios(config);
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenTelemetry W3C TraceContext and Baggage PII Sanitization Guardrail

OpenTelemetry W3C TraceContext and Baggage PII Sanitization Guardrail defines an industrial-grade behavioral standard for devops engineering. Enforces strict allowlisting, redaction, and size boundaries on OpenTelemetry W3C Baggage propagation across service boundaries. Prevents severe regulatory compliance exposure (GDPR, HIPAA, CCPA) and downstream HTTP 431 header overflow cascades caused by unconstrained propagation of sensitive contextual data. 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 Unsanitized Baggage Headers Leaking PII and Inducing 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 DriftBlind Downstream Propagation of Unsanitized Baggage Headers Leaking PII and Inducing 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

Services MUST NEVER propagate incoming W3C Baggage headers downstream without passing through an explicit allowlist-based BaggageEntryFilter.

Services MUST NEVER propagate incoming W3C Baggage headers downstream without passing through an explicit allowlist-based BaggageEntryFilter.

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 populate OpenTelemetry Baggage with plain-text PII (e.g., email, account owner names, IP addresses, JWT tokens, credit card tokens). Only non-reversible pseudo-anonymous identifiers (e.g., hashed tenant IDs) are permitted.

Engineers MUST NEVER populate OpenTelemetry Baggage with plain-text PII (e.g., email, account owner names, IP addresses, JWT tokens, credit card tokens). Only non-reversible pseudo-anonymous identifiers (e.g., hashed tenant IDs) are permitted.

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

Outbound HTTP clients MUST enforce total serialized W3C Baggage header byte limits (maximum 8192 bytes across all items, maximum 64 total entries) to prevent HTTP 431 Request Header Fields Too Large errors.

Outbound HTTP clients MUST enforce total serialized W3C Baggage header byte limits (maximum 8192 bytes across all items, maximum 64 total entries) to prevent HTTP 431 Request Header Fields Too Large errors.

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

Custom OpenTelemetry TextMapPropagator instances MUST wrap default W3C Baggage propagators to filter, sanitize, and truncate entries on inject() and extract() cycles.

Custom OpenTelemetry TextMapPropagator instances MUST wrap default W3C Baggage propagators to filter, sanitize, and truncate entries on inject() and extract() cycles.

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

Telemetry interceptors MUST emit structured audit warning logs and drop keys whenever non-allowlisted or oversized baggage keys are detected.

Telemetry interceptors MUST emit structured audit warning logs and drop keys whenever non-allowlisted or oversized baggage keys are detected.

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 TraceContext and Baggage PII Sanitization Guardrail critical for AI coding assistants?

Enforces strict allowlisting, redaction, and size boundaries on OpenTelemetry W3C Baggage propagation across service boundaries. Prevents severe regulatory compliance exposure (GDPR, HIPAA, CCPA) and downstream HTTP 431 header overflow cascades caused by unconstrained propagation of sensitive contextual data. 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 Unsanitized Baggage Headers Leaking PII and Inducing 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