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

OpenTelemetry W3C Baggage Ingress Sanitization and PII Redaction Invariant

Enforces deterministic schema validation, allowlist filtering, and PII redaction on inbound W3C Baggage headers at API gateways and service boundaries. Prevents unbounded header injection, credential leakage, and cross-microservice PII exfiltration across distributed OpenTelemetry traces.

Prohibited Anti-Pattern: Unvalidated Forwarding of Raw Inbound W3C Baggage Headers to Downstream Trace Contexts

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry W3C Baggage Ingress Sanitization and PII Redaction Invariant - Enforces deterministic schema validation, allowlist filtering, and PII redaction on inbound W3C Baggage headers at API gateways and service boundaries. Prevents unbounded header injection, credential leakage, and cross-microservice PII exfiltration across distributed OpenTelemetry traces.
globs: src/middleware/**/*.{ts,js}, src/gateway/**/*.{ts,js}, src/telemetry/**/*.{ts,js}, src/tracing/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-baggage-ingress-pii-sanitization"
---

# OpenTelemetry W3C Baggage Ingress Sanitization and PII Redaction Invariant

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unvalidated Forwarding of Raw Inbound W3C Baggage Headers to Downstream Trace Contexts

## System Constraints
You are a Principal Engineer enforcing the OpenTelemetry W3C Baggage Ingress Sanitization and PII Redaction Invariant. Mandate that all incoming distributed context headers, specifically W3C Baggage, are treated as untrusted user input at ingress boundaries. Inbound baggage must be stripped, validated against an explicit metadata allowlist, checked for sensitive/PII patterns, bounded by size, and reconstructed into an immutable trace context before propagation to downstream microservices.

## Strict Guidelines
- Engineers MUST ALWAYS strip or sanitize untrusted external `baggage` HTTP headers at the edge/ingress gateway before invoking downstream services.
- Engineers MUST NEVER propagate raw inbound OpenTelemetry Baggage directly using default propagators without an explicit key allowlist.
- Ingress middleware MUST validate baggage keys against a strict, centrally defined schema of non-sensitive contextual metadata (e.g., `tenant.id`, `deployment.region`, `client.version`).
- Services MUST enforce strict boundary constraints: maximum 8 baggage entries, key length <= 32 bytes, and value length <= 128 bytes, silently dropping or rejecting non-conforming items.
- Components NEVER attach high-entropy tokens, authorization headers, email addresses, UUIDs representing direct PII, or credentials to trace baggage.
- Edge gateways SHOULD log security telemetry when anomalous or oversized baggage payloads are detected and dropped.

## Bad vs Good Implementations
### Ingress Baggage Handling in Gateway Middleware

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly delegating to defaultTextMapGetter propagates untrusted incoming W3C Baggage entries (e.g., 'baggage: [email protected],secret_token=jwt...') across internal services, triggering compliance violations, log contamination, and potential denial-of-service via header amplification.
```typescript
import { propagation, context, defaultTextMapGetter } from '@opentelemetry/api';
import { Request, Response, NextFunction } from 'express';

export function telemetryMiddleware(req: Request, res: Response, next: NextFunction) {
  // VULNERABLE: Direct extraction propagates arbitrary client-supplied baggage
  // Untrusted clients can inject PII, authorization tokens, or massive payloads
  const extractedContext = propagation.extract(context.active(), req.headers, defaultTextMapGetter);
  
  context.with(extractedContext, () => {
    next();
  });
}
```

#### Production Standard (Correct)
> **Standard**: Extracts context safely by intercepting incoming baggage, dropping unapproved keys, enforcing length limits, validating against PII/token patterns, and reconstructing a minimal, clean Baggage instance bound to downstream execution.
```typescript
import { propagation, context, defaultTextMapGetter, Baggage, baggageEntryMetadataSymbol } from '@opentelemetry/api';
import { Request, Response, NextFunction } from 'express';

const ALLOWED_BAGGAGE_KEYS = new Set(['tenant.id', 'client.environment', 'routing.datacenter']);
const MAX_BAGGAGE_ENTRIES = 8;
const MAX_VALUE_LENGTH = 128;
const PII_REGEX = /[\w.-]+@[\w.-]+\.[A-Za-z]{2,}|bearer\s+[a-zA-Z0-9._-]+/i;

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

  let sanitizedBaggage = propagation.createBaggage();
  
  if (rawBaggage) {
    let count = 0;
    for (const [key, entry] of rawBaggage.getAllEntries()) {
      if (count >= MAX_BAGGAGE_ENTRIES) break;
      
      if (
        ALLOWED_BAGGAGE_KEYS.has(key) &&
        typeof entry.value === 'string' &&
        entry.value.length <= MAX_VALUE_LENGTH &&
        !PII_REGEX.test(entry.value)
      ) {
        sanitizedBaggage = sanitizedBaggage.setEntry(key, { value: entry.value });
        count++;
      }
    }
  }

  const secureContext = propagation.setBaggage(extractedContext, sanitizedBaggage);
  context.with(secureContext, () => {
    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 PII Redaction Invariant

OpenTelemetry W3C Baggage Ingress Sanitization and PII Redaction Invariant defines an industrial-grade behavioral standard for devops engineering. Enforces deterministic schema validation, allowlist filtering, and PII redaction on inbound W3C Baggage headers at API gateways and service boundaries. Prevents unbounded header injection, credential leakage, and cross-microservice PII exfiltration across distributed OpenTelemetry traces. 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 Forwarding of Raw Inbound W3C Baggage Headers to Downstream Trace Contexts 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 Forwarding of Raw Inbound W3C Baggage Headers to Downstream Trace ContextsCritical
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 strip or sanitize untrusted external `baggage` HTTP headers at the edge/ingress gateway before invoking downstream services.

Engineers MUST ALWAYS strip or sanitize untrusted external `baggage` HTTP headers at the edge/ingress gateway before invoking 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 NEVER propagate raw inbound OpenTelemetry Baggage directly using default propagators without an explicit key allowlist.

Engineers MUST NEVER propagate raw inbound OpenTelemetry Baggage directly using default propagators without an explicit key allowlist.

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

Ingress middleware MUST validate baggage keys against a strict, centrally defined schema of non-sensitive contextual metadata (e.g., `tenant.id`, `deployment.region`, `client.version`).

Ingress middleware MUST validate baggage keys against a strict, centrally defined schema of non-sensitive contextual metadata (e.g., `tenant.id`, `deployment.region`, `client.version`).

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 strict boundary constraints

Services MUST enforce strict boundary constraints: maximum 8 baggage entries, key length <= 32 bytes, and value length <= 128 bytes, silently dropping or rejecting non-conforming items.

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 attach high-entropy tokens, authorization headers, email addresses, UUIDs representing direct PII, or credentials to trace baggage.

Components NEVER attach high-entropy tokens, authorization headers, email addresses, UUIDs representing direct PII, or credentials to trace baggage.

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

Edge gateways SHOULD log security telemetry when anomalous or oversized baggage payloads are detected and dropped.

Edge gateways SHOULD log security telemetry when anomalous or oversized baggage payloads are detected and dropped.

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 PII Redaction Invariant critical for AI coding assistants?

Enforces deterministic schema validation, allowlist filtering, and PII redaction on inbound W3C Baggage headers at API gateways and service boundaries. Prevents unbounded header injection, credential leakage, and cross-microservice PII exfiltration across distributed OpenTelemetry traces. 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 Forwarding of Raw Inbound W3C Baggage Headers to Downstream Trace Contexts) 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