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

OpenTelemetry W3C Baggage Cross-Tenant Isolation & Ingress Sanitization Guardrail

Mandates strict allowlist filtering, cryptographic identity cross-verification, and untrusted header stripping for W3C Baggage (`baggage`) at service ingress boundaries. Prevents multi-tenant context confusion, privilege escalation, and exfiltration attacks caused by arbitrary baggage propagation across distributed trace contexts.

Prohibited Anti-Pattern: Blind Ingress Propagation of Untrusted W3C Baggage Headers Across Multi-Tenant Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry W3C Baggage Cross-Tenant Isolation & Ingress Sanitization Guardrail - Mandates strict allowlist filtering, cryptographic identity cross-verification, and untrusted header stripping for W3C Baggage (`baggage`) at service ingress boundaries. Prevents multi-tenant context confusion, privilege escalation, and exfiltration attacks caused by arbitrary baggage propagation across distributed trace contexts.
globs: src/middleware/**/*.{ts,js}, src/tracing/**/*.{ts,js}, src/gateway/**/*.{ts,js}, src/telemetry/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-baggage-cross-tenant-isolation-standard"
---

# OpenTelemetry W3C Baggage Cross-Tenant Isolation & Ingress Sanitization Guardrail

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Blind Ingress Propagation of Untrusted W3C Baggage Headers Across Multi-Tenant Boundaries

## System Constraints
You are a Principal Software Architect enforcing the OpenTelemetry W3C Baggage Cross-Tenant Isolation & Sanitization Standard. Untrusted clients must never dictate baggage state. Ingress gateways and service boundaries must strip inbound baggage headers, re-hydrate exclusively from validated authentication tokens, and strictly constrain keys to an immutable allowlist before downstream propagation.

## Strict Guidelines
- Edge gateways and ingress reverse proxies MUST strip raw incoming `baggage` HTTP headers from untrusted networks prior to context extraction.
- Engineers MUST NOT invoke `propagation.extract()` directly on unvalidated external request headers without passing a sanitizing TextMapGetter.
- Telemetry contexts MUST populate multi-tenant baggage keys (`tenant.id`, `account.tier`) exclusively from cryptographically verified authentication credentials (e.g., validated JWT claims or mTLS identities), never from client-controlled headers.
- Services MUST enforce an explicit schema allowlist for permitted baggage keys, rejecting or silently dropping any unapproved metadata.
- All baggage key and value pairs MUST be strictly sanitized against regex bounds `^[a-zA-Z0-9_.-]{1,64}$` to prevent CRLF injection, log poisoning, and unbounded memory consumption in downstream baggage stores.

## Bad vs Good Implementations
### Ingress Baggage Sanitization & Tenant Context Binding

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly extracting OpenTelemetry context from raw HTTP headers permits untrusted clients to inject arbitrary key-value pairs into the W3C Baggage state. Downstream services consuming `propagation.getBaggage()` for logging, routing, or tenancy will inherit poisoned tenant identities and untrusted parameters.
```typescript
import { Request, Response, NextFunction } from 'express';
import { context, propagation, trace } from '@opentelemetry/api';

// ANTI-PATTERN: Direct extraction of client-supplied baggage.
// An attacker can pass `baggage: tenant.id=target-corp,role=superuser` to spoof context
// or exfiltrate state to downstream distributed tracing collectors.
export function tracingMiddleware(req: Request, res: Response, next: NextFunction) {
  const extractedContext = propagation.extract(context.active(), req.headers);
  
  context.with(extractedContext, () => {
    const span = trace.getTracer('ingress').startSpan('handleRequest');
    res.on('finish', () => span.end());
    next();
  });
}
```

