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

OpenTelemetry Baggage Ingress Sanitization and Boundary Defense

Enforces strict boundary validation and stripping of untrusted W3C Baggage HTTP headers at API gateways and perimeter ingress proxies. Prevents trace context poisoning, privilege escalation via contextual spoofing, and memory exhaustion caused by unbounded baggage propagation across downstream distributed microservices.

Prohibited Anti-Pattern: Blind Context Propagation of Untrusted Ingress Baggage Headers into Internal Tracing Spans

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry Baggage Ingress Sanitization and Boundary Defense - Enforces strict boundary validation and stripping of untrusted W3C Baggage HTTP headers at API gateways and perimeter ingress proxies. Prevents trace context poisoning, privilege escalation via contextual spoofing, and memory exhaustion caused by unbounded baggage propagation across downstream distributed microservices.
globs: src/middleware/**/*.{ts,js}, src/gateway/**/*.{ts,js}, src/tracing/**/*.{ts,js}, apps/api/src/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/otel-baggage-ingress-sanitization-standard"
---

# OpenTelemetry Baggage Ingress Sanitization and Boundary Defense

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Blind Context Propagation of Untrusted Ingress Baggage Headers into Internal Tracing Spans

## System Constraints
You are a Principal Software Architect enforcing the OpenTelemetry Baggage Header Ingress Sanitization Standard. Untrusted external clients must never dictate baggage state in internal service meshes. Ensure all edge and gateway layers explicitly drop, validate, or filter W3C baggage headers according to strict allowlists, maximum size constraints, and key-format specifications before propagating context downstream.

## Strict Guidelines
- Edge API Gateways MUST drop untrusted external `baggage` headers by default unless the request is cryptographically authenticated and explicitly permitted.
- Engineers MUST NOT pass raw `req.headers['baggage']` or `req.headers` directly to OpenTelemetry `propagation.extract()` at edge boundaries without an intermediary sanitization step.
- When baggage pass-through is required, services MUST apply a strict allowlist matching expected key regex patterns (e.g., `^[a-z0-9_\-\.]{1,32}$`).
- Services MUST enforce strict resource bounds on baggage payloads: maximum 8192 total bytes, maximum 16 key-value pairs, and maximum 256 bytes per value.
- Components NEVER store sensitive internal tokens, PII, authorization scopes, or unhashed identifiers inside baggage entries propagated to external downstream destinations.
- Sanitization layers MUST log security telemetry warnings with rate-limiting when malformed or oversized baggage headers are intercepted at ingress points.

## Bad vs Good Implementations
### Sanitizing W3C Baggage Headers at API Gateway Ingress

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Raw request headers are extracted without sanitization. An external attacker can inject arbitrary keys (e.g., internal-routing-flags, malicious baggage properties) or send an oversized payload that propagates to all downstream internal RPCs, causing context poisoning and high memory consumption.
```typescript
import { Request, Response, NextFunction } from 'express';
import { context, propagation } from '@opentelemetry/api';

// ANTI-PATTERN: Blindly extracting untrusted baggage headers from public clients
export function tracingMiddleware(req: Request, res: Response, next: NextFunction): void {
  // Directly extracting untrusted HTTP headers propagates arbitrary baggage
  // into the active context, enabling unbounded memory allocation and context spoofing.
  const extractedContext = propagation.extract(context.active(), req.headers);
  
  context.with(extractedContext, () => {
    next();
  });
}
```

