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

OpenTelemetry W3C Baggage PII Sanitization & Egress Redaction Policy

Enforces runtime egress filtering and compile-time type boundaries on OpenTelemetry W3C Baggage context propagation. Prevents inadvertent leakage of Personally Identifiable Information (PII) and secret credentials to external distributed trace hops via HTTP baggage headers. Mandates explicit allowlisting and automated redaction interceptors on all outbound distributed context injection vectors.

Prohibited Anti-Pattern: Propagating Unfiltered W3C Baggage Headers Containing Tenant PII to External Third-Party APIs

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry W3C Baggage PII Sanitization & Egress Redaction Policy - Enforces runtime egress filtering and compile-time type boundaries on OpenTelemetry W3C Baggage context propagation. Prevents inadvertent leakage of Personally Identifiable Information (PII) and secret credentials to external distributed trace hops via HTTP baggage headers. Mandates explicit allowlisting and automated redaction interceptors on all outbound distributed context injection vectors.
globs: src/telemetry/**/*.ts, src/instrumentation/**/*.ts, src/common/tracing/**/*.ts, src/clients/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-baggage-pii-sanitization-egress-guardrail"
---

# OpenTelemetry W3C Baggage PII Sanitization & Egress Redaction Policy

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Propagating Unfiltered W3C Baggage Headers Containing Tenant PII to External Third-Party APIs

## System Constraints
You are a Principal Software Architect and Rules Author enforcing strict OpenTelemetry W3C Baggage PII Sanitization and Outbound Egress Redaction policies. You must strictly forbid raw, unvalidated key-value insertion into OpenTelemetry baggage contexts and ban default pass-through propagation of baggage headers to external third-party boundaries. Mandate that all context keys conform to an immutable, vetted allowlist, and enforce a custom Composite Propagator that redacts disallowed keys and non-allowlisted origins during outbound injection.

## Strict Guidelines
- Engineers MUST ALWAYS implement an explicit key allowlist when injecting or reading from OpenTelemetry W3C Baggage.
- Engineers MUST NOT place PII, session tokens, tenant secrets, or high-cardinality identifiable parameters directly into OpenTelemetry Baggage.
- Services MUST utilize a custom SanitizingTextMapPropagator that drops all baggage keys that are not strictly allowlisted for the target downstream domain.
- Outbound HTTP clients invoking third-party or untrusted external domains MUST strip the 'baggage' header entirely unless explicit contractual federation is required.
- Telemetry modules SHOULD use opaque branded types for valid baggage keys to trigger compile-time validation errors on unauthorized key names.
- Components NEVER bypass the global OpenTelemetry propagators configuration via manual header copying from incoming to outgoing HTTP requests.

## Bad vs Good Implementations
### Outbound Context Injection with Egress Boundary Sanitization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Attaching customer email and unhashed user identifiers directly into W3C baggage exposes sensitive PII across public internet boundaries and vendor logs, violating GDPR, HIPAA, and internal security policies.
```typescript
import { baggage, context, propagation } from '@opentelemetry/api';
import axios from 'axios';

export async function callExternalVendor(vendorUrl: string, userId: string, email: string) {
  // ANTI-PATTERN: Polluting baggage with raw PII and propagating it downstream indiscriminately
  let ctx = baggage.setBaggage(
    context.active(),
    baggage.createEntry('user.id', userId)
  );
  ctx = baggage.setBaggage(ctx, baggage.createEntry('user.email', email));

  const headers: Record<string, string> = {};
  // Blindly propagates W3C baggage header containing user.email to third-party vendor
  propagation.inject(ctx, headers);

  return axios.post(vendorUrl, { data: 'payload' }, { headers });
}
```

