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

OpenTelemetry Ingress Baggage Sanitization & Strict PII Redaction Boundary

Enforces boundary verification and deterministic key allowlisting on all incoming OpenTelemetry Baggage contexts. Prevents cross-tenant context injection, unauthorized privilege escalation via telemetry metadata, and inadvertent transit of PII or credentials down distributed service call chains.

Prohibited Anti-Pattern: Trusting Ingress W3C Baggage Headers Blindly Without Allowlist Filtering or Cryptographic Verification

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry Ingress Baggage Sanitization & Strict PII Redaction Boundary - Enforces boundary verification and deterministic key allowlisting on all incoming OpenTelemetry Baggage contexts. Prevents cross-tenant context injection, unauthorized privilege escalation via telemetry metadata, and inadvertent transit of PII or credentials down distributed service call chains.
globs: src/telemetry/**/*.{ts,js}, src/middleware/**/*.{ts,js}, src/tracing/**/*.{ts,js}, src/server/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/otel-baggage-ingress-sanitization-pii-boundary"
---

# OpenTelemetry Ingress Baggage Sanitization & Strict PII Redaction Boundary

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Trusting Ingress W3C Baggage Headers Blindly Without Allowlist Filtering or Cryptographic Verification

## System Constraints
You are a Principal Software Architect enforcing zero-trust OpenTelemetry context propagation. Mandate strict allowlisting, sanitization, and immutable tenant isolation across all W3C Baggage ingress points. You must reject any raw ingestion of inbound baggage headers, enforce zero-PII propagation boundaries, and ensure identity claims originate exclusively from verified cryptographic tokens.

## Strict Guidelines
- Services MUST NEVER accept incoming W3C `baggage` headers directly into active tracing context without passing through an explicit key allowlist filter.
- Engineers MUST ALWAYS strip and overwrite identity-critical baggage entries (such as `tenant_id`, `account_id`, `user_id`, or `role`) using verified cryptographic claims from mutual TLS or validated JWT payloads.
- Middleware MUST scrub any baggage key or value containing high-entropy strings, JWT signatures, session tokens, or patterns matching PII (e.g., email addresses, credit cards, or UUIDs that map to raw user identities).
- Services MUST enforce strict length constraints (maximum 64 bytes per key, 256 bytes per value, maximum 10 total baggage entries) on incoming baggage to prevent header-bloat denial of service.
- Telemetry interceptors SHOULD log dropped, mutated, or rejected baggage keys as security-relevant observability metrics (`telemetry.baggage.dropped_keys_count`) without logging the dropped payload values.
- Components NEVER propagate client-supplied downstream baggage entries to external third-party API integrations or unauthenticated external webhook targets.

## Bad vs Good Implementations
### Ingress Baggage Sanitization & Tenant Isolation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly extracting baggage into the active context without sanitization allows cross-tenant context injection, downstream spoofing, and propagation of sensitive tokens or unverified claims.
```typescript
import { Request, Response, NextFunction } from 'express';
import { context, propagation } from '@opentelemetry/api';

export function otelTracingMiddleware(req: Request, res: Response, next: NextFunction): void {
  // VULNERABLE: Direct extraction accepts arbitrary caller-supplied baggage.
  // Malicious clients can inject 'tenant_id=victim_corp' or leak 'auth_token=bearer...'
  // directly into downstream microservice contexts and span attributes.
  const extractedContext = propagation.extract(context.active(), req.headers);

  context.with(extractedContext, () => {
    next();
  });
}
```