#### Production Standard (Correct)
> **Standard**: Validates incoming baggage against strict security invariants: drops payloads exceeding 2KB, enforces an entry count cap of 8, strictly checks keys against an immutable allowlist, limits value length, and purges untrusted entry metadata before activating the OpenTelemetry execution context.
```typescript
import { Request, Response, NextFunction } from 'express';
import { context, propagation, Baggage, BaggageEntry } from '@opentelemetry/api';

const ALLOWED_BAGGAGE_KEYS = new Set(['tenant_id', 'client_version', 'traffic_source']);
const MAX_BAGGAGE_BYTES = 2048;
const MAX_ENTRIES = 8;
const MAX_VALUE_LENGTH = 128;

export function sanitizeBaggageMiddleware(req: Request, res: Response, next: NextFunction): void {
  const rawBaggage = req.headers['baggage'];

  // Extract existing propagation context (traceparent) using only safe extractors
  const parentContext = propagation.extract(context.active(), req.headers);
  const currentBaggage = propagation.getBaggage(parentContext);

  if (!rawBaggage || !currentBaggage) {
    // No baggage or parsing yielded null: propagate parent context without baggage
    const cleanContext = propagation.deleteBaggage(parentContext);
    context.with(cleanContext, () => next());
    return;
  }

  const rawBaggageString = Array.isArray(rawBaggage) ? rawBaggage.join(',') : rawBaggage;
  if (Buffer.byteLength(rawBaggageString, 'utf8') > MAX_BAGGAGE_BYTES) {
    // Exceeded maximum byte limit; discard completely to prevent memory exhaustion
    const cleanContext = propagation.deleteBaggage(parentContext);
    context.with(cleanContext, () => next());
    return;
  }

  // Build a sanitized baggage instance conforming strictly to allowlists
  let sanitizedBaggage: Baggage = propagation.createBaggage();
  let entryCount = 0;

  for (const [key, entry] of currentBaggage.getAllEntries()) {
    if (entryCount >= MAX_ENTRIES) break;
    
    if (ALLOWED_BAGGAGE_KEYS.has(key) && entry.value.length <= MAX_VALUE_LENGTH) {
      const sanitizedEntry: BaggageEntry = {
        value: entry.value,
        metadata: undefined, // Strip untrusted client metadata
      };
      sanitizedBaggage = sanitizedBaggage.setEntry(key, sanitizedEntry);
      entryCount++;
    }
  }

  const safeContext = propagation.setBaggage(parentContext, sanitizedBaggage);
  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 Ingress Sanitization and Boundary Defense

OpenTelemetry Baggage Ingress Sanitization and Boundary Defense defines an industrial-grade behavioral standard for devops engineering. Enforces strict boundary validation and stripping of untrusted W3C Baggage HTTP headers at API gateways and perimeter ingress proxies. Prevents trace context poisoning, privilege escalation via contextual spoofing, and memory exhaustion caused by unbounded baggage propagation across downstream distributed microservices. 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 Context Propagation of Untrusted Ingress Baggage Headers into Internal Tracing Spans 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 Context Propagation of Untrusted Ingress Baggage Headers into Internal Tracing SpansCritical
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 API Gateways MUST drop untrusted external `baggage` headers by default unless the request is cryptographically authenticated and explicitly permitted.

Edge API Gateways MUST drop untrusted external `baggage` headers by default unless the request is cryptographically authenticated and explicitly permitted.

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 pass raw `req.headers['baggage']` or `req.headers` directly to OpenTelemetry `propagation.extract()` at edge boundaries without an intermediary sanitization step.

Engineers MUST NOT pass raw `req.headers['baggage']` or `req.headers` directly to OpenTelemetry `propagation.extract()` at edge boundaries without an intermediary sanitization step.

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

When baggage pass-through is required, services MUST apply a strict allowlist matching expected key regex patterns (e.g., `^[a-z0-9_\-\.]{1,32}$`).

When baggage pass-through is required, services MUST apply a strict allowlist matching expected key regex patterns (e.g., `^[a-z0-9_\-\.]{1,32}$`).

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 strict resource bounds on baggage payloads

Services MUST enforce strict resource bounds on baggage payloads: maximum 8192 total bytes, maximum 16 key-value pairs, and maximum 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

Components NEVER store sensitive internal tokens, PII, authorization scopes, or unhashed identifiers inside baggage entries propagated to external downstream destinations.

Components NEVER store sensitive internal tokens, PII, authorization scopes, or unhashed identifiers inside baggage entries propagated to external downstream destinations.

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.
6

Sanitization layers MUST log security telemetry warnings with rate-limiting when malformed or oversized baggage headers are intercepted at ingress points.

Sanitization layers MUST log security telemetry warnings with rate-limiting when malformed or oversized baggage headers are intercepted at ingress points.

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

Enforces strict boundary validation and stripping of untrusted W3C Baggage HTTP headers at API gateways and perimeter ingress proxies. Prevents trace context poisoning, privilege escalation via contextual spoofing, and memory exhaustion caused by unbounded baggage propagation across downstream distributed microservices. 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 Context Propagation of Untrusted Ingress Baggage Headers into Internal Tracing Spans) 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