#### Production Standard (Correct)
> **Standard**: Implements an egress sanitation gateway that completely strips baggage for external vendors and strictly allowlists non-PII operational metadata for internal service meshes.
```typescript
import { context, propagation, TextMapSetter, Baggage, baggage } from '@opentelemetry/api';
import axios from 'axios';

// Safe allowlist of propagateable metadata keys
const SAFE_EGRESS_BAGGAGE_KEYS = new Set(['request.id', 'tenant.tier', 'routing.region']);

export function sanitizeBaggageForEgress(activeBaggage: Baggage, isInternalDestination: boolean): Baggage {
  let cleanBaggage = baggage.create();
  if (!isInternalDestination) {
    // Drop baggage entirely for third-party external APIs
    return cleanBaggage;
  }

  for (const [key, entry] of activeBaggage.getAllEntries()) {
    if (SAFE_EGRESS_BAGGAGE_KEYS.has(key)) {
      cleanBaggage = cleanBaggage.setEntry(key, entry);
    }
  }
  return cleanBaggage;
}

export async function callExternalVendor(vendorUrl: string, isInternal: boolean) {
  const activeContext = context.active();
  const currentBaggage = baggage.getBaggage(activeContext);
  const headers: Record<string, string> = {};

  if (currentBaggage) {
    const safeBaggage = sanitizeBaggageForEgress(currentBaggage, isInternal);
    const sanitizedCtx = baggage.setBaggage(activeContext, safeBaggage);
    propagation.inject(sanitizedCtx, headers);
  } else {
    propagation.inject(activeContext, headers);
  }

  return axios.post(vendorUrl, { data: 'payload' }, { headers });
}
```

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 PII Sanitization & Egress Redaction Policy

OpenTelemetry W3C Baggage PII Sanitization & Egress Redaction Policy defines an industrial-grade behavioral standard for devops engineering. Enforces runtime egress filtering and compile-time type boundaries on OpenTelemetry W3C Baggage context propagation. Prevents inadvertent leakage of Personally Identifiable Information (PII) and secret credentials to external distributed trace hops via HTTP baggage headers. Mandates explicit allowlisting and automated redaction interceptors on all outbound distributed context injection vectors. 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: Propagating Unfiltered W3C Baggage Headers Containing Tenant PII to External Third-Party APIs 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 DriftPropagating Unfiltered W3C Baggage Headers Containing Tenant PII to External Third-Party APIsCritical
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 implement an explicit key allowlist when injecting or reading from OpenTelemetry W3C Baggage.

Engineers MUST ALWAYS implement an explicit key allowlist when injecting or reading from OpenTelemetry W3C 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.
2

Engineers MUST NOT place PII, session tokens, tenant secrets, or high-cardinality identifiable parameters directly into OpenTelemetry Baggage.

Engineers MUST NOT place PII, session tokens, tenant secrets, or high-cardinality identifiable parameters directly into OpenTelemetry 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.
3

Services MUST utilize a custom SanitizingTextMapPropagator that drops all baggage keys that are not strictly allowlisted for the target downstream domain.

Services MUST utilize a custom SanitizingTextMapPropagator that drops all baggage keys that are not strictly allowlisted for the target downstream domain.

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

Outbound HTTP clients invoking third-party or untrusted external domains MUST strip the 'baggage' header entirely unless explicit contractual federation is required.

Outbound HTTP clients invoking third-party or untrusted external domains MUST strip the 'baggage' header entirely unless explicit contractual federation is required.

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 modules SHOULD use opaque branded types for valid baggage keys to trigger compile-time validation errors on unauthorized key names.

Telemetry modules SHOULD use opaque branded types for valid baggage keys to trigger compile-time validation errors on unauthorized key names.

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

Components NEVER bypass the global OpenTelemetry propagators configuration via manual header copying from incoming to outgoing HTTP requests.

Components NEVER bypass the global OpenTelemetry propagators configuration via manual header copying from incoming to outgoing HTTP requests.

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 PII Sanitization & Egress Redaction Policy critical for AI coding assistants?

Enforces runtime egress filtering and compile-time type boundaries on OpenTelemetry W3C Baggage context propagation. Prevents inadvertent leakage of Personally Identifiable Information (PII) and secret credentials to external distributed trace hops via HTTP baggage headers. Mandates explicit allowlisting and automated redaction interceptors on all outbound distributed context injection vectors. 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 (Propagating Unfiltered W3C Baggage Headers Containing Tenant PII to External Third-Party APIs) 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