#### Production Standard (Correct)
> **Standard**: Filters incoming baggage against a strict set of non-sensitive keys, validates string boundaries, checks for token patterns, and deterministically injects verified tenant claims from authenticated server state.
```typescript
import { Request, Response, NextFunction } from 'express';
import { context, propagation, baggageEntryMetadataEmpty } from '@opentelemetry/api';

const PERMITTED_BAGGAGE_KEYS = new Set<string>([
  'traffic_source',
  'experiment_id',
  'routing_cell'
]);

const PII_OR_SECRET_PATTERN = /bearer|token|secret|password|key|@|[0-9]{3}-[0-9]{2}-[0-9]{4}/i;

export function secureOtelBaggageMiddleware(req: Request, res: Response, next: NextFunction): void {
  // 1. Extract raw context from wire
  const rawContext = propagation.extract(context.active(), req.headers);
  const rawBaggage = propagation.getBaggage(rawContext);

  // 2. Build sanitized baggage container
  let sanitizedBaggage = propagation.createBaggage();

  if (rawBaggage) {
    for (const [key, entry] of rawBaggage.getAllEntries()) {
      // Enforce allowlist, size limits, and heuristic PII redaction
      if (
        PERMITTED_BAGGAGE_KEYS.has(key) &&
        key.length <= 64 &&
        entry.value.length <= 256 &&
        !PII_OR_SECRET_PATTERN.test(entry.value)
      ) {
        sanitizedBaggage = sanitizedBaggage.setEntry(key, entry);
      }
    }
  }

  // 3. Immutably set verified security boundaries from authenticated request
  // Assuming req.verifiedAuth was populated by prior cryptographically secure JWT/mTLS verification
  if (req.verifiedAuth?.tenantId) {
    sanitizedBaggage = sanitizedBaggage.setEntry('tenant_id', {
      value: req.verifiedAuth.tenantId,
      metadata: baggageEntryMetadataEmpty()
    });
  }

  // 4. Bind sanitized baggage back onto the active context chain
  const cleanContext = propagation.setBaggage(rawContext, 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 Ingress Baggage Sanitization & Strict PII Redaction Boundary

OpenTelemetry Ingress Baggage Sanitization & Strict PII Redaction Boundary defines an industrial-grade behavioral standard for devops engineering. Enforces boundary verification and deterministic key allowlisting on all incoming OpenTelemetry Baggage contexts. Prevents cross-tenant context injection, unauthorized privilege escalation via telemetry metadata, and inadvertent transit of PII or credentials down distributed service call chains. 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: Trusting Ingress W3C Baggage Headers Blindly Without Allowlist Filtering or Cryptographic Verification 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 DriftTrusting Ingress W3C Baggage Headers Blindly Without Allowlist Filtering or Cryptographic VerificationCritical
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 accept incoming W3C `baggage` headers directly into active tracing context without passing through an explicit key allowlist filter.

Services MUST NEVER accept incoming W3C `baggage` headers directly into active tracing context without passing through an explicit key allowlist filter.

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 ALWAYS strip and overwrite identity-critical baggage entries (such as `tenant_id`, `account_id`, `user_id`, or `role`) using verified cryptographic claims from mutual TLS or validated JWT payloads.

Engineers MUST ALWAYS strip and overwrite identity-critical baggage entries (such as `tenant_id`, `account_id`, `user_id`, or `role`) using verified cryptographic claims from mutual TLS or validated JWT payloads.

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

Middleware MUST scrub any baggage key or value containing high-entropy strings, JWT signatures, session tokens, or patterns matching PII (e.g., email addresses, credit cards, or UUIDs that map to raw user identities).

Middleware MUST scrub any baggage key or value containing high-entropy strings, JWT signatures, session tokens, or patterns matching PII (e.g., email addresses, credit cards, or UUIDs that map to raw user identities).

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 length constraints (maximum 64 bytes per key, 256 bytes per value, maximum 10 total baggage entries) on incoming baggage to prevent header-bloat denial of service.

Services MUST enforce strict length constraints (maximum 64 bytes per key, 256 bytes per value, maximum 10 total baggage entries) on incoming baggage to prevent header-bloat denial of service.

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 SHOULD log dropped, mutated, or rejected baggage keys as security-relevant observability metrics (`telemetry.baggage.dropped_keys_count`) without logging the dropped payload values.

Telemetry interceptors SHOULD log dropped, mutated, or rejected baggage keys as security-relevant observability metrics (`telemetry.baggage.dropped_keys_count`) without logging the dropped payload values.

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 propagate client-supplied downstream baggage entries to external third-party API integrations or unauthenticated external webhook targets.

Components NEVER propagate client-supplied downstream baggage entries to external third-party API integrations or unauthenticated external webhook targets.

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 Ingress Baggage Sanitization & Strict PII Redaction Boundary critical for AI coding assistants?

Enforces boundary verification and deterministic key allowlisting on all incoming OpenTelemetry Baggage contexts. Prevents cross-tenant context injection, unauthorized privilege escalation via telemetry metadata, and inadvertent transit of PII or credentials down distributed service call chains. 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 (Trusting Ingress W3C Baggage Headers Blindly Without Allowlist Filtering or Cryptographic Verification) 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