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

OpenTelemetry W3C Baggage Cross-Tenant Isolation and Propagation Sanitizer

Enforces strict boundary sanitization on W3C Baggage headers across microservice ingress and egress filters to prevent tenant spoofing, authorization bypass, and metadata leakage. Untrusted incoming baggage keys representing tenant identity, customer scope, or authorization claims must be dropped or re-validated against cryptographically signed session tokens before propagation. Downstream egress proxies must strictly whitelist contextual metadata keys to avoid exfiltrating internal partition topologies.

Prohibited Anti-Pattern: Blind Ingress/Egress Propagation of W3C Baggage Containing Unsanitized Tenant Identifiers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry W3C Baggage Cross-Tenant Isolation and Propagation Sanitizer - Enforces strict boundary sanitization on W3C Baggage headers across microservice ingress and egress filters to prevent tenant spoofing, authorization bypass, and metadata leakage. Untrusted incoming baggage keys representing tenant identity, customer scope, or authorization claims must be dropped or re-validated against cryptographically signed session tokens before propagation. Downstream egress proxies must strictly whitelist contextual metadata keys to avoid exfiltrating internal partition topologies.
globs: src/middleware/**/*.{ts,js,go,py}, src/telemetry/**/*.{ts,js,go,py}, src/instrumentation/**/*.{ts,js,go,py}, src/gateway/**/*.{ts,js,go,py}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/otel-w3c-baggage-tenant-isolation-filter"
---

# OpenTelemetry W3C Baggage Cross-Tenant Isolation and Propagation Sanitizer

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Blind Ingress/Egress Propagation of W3C Baggage Containing Unsanitized Tenant Identifiers

## System Constraints
You are a Principal Security and Observability Architect enforcing OpenTelemetry W3C Baggage Cross-Tenant Isolation. Mandate strict cryptographic verification and boundary filtering of distributed context baggage before tracing propagators serialize or deserialize state. Ensure that tenant identifiers (e.g., tenant_id, org_id) are never blindly hydrated from untrusted inbound baggage headers.

## Strict Guidelines
- Engineers MUST ALWAYS strip and recompute tenant-identifying baggage items (e.g., 'tenant_id', 'org_id', 'account_id') at the ingress perimeter using authenticated JWT claims or mTLS identities.
- Engineers MUST NOT use default OpenTelemetry W3CBaggagePropagator in multi-tenant environments without a custom BaggageFilter or TextMapPropagator interceptor that enforces key allowlists.
- Code MUST explicitly drop any baggage entries where key lengths exceed 256 bytes, values exceed 4096 bytes, or keys violate strict regex compliance `^[a-z0-9_.-]+$`.
- Egress proxies MUST sanitize outbound W3C baggage headers to external third-party services, completely removing internal tenant routing metadata, cluster IDs, and customer tier flags.
- Services MUST log a security-audited warning and emit a metric counter (e.g., `telemetry.baggage.dropped_untrusted_tenant`) whenever an unauthenticated tenant context mutation attempt is detected.

## Bad vs Good Implementations
### Ingress Baggage Sanitization and Allowlist Propagation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly extracting baggage from HTTP headers without filtering permits untrusted callers to spoof tenant IDs and access roles, poisoning the OpenTelemetry distributed context across the entire internal service mesh.
```typescript
import { baggage, context, defaultTextMapGetter, propagation } from '@opentelemetry/api';
import { Request, Response, NextFunction } from 'express';

export function tracingMiddleware(req: Request, res: Response, next: NextFunction): void {
  // Anti-pattern: Blindly extracts untrusted inbound W3C baggage.
  // An attacker can inject 'baggage: tenant_id=compromised-corp,role=admin'
  // and internal downstream microservices reading baggage will trust this identity.
  const extractedContext = propagation.extract(context.active(), req.headers, defaultTextMapGetter);
  context.with(extractedContext, () => {
    next();
  });
}
```

