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

OpenTelemetry Baggage Sanitization and Multi-Tenant Context Fencing

Enforces strict DLP and isolation guarantees by intercepting, validating, and filtering OpenTelemetry baggage items during cross-boundary propagation. Prevents cross-tenant context injection and credential leakage through unvetted distributed tracing metadata traversing zero-trust perimeter boundaries.

Prohibited Anti-Pattern: Unrestricted Passthrough of OpenTelemetry Baggage Across Multi-Tenant Network Perimeters

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry Baggage Sanitization and Multi-Tenant Context Fencing - Enforces strict DLP and isolation guarantees by intercepting, validating, and filtering OpenTelemetry baggage items during cross-boundary propagation. Prevents cross-tenant context injection and credential leakage through unvetted distributed tracing metadata traversing zero-trust perimeter boundaries.
globs: src/telemetry/**/*.{ts,js}, src/middleware/**/*.{ts,js}, src/instrumentation/**/*.{ts,js}, src/tracing/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/otel-baggage-filtering-tenant-fencing"
---

# OpenTelemetry Baggage Sanitization and Multi-Tenant Context Fencing

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unrestricted Passthrough of OpenTelemetry Baggage Across Multi-Tenant Network Perimeters

## System Constraints
You are a Principal Software Architect specializing in Cloud-Native Observability and Zero-Trust Security. Your mission is to strictly mandate OpenTelemetry baggage sanitization, cryptographic validation of tenant fencing headers, and strict allowlisting of propagated context keys across all external and cross-service HTTP/gRPC boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS implement a custom OpenTelemetry TextMapPropagator wrapper that strips any baggage entries not explicitly declared in an immutable strict allowlist.
- Engineers MUST NEVER propagate raw authorization tokens, PII, internal IP addresses, or unvalidated tenant identifiers via the W3C Baggage header across trust boundaries.
- Services MUST validate that the propagated `tenant.id` matches the cryptographically verified identity extracted from the inbound JWT/mTLS context before accepting downstream baggage.
- Components NEVER blindly merge incoming W3C baggage headers into local tracer execution context without explicit schema validation and key/value length constraints (max 32 keys, max 256 bytes per value).
- Code SHOULD record audit security events or increment drop metrics (`otel.baggage.dropped_entries_total`) when unauthorized baggage keys or oversized values are purged at perimeter boundaries.

## Bad vs Good Implementations
### Unsanitized Baggage Injection vs Allowlist-Fenced Baggage Propagator

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The propagator blindly serializes and deserializes the entire W3C Baggage header. An attacker or untrusted upstream caller can inject spoofed `tenant.id` values, bypass access control guards, or leak sensitive authorization secrets across trust boundaries.
```typescript
import { Context, TextMapPropagator, TextMapSetter, defaultTextMapGetter, defaultTextMapSetter, baggage } from '@opentelemetry/api';
import { W3CBaggagePropagator } from '@opentelemetry/core';

// ANTI-PATTERN: Direct propagation of inbound headers without validation or filtering
export class UnsafeProxyPropagator implements TextMapPropagator {
  private wrapped = new W3CBaggagePropagator();

  inject(context: Context, carrier: unknown, setter: TextMapSetter): void {
    // Blindly serializes any arbitrary context keys injected upstream,
    // leaking internal auth tokens, tenant overrides, or PII downstream.
    this.wrapped.inject(context, carrier, setter);
  }

  extract(context: Context, carrier: unknown): Context {
    // Ingests untrusted baggage without tenant fence verification
    return this.wrapped.extract(context, carrier, defaultTextMapGetter);
  }

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

#### Production Standard (Correct)
> **Standard**: Implements an explicit allowlist propagator (`FencedBaggagePropagator`) that strictly enforces allowed keys and max value length boundaries during both injection and extraction. Non-whitelisted baggage items, arbitrary headers, and oversized payloads are discarded before crossing network boundaries.
```typescript
import { Context, TextMapPropagator, TextMapSetter, TextMapGetter, defaultTextMapGetter, baggage } from '@opentelemetry/api';
import { W3CBaggagePropagator } from '@opentelemetry/core';

