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

OpenTelemetry Baggage Strict Allowlisting, Size Capping, and Cross-Tenant Isolation

Unconstrained OpenTelemetry baggage propagation causes distributed header memory amplification, HTTP 431 request rejection cascades, and critical multi-tenant credential leaks across untrusted service boundaries. Systems must enforce compile-time or runtime allowlists of approved telemetry keys, strict byte-size limits, and boundary sanitization prior to distributed context injection.

Prohibited Anti-Pattern: Unbounded Context Injection into W3C Baggage Causing Header Explosion and Multi-Tenant Credential Leakage

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry Baggage Strict Allowlisting, Size Capping, and Cross-Tenant Isolation - Unconstrained OpenTelemetry baggage propagation causes distributed header memory amplification, HTTP 431 request rejection cascades, and critical multi-tenant credential leaks across untrusted service boundaries. Systems must enforce compile-time or runtime allowlists of approved telemetry keys, strict byte-size limits, and boundary sanitization prior to distributed context injection.
globs: src/**/telemetry/**/*.{ts,js,go,py}, src/**/middleware/**/*.{ts,js,go,py}, src/**/tracing/**/*.{ts,js,go,py}, src/**/http/**/*.{ts,js,go,py}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-baggage-cardinality-tenant-boundary-standard"
---

# OpenTelemetry Baggage Strict Allowlisting, Size Capping, and Cross-Tenant Isolation

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unbounded Context Injection into W3C Baggage Causing Header Explosion and Multi-Tenant Credential Leakage

## System Constraints
You are a Principal Engineer enforcing the OpenTelemetry Baggage Strict Cardinality and Cross-Tenant Data Boundary Standard. Mandate strict allowlists, maximum size constraints, and egress filtering for all distributed baggage manipulation. Reject dynamic key-value baggage injection, unvalidated tenant attributes, and downstream propagation of sensitive context.

## Strict Guidelines
- Engineers MUST ALWAYS validate baggage keys against a strict, static allowlist before injecting entries into the active OpenTelemetry context.
- Engineers MUST NOT inject authorization tokens, JWTs, user-submitted payload attributes, passwords, or PII into distributed W3C Baggage headers.
- Code SHOULD enforce maximum length constraints of 64 bytes per key, 128 bytes per value, and an aggregated total baggage limit of 1024 bytes per trace context.
- Services MUST sanitize or purge baggage headers at perimeter ingress and public egress boundaries before dispatching requests to external or third-party networks.
- Components NEVER bridge raw incoming HTTP headers, dynamic query parameters, or unvetted multi-tenant context directly into OpenTelemetry baggage.

## Bad vs Good Implementations
### Unbounded Baggage Dynamic Ingestion vs. Hardened Allowlisted Propagation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Iterating over raw request headers and populating W3C baggage introduces header amplification attacks (HTTP 431) and transmits sensitive authentication tokens and PII to every downstream service in the call chain.
```typescript
import { Request, Response, NextFunction } from 'express';
import { context, propagation } from '@opentelemetry/api';

export function telemetryMiddleware(req: Request, res: Response, next: NextFunction) {
  // VULNERABILITY 1: Direct propagation of user-controlled headers & sensitive tokens
  // VULNERABILITY 2: Unbounded memory amplification; causes HTTP 431 cascades downstream
  let currentBaggage = propagation.getBaggage(context.active()) || propagation.createBaggage();

  for (const [key, value] of Object.entries(req.headers)) {
    if (typeof value === 'string') {
      currentBaggage = currentBaggage.setEntry(key, { value });
    }
  }

  // Leaking auth secrets and tenant data to all downstream microservices
  if (req.user) {
    currentBaggage = currentBaggage
      .setEntry('user_email', { value: req.user.email })
      .setEntry('auth_token', { value: req.headers.authorization ?? '' });
  }

  const newContext = propagation.setBaggage(context.active(), currentBaggage);
  context.with(newContext, () => next());
}
```