#### Production Standard (Correct)
> **Standard**: Implements an explicit key allowlist for contextual baggage, strips any caller-supplied tenant identifiers, and re-attaches authoritative tenant metadata exclusively from cryptographically verified credentials.
```typescript
import { baggage, context, defaultTextMapGetter, propagation, Context } from '@opentelemetry/api';
import { Request, Response, NextFunction } from 'express';

const ALLOWED_BAGGAGE_KEYS = new Set(['request_id', 'client_version', 'trace_origin']);

export function secureTenantIsolationMiddleware(req: Request, res: Response, next: NextFunction): void {
  const extractedContext: Context = propagation.extract(context.active(), req.headers, defaultTextMapGetter);
  const incomingBaggage = baggage.getBaggage(extractedContext);
  
  // Strip untrusted keys; reconstruct baggage only with allowed operational telemetry
  let sanitizedBaggage = baggage.createBaggage();
  if (incomingBaggage) {
    for (const [key, entry] of incomingBaggage.getAllEntries()) {
      if (ALLOWED_BAGGAGE_KEYS.has(key.toLowerCase()) && entry.value.length < 512) {
        sanitizedBaggage = sanitizedBaggage.setEntry(key, entry);
      }
    }
  }

  // Authoritative tenant binding: enforce tenant ID derived ONLY from validated auth token
  const verifiedTenantId = req.authenticatedUser?.tenantId;
  if (verifiedTenantId) {
    sanitizedBaggage = sanitizedBaggage.setEntry('tenant_id', { value: verifiedTenantId });
  }

  const secureContext = baggage.setBaggage(extractedContext, sanitizedBaggage);
  context.with(secureContext, () => {
    next();
  });
}
```

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 Cross-Tenant Isolation and Propagation Sanitizer

OpenTelemetry W3C Baggage Cross-Tenant Isolation and Propagation Sanitizer defines an industrial-grade behavioral standard for devops engineering. Enforces strict boundary sanitization on W3C Baggage headers across microservice ingress and egress filters to prevent tenant spoofing, authorization bypass, and metadata leakage. Untrusted incoming baggage keys representing tenant identity, customer scope, or authorization claims must be dropped or re-validated against cryptographically signed session tokens before propagation. Downstream egress proxies must strictly whitelist contextual metadata keys to avoid exfiltrating internal partition topologies. 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 Ingress/Egress Propagation of W3C Baggage Containing Unsanitized Tenant Identifiers 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 Ingress/Egress Propagation of W3C Baggage Containing Unsanitized Tenant IdentifiersCritical
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 strip and recompute tenant-identifying baggage items (e.g., 'tenant_id', 'org_id', 'account_id') at the ingress perimeter using authenticated JWT claims or mTLS identities.

Engineers MUST ALWAYS strip and recompute tenant-identifying baggage items (e.g., 'tenant_id', 'org_id', 'account_id') at the ingress perimeter using authenticated JWT claims or mTLS 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.
2

Engineers MUST NOT use default OpenTelemetry W3CBaggagePropagator in multi-tenant environments without a custom BaggageFilter or TextMapPropagator interceptor that enforces key allowlists.

Engineers MUST NOT use default OpenTelemetry W3CBaggagePropagator in multi-tenant environments without a custom BaggageFilter or TextMapPropagator interceptor that enforces key allowlists.

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 MUST explicitly drop any baggage entries where key lengths exceed 256 bytes, values exceed 4096 bytes, or keys violate strict regex compliance `^[a-z0-9_.-]+$`.

Code MUST explicitly drop any baggage entries where key lengths exceed 256 bytes, values exceed 4096 bytes, or keys violate strict regex compliance `^[a-z0-9_.-]+$`.

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 proxies MUST sanitize outbound W3C baggage headers to external third-party services, completely removing internal tenant routing metadata, cluster IDs, and customer tier flags.

Egress proxies MUST sanitize outbound W3C baggage headers to external third-party services, completely removing internal tenant routing metadata, cluster IDs, and customer tier flags.

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

Services MUST log a security-audited warning and emit a metric counter (e.g., `telemetry.baggage.dropped_untrusted_tenant`) whenever an unauthenticated tenant context mutation attempt is detected.

Services MUST log a security-audited warning and emit a metric counter (e.g., `telemetry.baggage.dropped_untrusted_tenant`) whenever an unauthenticated tenant context mutation attempt is detected.

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 Cross-Tenant Isolation and Propagation Sanitizer critical for AI coding assistants?

Enforces strict boundary sanitization on W3C Baggage headers across microservice ingress and egress filters to prevent tenant spoofing, authorization bypass, and metadata leakage. Untrusted incoming baggage keys representing tenant identity, customer scope, or authorization claims must be dropped or re-validated against cryptographically signed session tokens before propagation. Downstream egress proxies must strictly whitelist contextual metadata keys to avoid exfiltrating internal partition topologies. 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 Ingress/Egress Propagation of W3C Baggage Containing Unsanitized Tenant Identifiers) 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