const ALLOWED_BAGGAGE_KEYS = new Set(['tenant.id', 'request.correlation_id', 'traffic.shard']);
const MAX_VALUE_LENGTH = 128;

export class FencedBaggagePropagator implements TextMapPropagator {
  private basePropagator = new W3CBaggagePropagator();

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

    let sanitizedBaggage = baggage.createBaggage();
    for (const [key, entry] of activeBaggage.getAllEntries()) {
      if (ALLOWED_BAGGAGE_KEYS.has(key) && entry.value.length <= MAX_VALUE_LENGTH) {
        sanitizedBaggage = sanitizedBaggage.setEntry(key, entry);
      }
    }

    const sanitizedContext = baggage.setBaggage(context, sanitizedBaggage);
    this.basePropagator.inject(sanitizedContext, carrier, setter);
  }

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

    let fencedBaggage = baggage.createBaggage();
    for (const [key, entry] of rawBaggage.getAllEntries()) {
      if (ALLOWED_BAGGAGE_KEYS.has(key) && entry.value.length <= MAX_VALUE_LENGTH) {
        fencedBaggage = fencedBaggage.setEntry(key, { value: entry.value.trim() });
      }
    }

    return baggage.setBaggage(context, fencedBaggage);
  }

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenTelemetry Baggage Sanitization and Multi-Tenant Context Fencing

OpenTelemetry Baggage Sanitization and Multi-Tenant Context Fencing defines an industrial-grade behavioral standard for devops engineering. Enforces strict DLP and isolation guarantees by intercepting, validating, and filtering OpenTelemetry baggage items during cross-boundary propagation. Prevents cross-tenant context injection and credential leakage through unvetted distributed tracing metadata traversing zero-trust perimeter boundaries. 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 Passthrough of OpenTelemetry Baggage Across Multi-Tenant Network Perimeters 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 Passthrough of OpenTelemetry Baggage Across Multi-Tenant Network PerimetersCritical
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 a custom OpenTelemetry TextMapPropagator wrapper that strips any baggage entries not explicitly declared in an immutable strict allowlist.

Engineers MUST ALWAYS implement a custom OpenTelemetry TextMapPropagator wrapper that strips any baggage entries not explicitly declared in an immutable strict allowlist.

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 NEVER propagate raw authorization tokens, PII, internal IP addresses, or unvalidated tenant identifiers via the W3C Baggage header across trust boundaries.

Engineers MUST NEVER propagate raw authorization tokens, PII, internal IP addresses, or unvalidated tenant identifiers via the W3C Baggage header across trust boundaries.

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 validate that the propagated `tenant.id` matches the cryptographically verified identity extracted from the inbound JWT/mTLS context before accepting downstream baggage.

Services MUST validate that the propagated `tenant.id` matches the cryptographically verified identity extracted from the inbound JWT/mTLS context before accepting downstream 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.
4

Components NEVER blindly merge incoming W3C baggage headers into local tracer execution context without explicit schema validation and key/value length constraints (max 32 keys, max 256 bytes per value).

Components NEVER blindly merge incoming W3C baggage headers into local tracer execution context without explicit schema validation and key/value length constraints (max 32 keys, max 256 bytes per value).

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

Code SHOULD record audit security events or increment drop metrics (`otel.baggage.dropped_entries_total`) when unauthorized baggage keys or oversized values are purged at perimeter boundaries.

Code SHOULD record audit security events or increment drop metrics (`otel.baggage.dropped_entries_total`) when unauthorized baggage keys or oversized values are purged at perimeter boundaries.

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 Sanitization and Multi-Tenant Context Fencing critical for AI coding assistants?

Enforces strict DLP and isolation guarantees by intercepting, validating, and filtering OpenTelemetry baggage items during cross-boundary propagation. Prevents cross-tenant context injection and credential leakage through unvetted distributed tracing metadata traversing zero-trust perimeter boundaries. 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 Passthrough of OpenTelemetry Baggage Across Multi-Tenant Network Perimeters) 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