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

OpenTelemetry Baggage Boundary & Cryptographic PII Redaction Standard

Mandates strict schema validation, allowlist enforcement, and deterministic cryptographic pseudonymization for OpenTelemetry distributed baggage at trust and tenant boundaries. Prevents uncontrolled egress and lateral propagation of sensitive personal data (PII/PHI) through distributed trace context propagators.

Prohibited Anti-Pattern: Transparent Pass-Through and Plaintext PII Injection into Distributed OpenTelemetry Baggage Context

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry Baggage Boundary & Cryptographic PII Redaction Standard - Mandates strict schema validation, allowlist enforcement, and deterministic cryptographic pseudonymization for OpenTelemetry distributed baggage at trust and tenant boundaries. Prevents uncontrolled egress and lateral propagation of sensitive personal data (PII/PHI) through distributed trace context propagators.
globs: src/telemetry/**/*.{ts,js}, src/middleware/**/*.{ts,js}, src/gateway/**/*.{ts,js}, src/tracing/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/otel-baggage-pii-boundary-guardrail"
---

# OpenTelemetry Baggage Boundary & Cryptographic PII Redaction Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Transparent Pass-Through and Plaintext PII Injection into Distributed OpenTelemetry Baggage Context

## System Constraints
You are a Principal Security Architect enforcing Zero-Trust Distributed Tracing architectures. In OpenTelemetry ecosystems, W3C Baggage flows across microservice boundaries unencrypted by default. You MUST enforce deterministic cryptographic hashing (HMAC-SHA256) of tenant-bound user references and an absolute schema allowlist at all ingress and egress boundaries. Code violating context segregation or injecting plaintext PII into OpenTelemetry Baggage MUST be rejected immediately.

## Strict Guidelines
- Services MUST NOT inject raw Personally Identifiable Information (such as email addresses, government IDs, phone numbers, or IP addresses) into OpenTelemetry Baggage via propagation.setBaggage().
- Gateway and edge boundary filters MUST intercept incoming 'baggage' headers and strip any key not explicitly registered in an immutable context allowlist before passing downstream.
- Any user or account identifier propagating in baggage MUST be pseudonymized using HMAC-SHA256 keyed with a tenant-scoped rotary secret.
- Egress interceptors MUST strip internal routing or tenant baggage metadata before propagating requests across trust boundaries to third-party APIs or untrusted external endpoints.
- Custom TextMapPropagator implementations MUST reject individual baggage entries exceeding 256 bytes or baggage headers exceeding 8192 bytes to mitigate context exhaustion denial-of-service.

## Bad vs Good Implementations
### Baggage Ingestion and Egress Propagation at Gateway Boundary

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly injects plaintext personal data (user email, authorization tokens) into W3C baggage, and blindly propagates all incoming unvalidated baggage headers downstream, causing cross-tenant PII leakage and trace context pollution.
```typescript
import { propagation, context, defaultTextMapSetter } from '@opentelemetry/api';
import { Request, Response, NextFunction } from 'express';

export function tracingMiddleware(req: Request, res: Response, next: NextFunction) {
  // ANTI-PATTERN: Ingesting untrusted baggage verbatim and appending raw PII
  let currentContext = propagation.extract(context.active(), req.headers);

  const rawUserEmail = req.headers['x-user-email'] as string;
  const rawUserId = req.headers['x-user-id'] as string;

  // Directly injects raw tenant PII into global baggage
  currentContext = propagation.setBaggage(
    currentContext,
    propagation.createBaggage({
      'user.email': { value: rawUserEmail },
      'user.id': { value: rawUserId },
      'tenant.raw_token': { value: req.headers['authorization'] as string }
    })
  );

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

#### Production Standard (Correct)
> **Standard**: Enforces a strict allowlist on inbound baggage keys, limits payload size to mitigate DoS, and passes user identifiers only after HMAC-SHA256 pseudonymization, preventing PII egress across distributed traces.
```typescript
import { propagation, context, Baggage, BaggageEntry } from '@opentelemetry/api';
import { createHmac } from 'crypto';
import { Request, Response, NextFunction } from 'express';

