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

OpenTelemetry Ingress Baggage Sanitization, Allowlisting, and Bounding Guardrail

Enforces strict perimeter hygiene on incoming W3C Baggage headers at API gateways and ingress points. Mandates payload size bounding, entry count truncation, and key allowlisting to prevent telemetry memory amplification attacks, trace context injection exploits, and upstream context pollution.

Prohibited Anti-Pattern: Blind Ingress Propagation of Unbounded, Untrusted Client Baggage into Internal Distributed Contexts

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry Ingress Baggage Sanitization, Allowlisting, and Bounding Guardrail - Enforces strict perimeter hygiene on incoming W3C Baggage headers at API gateways and ingress points. Mandates payload size bounding, entry count truncation, and key allowlisting to prevent telemetry memory amplification attacks, trace context injection exploits, and upstream context pollution.
globs: src/middleware/**/*.{ts,js,go}, src/gateway/**/*.{ts,js,go}, src/tracing/**/*.{ts,js,go}, src/server/**/*.{ts,js,go}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-baggage-ingress-sanitization-guardrail"
---

# OpenTelemetry Ingress Baggage Sanitization, Allowlisting, and Bounding Guardrail

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Blind Ingress Propagation of Unbounded, Untrusted Client Baggage into Internal Distributed Contexts

## System Constraints
You are a Principal Security and Reliability Architect enforcing OpenTelemetry Baggage perimeter ingress controls. You must ensure that no untrusted external client input blindly propagates into downstream distributed contexts via W3C Baggage. Mandate hard byte limits, item limits, regex key validation, and strict allowlisting at ingress boundaries while preserving explicit traceparent propagation.

## Strict Guidelines
- Engineers MUST ALWAYS drop or strictly sanitize incoming `baggage` headers at external API ingress before extracting OpenTelemetry context into the active request runtime.
- Engineers MUST NOT blindly deserialize untrusted client-supplied `baggage` headers using the standard `W3CBaggagePropagator` without an intermediate bounded sanitization layer.
- Perimeter gateways MUST enforce hard upper bounds: maximum aggregate `baggage` header length (e.g., <= 512 bytes), maximum key-value pair count (e.g., <= 8 items), and per-value length caps (e.g., <= 64 bytes).
- Services MUST validate baggage keys against an explicit runtime allowlist (e.g., `['tenant-id', 'client-version']`) and reject or discard keys containing reserved metadata, user-controlled credentials, or arbitrary control characters.
- Components NEVER permit untrusted client baggage to overwrite authoritative server-side metadata established during authentication or authorization stages.

## Bad vs Good Implementations
### Ingress Baggage Sanitization and Extraction Middleware

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly running `propagation.extract` on `req.headers` processes the raw W3C `baggage` header. Attackers can inject arbitrary keys, trigger telemetry buffer exhaustion, and inject malicious operational flags that propagate unchecked across all downstream microservices.
```typescript
import { Request, Response, NextFunction } from 'express';
import { context, propagation } from '@opentelemetry/api';

// VULNERABLE: Direct extraction propagates arbitrary external client-supplied baggage.
// Attackers can send 64KB headers with thousands of keys to cause telemetry node memory exhaustion,
// or inject fake operational flags ('is_admin=true') downstream.
export function ingressTraceMiddleware(req: Request, res: Response, next: NextFunction): void {
  const extractedContext = propagation.extract(context.active(), req.headers);
  context.with(extractedContext, () => {
    next();
  });
}
```

