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

OpenTelemetry W3C Baggage Sanitization and Tenant Boundary Invariant

Cross-boundary asynchronous message broker boundaries require strict sanitization and schema validation of W3C baggage entries. Propagating raw, unvalidated baggage headers leads to cross-tenant context pollution, silent PII exfiltration into distributed telemetry backends, and trace context corruption across isolation perimeters.

Prohibited Anti-Pattern: Blind Propagation of Untrusted W3C Baggage Across Async Broker Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry W3C Baggage Sanitization and Tenant Boundary Invariant - Cross-boundary asynchronous message broker boundaries require strict sanitization and schema validation of W3C baggage entries. Propagating raw, unvalidated baggage headers leads to cross-tenant context pollution, silent PII exfiltration into distributed telemetry backends, and trace context corruption across isolation perimeters.
globs: src/telemetry/**/*.ts, src/messaging/**/*.ts, src/middleware/**/*.ts, src/instrumentation/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/otel-baggage-sanitization-tenant-boundary"
---

# OpenTelemetry W3C Baggage Sanitization and Tenant Boundary Invariant

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Blind Propagation of Untrusted W3C Baggage Across Async Broker Boundaries

## System Constraints
You are a Principal Software Architect enforcing OpenTelemetry W3C Baggage Sanitization and Tenant Boundary Invariants. Mandate strict allowlist filtering, tenant identifier verification, and PII eradication before serializing or deserializing W3C baggage across message broker boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS filter incoming and outgoing W3C baggage entries against an explicit, immutable allowlist schema before cross-boundary propagation.
- Engineers MUST NOT directly serialize or deserialize raw W3C baggage headers into message broker payload metadata without verifying tenant boundary isolation.
- Code SHOULD enforce strict RFC-7230/W3C baggage key and value validation, rejecting any key containing characters outside the defined token specification.
- Services MUST extract the authenticated tenant ID from the trusted cryptographic token/session and verify it matches any inbound `tenant.id` baggage key before adopting the trace context.
- Components NEVER propagate sensitive fields (e.g., email, account numbers, IP addresses, credentials) in baggage, restricting baggage to ephemeral, low-cardinality routing metadata.

## Bad vs Good Implementations
### Baggage Sanitization and Tenant Verification Across Broker Ingestion

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly extracting baggage from raw message headers imports all external baggage items into active context without validation, causing PII leaks into traces and enabling cross-tenant context spoofing.
```typescript
import { propagation, context } from '@opentelemetry/api';
import { Message } from 'kafkajs';

export function handleIncomingMessage(message: Message): void {
  // ANTI-PATTERN: Blindly extracting carrier baggage and binding it to context
  // Propagates potential PII and unchecked tenant IDs across internal services
  const rawHeaders: Record<string, string> = {};
  for (const [key, value] of Object.entries(message.headers || {})) {
    if (value) rawHeaders[key] = value.toString();
  }

  const extractedContext = propagation.extract(context.active(), rawHeaders);
  context.with(extractedContext, () => {
    // Context contains untrusted baggage (e.g. user.email, fake tenant.id)
    processMessage(message);
  });
}
```

#### Production Standard (Correct)
> **Standard**: Filters incoming baggage entries against an immutable allowlist to eliminate telemetry PII, and asserts verified tenant identity over inbound unverified metadata to prevent tenant context spoofing.
```typescript
import { propagation, context, createBaggage, getBaggage, Baggage } from '@opentelemetry/api';
import { Message } from 'kafkajs';

const ALLOWED_BAGGAGE_KEYS = new Set(['tenant.id', 'service.tier', 'routing.region']);

export function handleIncomingMessage(message: Message, verifiedTenantId: string): void {
  const rawHeaders: Record<string, string> = {};
  for (const [key, value] of Object.entries(message.headers || {})) {
    if (value) rawHeaders[key] = value.toString();
  }

  const rawContext = propagation.extract(context.active(), rawHeaders);
  const incomingBaggage = getBaggage(rawContext);
  const sanitizedBaggageEntries: Record<string, { value: string }> = {};

  if (incomingBaggage) {
    for (const [entryKey, entryVal] of incomingBaggage.getAllEntries()) {
      if (ALLOWED_BAGGAGE_KEYS.has(entryKey)) {
        sanitizedBaggageEntries[entryKey] = entryVal;
      }
    }
  }

  // Enforce tenant boundary: verified message tenant MUST override/match baggage
  sanitizedBaggageEntries['tenant.id'] = { value: verifiedTenantId };

  const secureBaggage: Baggage = createBaggage(sanitizedBaggageEntries);
  const isolatedContext = propagation.setBaggage(rawContext, secureBaggage);

  context.with(isolatedContext, () => {
    processMessage(message);
  });
}
```

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 Sanitization and Tenant Boundary Invariant

OpenTelemetry W3C Baggage Sanitization and Tenant Boundary Invariant defines an industrial-grade behavioral standard for devops engineering. Cross-boundary asynchronous message broker boundaries require strict sanitization and schema validation of W3C baggage entries. Propagating raw, unvalidated baggage headers leads to cross-tenant context pollution, silent PII exfiltration into distributed telemetry backends, and trace context corruption across isolation perimeters. 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: Blind Propagation of Untrusted W3C Baggage Across Async Broker Boundaries 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 DriftBlind Propagation of Untrusted W3C Baggage Across Async Broker BoundariesCritical
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 filter incoming and outgoing W3C baggage entries against an explicit, immutable allowlist schema before cross-boundary propagation.

Engineers MUST ALWAYS filter incoming and outgoing W3C baggage entries against an explicit, immutable allowlist schema before cross-boundary propagation.

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 directly serialize or deserialize raw W3C baggage headers into message broker payload metadata without verifying tenant boundary isolation.

Engineers MUST NOT directly serialize or deserialize raw W3C baggage headers into message broker payload metadata without verifying tenant boundary isolation.

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

Code SHOULD enforce strict RFC-7230/W3C baggage key and value validation, rejecting any key containing characters outside the defined token specification.

Code SHOULD enforce strict RFC-7230/W3C baggage key and value validation, rejecting any key containing characters outside the defined token specification.

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 extract the authenticated tenant ID from the trusted cryptographic token/session and verify it matches any inbound `tenant.id` baggage key before adopting the trace context.

Services MUST extract the authenticated tenant ID from the trusted cryptographic token/session and verify it matches any inbound `tenant.id` baggage key before adopting the trace 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 propagate sensitive fields (e.g., email, account numbers, IP addresses, credentials) in baggage, restricting baggage to ephemeral, low-cardinality routing metadata.

Components NEVER propagate sensitive fields (e.g., email, account numbers, IP addresses, credentials) in baggage, restricting baggage to ephemeral, low-cardinality routing metadata.

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 Sanitization and Tenant Boundary Invariant critical for AI coding assistants?

Cross-boundary asynchronous message broker boundaries require strict sanitization and schema validation of W3C baggage entries. Propagating raw, unvalidated baggage headers leads to cross-tenant context pollution, silent PII exfiltration into distributed telemetry backends, and trace context corruption across isolation perimeters. 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 (Blind Propagation of Untrusted W3C Baggage Across Async Broker Boundaries) 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