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

OpenTelemetry W3C Baggage PII Boundary and Propagation Guardrail

Enforces strict compile-time schema validation and runtime redaction filters on OpenTelemetry W3C Baggage propagation across network boundaries. Prevents catastrophic compliance violations (GDPR, HIPAA, PCI-DSS) caused by leaking unsanitized user identity and sensitive contextual metadata down distributed trace graphs. Mandates custom TextMapPropagators with strict allowlists and automated entropy/pattern redaction.

Prohibited Anti-Pattern: Unrestricted Propagation of Sensitive User Identity and Raw Context Keys in Outgoing W3C Baggage Headers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry W3C Baggage PII Boundary and Propagation Guardrail - Enforces strict compile-time schema validation and runtime redaction filters on OpenTelemetry W3C Baggage propagation across network boundaries. Prevents catastrophic compliance violations (GDPR, HIPAA, PCI-DSS) caused by leaking unsanitized user identity and sensitive contextual metadata down distributed trace graphs. Mandates custom TextMapPropagators with strict allowlists and automated entropy/pattern redaction.
globs: src/telemetry/**/*.{ts,js}, src/instrumentation/**/*.{ts,js}, src/middleware/**/*.{ts,js}, src/tracing/**/*.{ts,js}, src/lib/observability/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/otel-w3c-baggage-pii-boundary-guardrail"
---

# OpenTelemetry W3C Baggage PII Boundary and Propagation Guardrail

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unrestricted Propagation of Sensitive User Identity and Raw Context Keys in Outgoing W3C Baggage Headers

## System Constraints
You are a Principal Observability & Security Architect enforcing strict OpenTelemetry W3C Baggage boundary controls. Never allow arbitrary, dynamic, or unredacted metadata into baggage contexts. Baggage propagates downstream across public/private service boundaries without encryption by default; therefore, treat all baggage injections as public network egress points. Enforce explicit allowlists, strict structural schemas, cryptographic tokenization, and runtime sanitization on all OpenTelemetry TextMapPropagator implementations.

## Strict Guidelines
- Engineers MUST ALWAYS enforce an immutable, explicit allowlist of keys permitted to be injected into or extracted from W3C Baggage.
- Engineers MUST NOT inject raw PII, sensitive customer identifiers (e.g., email, SSN, raw customer_id, IP addresses), authentication tokens, or session IDs into OpenTelemetry Baggage.
- Services MUST wrap standard W3C Baggage propagators with custom sanitizing propagators that validate types, lengths, and regex patterns against compile-time schemas.
- Engineers MUST use opaque, ephemeral routing tokens or pseudonymized hash digests instead of stable internal business entities when passing boundary context.
- Components NEVER accept raw, incoming baggage headers without immediate schema validation, strict truncation, and automated removal of unapproved foreign baggage keys.

## Bad vs Good Implementations
### W3C Baggage Injection with Compile-Time Allowed Keys vs Unsanitized Context Leaks

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly injecting raw PII like 'user.email' and internal IDs into W3C Baggage causes distributed compliance breaches. W3C Baggage is transmitted via plain text HTTP headers ('baggage: user.email=...') to third-party services, microservices, and downstream logs without encryption or boundary filtration.
```typescript
import { propagation, context } from '@opentelemetry/api';

// ANTI-PATTERN: Directly dumping unverified user request data into distributed Baggage
export function attachRequestContext(req: { userEmail: string; userId: string; tenantId: string }) {
  const currentBaggage = propagation.getBaggage(context.active()) || propagation.createBaggage();
  
  // CRITICAL VIOLATION: Injecting raw PII into baggage that propagates out across untrusted network hops
  const dangerousBaggage = currentBaggage
    .setEntry('user.email', { value: req.userEmail })
    .setEntry('user.id', { value: req.userId })
    .setEntry('tenant.id', { value: req.tenantId });

  return propagation.setBaggage(context.active(), dangerousBaggage);
}
```

#### Production Standard (Correct)
> **Standard**: Enforces a strict compile-time allowlist and sanitizes inputs before insertion into baggage. Raw PII (e.g. user IDs, emails) is never exposed directly; internal IDs are deterministically pseudonymized with cryptographic hashing, and contextual fields are scrubbed against malicious character injection and length limits.
```typescript
import { propagation, context, Baggage, BaggageEntry } from '@opentelemetry/api';
import { createHash } from 'node:crypto';

// STRICT: Compile-time schema for allowed boundary propagation keys
export const ALLOWED_BAGGAGE_KEYS = ['app.tenant_id', 'app.routing_shard', 'app.user_pseudoid'] as const;
export type AllowedBaggageKey = typeof ALLOWED_BAGGAGE_KEYS[number];

interface SafeBaggageContext {
  tenantId: string;
  routingShard: string;
  userId: string;
}

// Tokenize and validate identifiers against strict schemas
function toPseudonymizedHash(value: string, salt: string): string {
  return createHash('sha256').update(`${salt}:${value}`).digest('hex').substring(0, 16);
}

export function attachSafeRequestContext(ctx: SafeBaggageContext, hashSalt: string) {
  let safeBaggage: Baggage = propagation.createBaggage();

  // Strictly enforce allowed keys and tokenized, non-PII values
  const validatedEntries: Record<AllowedBaggageKey, string> = {
    'app.tenant_id': ctx.tenantId.replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 36),
    'app.routing_shard': ctx.routingShard.replace(/[^a-zA-Z0-9]/g, '').slice(0, 8),
    'app.user_pseudoid': toPseudonymizedHash(ctx.userId, hashSalt)
  };

  for (const [key, value] of Object.entries(validatedEntries) as [AllowedBaggageKey, string][]) {
    safeBaggage = safeBaggage.setEntry(key, { value });
  }

  return propagation.setBaggage(context.active(), safeBaggage);
}
```