#### Production Standard (Correct)
> **Standard**: Decouples traceparent extraction from untrusted baggage. Sanitizes the raw header by enforcing aggregate byte limits, key allowlisting, and strict entry counts before binding verified baggage to the downstream trace context.
```typescript
import { Request, Response, NextFunction } from 'express';
import { context, propagation, Baggage, createBaggage } from '@opentelemetry/api';

const ALLOWED_BAGGAGE_KEYS = new Set(['tenant.id', 'region.hint']);
const MAX_TOTAL_BAGGAGE_BYTES = 512;
const MAX_BAGGAGE_ENTRIES = 5;
const MAX_VALUE_LENGTH = 64;

export function sanitizeAndExtractContext(req: Request, res: Response, next: NextFunction): void {
  const rawBaggage = req.headers['baggage'];
  const safeHeaders: Record<string, string | string[] | undefined> = { ...req.headers };

  // Strip raw baggage from incoming headers to isolate trace extraction from baggage injection
  delete safeHeaders['baggage'];
  const baseContext = propagation.extract(context.active(), safeHeaders);

  if (typeof rawBaggage === 'string' && rawBaggage.length <= MAX_TOTAL_BAGGAGE_BYTES) {
    const safeEntries: Record<string, { value: string }> = {};
    let entryCount = 0;

    const pairs = rawBaggage.split(',');
    for (const pair of pairs) {
      if (entryCount >= MAX_BAGGAGE_ENTRIES) break;
      const [rawKey, rawVal] = pair.split('=').map((s) => s.trim());
      
      if (rawKey && rawVal && ALLOWED_BAGGAGE_KEYS.has(rawKey)) {
        const decodedVal = decodeURIComponent(rawVal).slice(0, MAX_VALUE_LENGTH);
        safeEntries[rawKey] = { value: decodedVal };
        entryCount++;
      }
    }

    const sanitizedBaggage: Baggage = createBaggage(safeEntries);
    const finalContext = propagation.setBaggage(baseContext, sanitizedBaggage);
    context.with(finalContext, () => next());
    return;
  }

  // If baggage header is oversized or missing, proceed with empty baggage context
  context.with(baseContext, () => 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 Ingress Baggage Sanitization, Allowlisting, and Bounding Guardrail

OpenTelemetry Ingress Baggage Sanitization, Allowlisting, and Bounding Guardrail defines an industrial-grade behavioral standard for devops engineering. Enforces strict perimeter hygiene on incoming W3C Baggage headers at API gateways and ingress points. Mandates payload size bounding, entry count truncation, and key allowlisting to prevent telemetry memory amplification attacks, trace context injection exploits, and upstream context pollution. 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 Unbounded, Untrusted Client Baggage into Internal Distributed Contexts 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 Unbounded, Untrusted Client Baggage into Internal Distributed ContextsCritical
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 drop or strictly sanitize incoming `baggage` headers at external API ingress before extracting OpenTelemetry context into the active request runtime.

Engineers MUST ALWAYS drop or strictly sanitize incoming `baggage` headers at external API ingress before extracting OpenTelemetry context into the active request runtime.

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 blindly deserialize untrusted client-supplied `baggage` headers using the standard `W3CBaggagePropagator` without an intermediate bounded sanitization layer.

Engineers MUST NOT blindly deserialize untrusted client-supplied `baggage` headers using the standard `W3CBaggagePropagator` without an intermediate bounded sanitization layer.

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

Perimeter gateways MUST enforce hard upper bounds

Perimeter gateways MUST enforce hard upper bounds: maximum aggregate `baggage` header length (e.g., <= 512 bytes), maximum key-value pair count (e.g., <= 8 items), and per-value length caps (e.g., <= 64 bytes).

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 validate baggage keys against an explicit runtime allowlist (e.g., `['tenant-id', 'client-version']`) and reject or discard keys containing reserved metadata, user-controlled credentials, or arbitrary control characters.

Services MUST validate baggage keys against an explicit runtime allowlist (e.g., `['tenant-id', 'client-version']`) and reject or discard keys containing reserved metadata, user-controlled credentials, or arbitrary control characters.

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 permit untrusted client baggage to overwrite authoritative server-side metadata established during authentication or authorization stages.

Components NEVER permit untrusted client baggage to overwrite authoritative server-side metadata established during authentication or authorization stages.

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 Ingress Baggage Sanitization, Allowlisting, and Bounding Guardrail critical for AI coding assistants?

Enforces strict perimeter hygiene on incoming W3C Baggage headers at API gateways and ingress points. Mandates payload size bounding, entry count truncation, and key allowlisting to prevent telemetry memory amplification attacks, trace context injection exploits, and upstream context pollution. 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 Unbounded, Untrusted Client Baggage into Internal Distributed Contexts) 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