#### Production Standard (Correct)
> **Standard**: The secure middleware explicitly purges untrusted inbound baggage, extracts only the valid W3C traceparent, and re-hydrates trace baggage exclusively using cryptographically verified claims from `req.user`. It validates values against a strict regex before propagation.
```typescript
import { Request, Response, NextFunction } from 'express';
import { context, propagation, trace, propagation as otelPropagation } from '@opentelemetry/api';

interface AuthenticatedUser {
  tenantId: string;
  userId: string;
}

const ALLOWED_BAGGAGE_KEYS = new Set(['tenant.id', 'user.id', 'request.origin']);
const BAGGAGE_VALUE_REGEX = /^[a-zA-Z0-9_.-]{1,64}$/;

export function secureTelemetryMiddleware(req: Request & { user?: AuthenticatedUser }, res: Response, next: NextFunction) {
  // 1. Sanitize incoming headers: extract traceparent but isolate baggage
  const sanitizedHeaders: Record<string, string> = {};
  if (typeof req.headers['traceparent'] === 'string') {
    sanitizedHeaders['traceparent'] = req.headers['traceparent'];
  }

  // 2. Extract baseline context without untrusted baggage
  const traceContext = propagation.extract(context.active(), sanitizedHeaders);

  // 3. Bind validated tenancy strictly from authenticated session
  let baggage = otelPropagation.createBaggage();
  if (req.user?.tenantId && BAGGAGE_VALUE_REGEX.test(req.user.tenantId)) {
    baggage = baggage.setEntry('tenant.id', { value: req.user.tenantId });
  }
  if (req.user?.userId && BAGGAGE_VALUE_REGEX.test(req.user.userId)) {
    baggage = baggage.setEntry('user.id', { value: req.user.userId });
  }

  // 4. Create an immutable, tenant-isolated context
  const secureContext = otelPropagation.setBaggage(traceContext, baggage);

  context.with(secureContext, () => {
    const span = trace.getTracer('ingress-gateway').startSpan(`${req.method} ${req.path}`);
    span.setAttribute('tenant.id', req.user?.tenantId ?? 'anonymous');
    res.on('finish', () => span.end());
    next();
  });
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenTelemetry W3C Baggage Cross-Tenant Isolation & Ingress Sanitization Guardrail

OpenTelemetry W3C Baggage Cross-Tenant Isolation & Ingress Sanitization Guardrail defines an industrial-grade behavioral standard for devops engineering. Mandates strict allowlist filtering, cryptographic identity cross-verification, and untrusted header stripping for W3C Baggage (`baggage`) at service ingress boundaries. Prevents multi-tenant context confusion, privilege escalation, and exfiltration attacks caused by arbitrary baggage propagation across distributed trace contexts. 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 Propagation of Untrusted W3C Baggage Headers Across Multi-Tenant 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 Ingress Propagation of Untrusted W3C Baggage Headers Across Multi-Tenant 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

Edge gateways and ingress reverse proxies MUST strip raw incoming `baggage` HTTP headers from untrusted networks prior to context extraction.

Edge gateways and ingress reverse proxies MUST strip raw incoming `baggage` HTTP headers from untrusted networks prior to context extraction.

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 invoke `propagation.extract()` directly on unvalidated external request headers without passing a sanitizing TextMapGetter.

Engineers MUST NOT invoke `propagation.extract()` directly on unvalidated external request headers without passing a sanitizing TextMapGetter.

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

Telemetry contexts MUST populate multi-tenant baggage keys (`tenant.id`, `account.tier`) exclusively from cryptographically verified authentication credentials (e.g., validated JWT claims or mTLS identities), never from client-controlled headers.

Telemetry contexts MUST populate multi-tenant baggage keys (`tenant.id`, `account.tier`) exclusively from cryptographically verified authentication credentials (e.g., validated JWT claims or mTLS identities), never from client-controlled headers.

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 an explicit schema allowlist for permitted baggage keys, rejecting or silently dropping any unapproved metadata.

Services MUST enforce an explicit schema allowlist for permitted baggage keys, rejecting or silently dropping any unapproved 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.
5

All baggage key and value pairs MUST be strictly sanitized against regex bounds `^[a-zA-Z0-9_.-]{1,64}$` to prevent CRLF injection, log poisoning, and unbounded memory consumption in downstream baggage stores.

All baggage key and value pairs MUST be strictly sanitized against regex bounds `^[a-zA-Z0-9_.-]{1,64}$` to prevent CRLF injection, log poisoning, and unbounded memory consumption in downstream baggage stores.

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 & Ingress Sanitization Guardrail critical for AI coding assistants?

Mandates strict allowlist filtering, cryptographic identity cross-verification, and untrusted header stripping for W3C Baggage (`baggage`) at service ingress boundaries. Prevents multi-tenant context confusion, privilege escalation, and exfiltration attacks caused by arbitrary baggage propagation across distributed trace contexts. 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 Propagation of Untrusted W3C Baggage Headers Across Multi-Tenant 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