### Custom Propagator with Boundary Redaction Filtering

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Default W3CBaggagePropagator propagates any key-value pairs stored in the trace context directly into outgoing HTTP headers. Untrusted upstream baggage or accidentally added internal secrets will leak unhindered to third-party APIs and downstream services.
```typescript
import { W3CBaggagePropagator } from '@opentelemetry/core';
import { Context, TextMapSetter } from '@opentelemetry/api';

// ANTI-PATTERN: Using raw default W3CBaggagePropagator with no egress filter
export const propagator = new W3CBaggagePropagator();

export function injectHeaders(ctx: Context, carrier: Record<string, string>, setter: TextMapSetter) {
  // Forwards all upstream and downstream baggage indiscriminately across network boundaries
  propagator.inject(ctx, carrier, setter);
}
```

#### Production Standard (Correct)
> **Standard**: Implements an egress/ingress BoundaryFilteredBaggagePropagator that decorates W3CBaggagePropagator. It guarantees that on injection and extraction, only pre-approved keys pass across boundaries and limits max payload size, stripping unvalidated context keys before they hit wire transports.
```typescript
import { TextMapPropagator, Context, TextMapSetter, TextMapGetter, propagation } from '@opentelemetry/api';
import { W3CBaggagePropagator } from '@opentelemetry/core';
import { ALLOWED_BAGGAGE_KEYS } from './constants';

export class BoundaryFilteredBaggagePropagator implements TextMapPropagator {
  private readonly delegate = new W3CBaggagePropagator();

  inject(context: Context, carrier: unknown, setter: TextMapSetter): void {
    const activeBaggage = propagation.getBaggage(context);
    if (!activeBaggage) return;

    // Filter active baggage to only permitted boundary keys
    let sanitizedBaggage = propagation.createBaggage();
    for (const allowedKey of ALLOWED_BAGGAGE_KEYS) {
      const entry = activeBaggage.getEntry(allowedKey);
      if (entry && entry.value.length <= 128) {
        sanitizedBaggage = sanitizedBaggage.setEntry(allowedKey, entry);
      }
    }

    const filteredContext = propagation.setBaggage(context, sanitizedBaggage);
    this.delegate.inject(filteredContext, carrier, setter);
  }

  extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {
    const extractedContext = this.delegate.extract(context, carrier, getter);
    const rawBaggage = propagation.getBaggage(extractedContext);
    if (!rawBaggage) return extractedContext;

    // Strip foreign unapproved baggage on ingress
    let ingressFilteredBaggage = propagation.createBaggage();
    for (const allowedKey of ALLOWED_BAGGAGE_KEYS) {
      const entry = rawBaggage.getEntry(allowedKey);
      if (entry) {
        ingressFilteredBaggage = ingressFilteredBaggage.setEntry(allowedKey, entry);
      }
    }

    return propagation.setBaggage(extractedContext, ingressFilteredBaggage);
  }

  fields(): string[] {
    return this.delegate.fields();
  }
}
```

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 Baggage PII Boundary and Propagation Guardrail

OpenTelemetry W3C Baggage PII Boundary and Propagation Guardrail defines an industrial-grade behavioral standard for devops engineering. Enforces strict compile-time schema validation and runtime redaction filters on OpenTelemetry W3C Baggage propagation across network boundaries. Prevents catastrophic compliance violations (GDPR, HIPAA, PCI-DSS) caused by leaking unsanitized user identity and sensitive contextual metadata down distributed trace graphs. Mandates custom TextMapPropagators with strict allowlists and automated entropy/pattern redaction. 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: Unrestricted Propagation of Sensitive User Identity and Raw Context Keys in Outgoing W3C Baggage Headers 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 DriftUnrestricted Propagation of Sensitive User Identity and Raw Context Keys in Outgoing W3C Baggage HeadersCritical
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 enforce an immutable, explicit allowlist of keys permitted to be injected into or extracted from W3C Baggage.

Engineers MUST ALWAYS enforce an immutable, explicit allowlist of keys permitted to be injected into or extracted from 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 inject raw PII, sensitive customer identifiers (e.g., email, SSN, raw customer_id, IP addresses), authentication tokens, or session IDs into OpenTelemetry Baggage.

Engineers MUST NOT inject raw PII, sensitive customer identifiers (e.g., email, SSN, raw customer_id, IP addresses), authentication tokens, or session IDs 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 wrap standard W3C Baggage propagators with custom sanitizing propagators that validate types, lengths, and regex patterns against compile-time schemas.

Services MUST wrap standard W3C Baggage propagators with custom sanitizing propagators that validate types, lengths, and regex patterns against compile-time schemas.

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

Engineers MUST use opaque, ephemeral routing tokens or pseudonymized hash digests instead of stable internal business entities when passing boundary context.

Engineers MUST use opaque, ephemeral routing tokens or pseudonymized hash digests instead of stable internal business entities when passing boundary context.

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 accept raw, incoming baggage headers without immediate schema validation, strict truncation, and automated removal of unapproved foreign baggage keys.

Components NEVER accept raw, incoming baggage headers without immediate schema validation, strict truncation, and automated removal of unapproved foreign baggage keys.

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 Boundary and Propagation Guardrail critical for AI coding assistants?

Enforces strict compile-time schema validation and runtime redaction filters on OpenTelemetry W3C Baggage propagation across network boundaries. Prevents catastrophic compliance violations (GDPR, HIPAA, PCI-DSS) caused by leaking unsanitized user identity and sensitive contextual metadata down distributed trace graphs. Mandates custom TextMapPropagators with strict allowlists and automated entropy/pattern redaction. 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 (Unrestricted Propagation of Sensitive User Identity and Raw Context Keys in Outgoing W3C Baggage Headers) 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