#### Production Standard (Correct)
> **Standard**: Implements an explicit static allowlist (`ALLOWED_BAGGAGE_KEYS`), strictly rejects unvetted header inputs, guarantees non-sensitive values only, and caps key, value, and total byte lengths to prevent memory amplification and context poisoning.
```typescript
import { Request, Response, NextFunction } from 'express';
import { context, propagation, Baggage } from '@opentelemetry/api';

// Strict production allowlist of low-cardinality, non-sensitive operational keys
const ALLOWED_BAGGAGE_KEYS = new Set(['tenant_id', 'region', 'traffic_tier'] as const);
type AllowedKey = 'tenant_id' | 'region' | 'traffic_tier';

const MAX_KEY_LENGTH = 64;
const MAX_VALUE_LENGTH = 128;
const MAX_TOTAL_BYTES = 1024;

export function hardenedTelemetryMiddleware(req: Request, res: Response, next: NextFunction): void {
  let currentBaggage = propagation.getBaggage(context.active()) ?? propagation.createBaggage();
  let totalBytes = 0;

  // Calculate existing byte footprint
  for (const entry of currentBaggage.getAllEntries()) {
    totalBytes += entry[0].length + entry[1].value.length;
  }

  const candidateEntries: Partial<Record<AllowedKey, string>> = {
    tenant_id: req.tenantContext?.tenantId,
    region: process.env.DEPLOYMENT_REGION,
    traffic_tier: req.tenantContext?.tier
  };

  for (const [key, value] of Object.entries(candidateEntries) as [AllowedKey, string | undefined][]) {
    if (!value || !ALLOWED_BAGGAGE_KEYS.has(key)) {
      continue;
    }

    const sanitizedVal = value.trim();
    const entryByteCost = key.length + sanitizedVal.length;

    if (
      key.length <= MAX_KEY_LENGTH &&
      sanitizedVal.length <= MAX_VALUE_LENGTH &&
      totalBytes + entryByteCost <= MAX_TOTAL_BYTES
    ) {
      currentBaggage = currentBaggage.setEntry(key, { value: sanitizedVal });
      totalBytes += entryByteCost;
    }
  }

  const safeContext = propagation.setBaggage(context.active(), currentBaggage);
  context.with(safeContext, () => 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 Strict Allowlisting, Size Capping, and Cross-Tenant Isolation

OpenTelemetry Baggage Strict Allowlisting, Size Capping, and Cross-Tenant Isolation defines an industrial-grade behavioral standard for devops engineering. Unconstrained OpenTelemetry baggage propagation causes distributed header memory amplification, HTTP 431 request rejection cascades, and critical multi-tenant credential leaks across untrusted service boundaries. Systems must enforce compile-time or runtime allowlists of approved telemetry keys, strict byte-size limits, and boundary sanitization prior to distributed context injection. 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: Unbounded Context Injection into W3C Baggage Causing Header Explosion and Multi-Tenant Credential Leakage 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 DriftUnbounded Context Injection into W3C Baggage Causing Header Explosion and Multi-Tenant Credential LeakageCritical
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 validate baggage keys against a strict, static allowlist before injecting entries into the active OpenTelemetry context.

Engineers MUST ALWAYS validate baggage keys against a strict, static allowlist before injecting entries into the active OpenTelemetry 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.
2

Engineers MUST NOT inject authorization tokens, JWTs, user-submitted payload attributes, passwords, or PII into distributed W3C Baggage headers.

Engineers MUST NOT inject authorization tokens, JWTs, user-submitted payload attributes, passwords, or PII into distributed W3C Baggage 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.
3

Code SHOULD enforce maximum length constraints of 64 bytes per key, 128 bytes per value, and an aggregated total baggage limit of 1024 bytes per trace context.

Code SHOULD enforce maximum length constraints of 64 bytes per key, 128 bytes per value, and an aggregated total baggage limit of 1024 bytes per 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.
4

Services MUST sanitize or purge baggage headers at perimeter ingress and public egress boundaries before dispatching requests to external or third-party networks.

Services MUST sanitize or purge baggage headers at perimeter ingress and public egress boundaries before dispatching requests to external or third-party networks.

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 bridge raw incoming HTTP headers, dynamic query parameters, or unvetted multi-tenant context directly into OpenTelemetry baggage.

Components NEVER bridge raw incoming HTTP headers, dynamic query parameters, or unvetted multi-tenant context directly into OpenTelemetry 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.
Technical Questions & Answers

Frequently Asked Technical Questions

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

Q:Why is OpenTelemetry Baggage Strict Allowlisting, Size Capping, and Cross-Tenant Isolation critical for AI coding assistants?

Unconstrained OpenTelemetry baggage propagation causes distributed header memory amplification, HTTP 431 request rejection cascades, and critical multi-tenant credential leaks across untrusted service boundaries. Systems must enforce compile-time or runtime allowlists of approved telemetry keys, strict byte-size limits, and boundary sanitization prior to distributed context injection. 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 (Unbounded Context Injection into W3C Baggage Causing Header Explosion and Multi-Tenant Credential Leakage) 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