const ALLOWED_BAGGAGE_KEYS = new Set(['tenant.id', 'service.tier', 'routing.region']);
const BAGGAGE_MAX_BYTES = 256;
const HMAC_SECRET = process.env.TELEMETRY_PSEUDONYMIZATION_SECRET || '';

function pseudonymize(value: string): string {
  return createHmac('sha256', HMAC_SECRET).update(value).digest('hex').substring(0, 32);
}

export function secureBoundaryBaggageMiddleware(req: Request, res: Response, next: NextFunction): void {
  const extractedContext = propagation.extract(context.active(), req.headers);
  const incomingBaggage = propagation.getBaggage(extractedContext);
  
  const sanitizedEntries: Record<string, BaggageEntry> = {};

  // Enforce allowlist filtering on incoming baggage
  if (incomingBaggage) {
    for (const [key, entry] of incomingBaggage.getAllEntries()) {
      if (ALLOWED_BAGGAGE_KEYS.has(key) && entry.value.length <= BAGGAGE_MAX_BYTES) {
        sanitizedEntries[key] = entry;
      }
    }
  }

  // Cryptographically pseudonymize identities before setting context
  const rawUserId = req.headers['x-user-id'];
  if (typeof rawUserId === 'string' && rawUserId.length > 0) {
    sanitizedEntries['user.pseudo_id'] = {
      value: pseudonymize(rawUserId)
    };
  }

  const cleanBaggage = propagation.createBaggage(sanitizedEntries);
  const secureContext = propagation.setBaggage(context.active(), cleanBaggage);

  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 Baggage Boundary & Cryptographic PII Redaction Standard

OpenTelemetry Baggage Boundary & Cryptographic PII Redaction Standard defines an industrial-grade behavioral standard for security engineering. Mandates strict schema validation, allowlist enforcement, and deterministic cryptographic pseudonymization for OpenTelemetry distributed baggage at trust and tenant boundaries. Prevents uncontrolled egress and lateral propagation of sensitive personal data (PII/PHI) through distributed trace context propagators. 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: Transparent Pass-Through and Plaintext PII Injection into Distributed OpenTelemetry Baggage Context 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 DriftTransparent Pass-Through and Plaintext PII Injection into Distributed OpenTelemetry Baggage ContextCritical
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 NOT inject raw Personally Identifiable Information (such as email addresses, government IDs, phone numbers, or IP addresses) into OpenTelemetry Baggage via propagation.setBaggage().

Services MUST NOT inject raw Personally Identifiable Information (such as email addresses, government IDs, phone numbers, or IP addresses) into OpenTelemetry Baggage via propagation.setBaggage().

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

Gateway and edge boundary filters MUST intercept incoming 'baggage' headers and strip any key not explicitly registered in an immutable context allowlist before passing downstream.

Gateway and edge boundary filters MUST intercept incoming 'baggage' headers and strip any key not explicitly registered in an immutable context allowlist before passing downstream.

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

Any user or account identifier propagating in baggage MUST be pseudonymized using HMAC-SHA256 keyed with a tenant-scoped rotary secret.

Any user or account identifier propagating in baggage MUST be pseudonymized using HMAC-SHA256 keyed with a tenant-scoped rotary secret.

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

Egress interceptors MUST strip internal routing or tenant baggage metadata before propagating requests across trust boundaries to third-party APIs or untrusted external endpoints.

Egress interceptors MUST strip internal routing or tenant baggage metadata before propagating requests across trust boundaries to third-party APIs or untrusted external endpoints.

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

Custom TextMapPropagator implementations MUST reject individual baggage entries exceeding 256 bytes or baggage headers exceeding 8192 bytes to mitigate context exhaustion denial-of-service.

Custom TextMapPropagator implementations MUST reject individual baggage entries exceeding 256 bytes or baggage headers exceeding 8192 bytes to mitigate context exhaustion 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is OpenTelemetry Baggage Boundary & Cryptographic PII Redaction Standard critical for AI coding assistants?

Mandates strict schema validation, allowlist enforcement, and deterministic cryptographic pseudonymization for OpenTelemetry distributed baggage at trust and tenant boundaries. Prevents uncontrolled egress and lateral propagation of sensitive personal data (PII/PHI) through distributed trace context propagators. 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 (Transparent Pass-Through and Plaintext PII Injection into Distributed OpenTelemetry Baggage Context) 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