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

OpenTelemetry Baggage Ingress Sanitization and Cryptographic Verification

Enforces strict boundary sanitization, payload size limits, and cryptographic HMAC signing on OpenTelemetry W3C Baggage across all network ingress points. Prevents denial-of-service via context-bloat (HTTP 431) and eliminates privilege escalation or secret exfiltration via unverified cross-process baggage injection. Mandates deterministic allowlisting and cryptographic signature verification before promoting inbound baggage entries to the active trace context.

Prohibited Anti-Pattern: Blind Context Propagation of Untrusted, Unbounded Baggage Headers Across Ingress Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry Baggage Ingress Sanitization and Cryptographic Verification - Enforces strict boundary sanitization, payload size limits, and cryptographic HMAC signing on OpenTelemetry W3C Baggage across all network ingress points. Prevents denial-of-service via context-bloat (HTTP 431) and eliminates privilege escalation or secret exfiltration via unverified cross-process baggage injection. Mandates deterministic allowlisting and cryptographic signature verification before promoting inbound baggage entries to the active trace context.
globs: src/middleware/**/*.{ts,js}, src/tracing/**/*.{ts,js}, src/instrumentation/**/*.{ts,js}, src/interceptors/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-baggage-sanitization-standard"
---

# OpenTelemetry Baggage Ingress Sanitization and Cryptographic Verification

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Blind Context Propagation of Untrusted, Unbounded Baggage Headers Across Ingress Boundaries

## System Constraints
You are a Principal Software Architect enforcing zero-trust distributed context propagation in OpenTelemetry. Inbound W3C Baggage headers originating outside a trust domain must never be deserialized directly into the active tracing context without strict schema validation, deterministic size truncation, and HMAC verification for privileged claims. Enforce secure boundary middleware and reject untrusted baggage keys.

## Strict Guidelines
- Services MUST ALWAYS enforce an explicit allowlist of acceptable Baggage keys at service ingress boundaries; unapproved keys MUST be dropped immediately.
- Engineers MUST NOT propagate sensitive credentials, raw tokens, or personally identifiable information (PII) inside distributed Baggage.
- Services MUST truncate and reject Baggage headers exceeding RFC/W3C limits: maximum 8192 bytes total, maximum 180 list members, and maximum 4096 bytes per list entry.
- High-privilege routing keys (e.g., 'tenant-id', 'routing-tier', 'datacenter-affinity') MUST be cryptographically verified using an HMAC signature attribute before being trusted by downstream services.
- Middleware MUST construct a sanitized, brand-new Baggage instance rather than mutating or passing through raw inbound context.

## Bad vs Good Implementations
### Ingress Baggage Sanitization & Cryptographic Verification Middleware

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly extracting inbound propagation context without allowlisting, size enforcement, or signature validation allows malicious clients to inject arbitrary context items, potentially spoofing security-critical tenant metadata or triggering memory bloat and upstream downstream HTTP 431 errors.
```typescript
import { Request, Response, NextFunction } from 'express';
import { context, propagation } from '@opentelemetry/api';

export function telemetryMiddleware(req: Request, res: Response, next: NextFunction) {
  // VULNERABLE: Direct propagation of untrusted, unbounded baggage header.
  // Allows HTTP header bloat attacks (431 DoS) and untrusted tenant spoofing.
  const extractedContext = propagation.extract(context.active(), req.headers);
  context.with(extractedContext, () => {
    next();
  });
}
```

#### Production Standard (Correct)
> **Standard**: Validates baggage size against limits, drops any keys not present in an explicit allowlist, cryptographically checks HMAC signatures on privileged attributes (like 'tenant-id'), and constructs an isolated, validated Baggage container before downstream execution.
```typescript
import { Request, Response, NextFunction } from 'express';
import { context, propagation, baggageUtils, createBaggage } from '@opentelemetry/api';
import { createHmac, timingSafeEqual } from 'crypto';

const MAX_BAGGAGE_BYTES = 8192;
const ALLOWED_BAGGAGE_KEYS = new Set(['request-source', 'tenant-id']);
const BAGGAGE_HMAC_SECRET = process.env.BAGGAGE_SIGNING_KEY || '';

function verifyHmac(key: string, value: string, signature: string): boolean {
  if (!BAGGAGE_HMAC_SECRET) return false;
  const expected = createHmac('sha256', BAGGAGE_HMAC_SECRET).update(`${key}=${value}`).digest('hex');
  return signature.length === expected.length && timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
}

export function telemetryMiddleware(req: Request, res: Response, next: NextFunction) {
  const rawBaggage = req.headers['baggage'];
  const extractedContext = propagation.extract(context.active(), req.headers);

  if (typeof rawBaggage === 'string' && rawBaggage.length <= MAX_BAGGAGE_BYTES) {
    const inboundBaggage = propagation.getBaggage(extractedContext);
    if (inboundBaggage) {
      const sanitizedEntries: Record<string, { value: string }> = {};

      for (const [key, entry] of inboundBaggage.getAllEntries()) {
        if (!ALLOWED_BAGGAGE_KEYS.has(key)) continue;

        if (key === 'tenant-id') {
          const sig = entry.metadata?.getValue();
          if (!sig || !verifyHmac(key, entry.value, sig)) {
            continue; // Drop forged/unverified privileged baggage
          }
        }

        sanitizedEntries[key] = { value: entry.value };
      }

      const sanitizedBaggage = createBaggage(sanitizedEntries);
      const secureContext = propagation.setBaggage(extractedContext, sanitizedBaggage);
      return context.with(secureContext, () => next());
    }
  }

  // Fallback to trace context stripped of unverified baggage
  const sanitizedContext = propagation.setBaggage(extractedContext, createBaggage());
  context.with(sanitizedContext, () => 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 Cryptographic Verification

OpenTelemetry Baggage Ingress Sanitization and Cryptographic Verification defines an industrial-grade behavioral standard for devops engineering. Enforces strict boundary sanitization, payload size limits, and cryptographic HMAC signing on OpenTelemetry W3C Baggage across all network ingress points. Prevents denial-of-service via context-bloat (HTTP 431) and eliminates privilege escalation or secret exfiltration via unverified cross-process baggage injection. Mandates deterministic allowlisting and cryptographic signature verification before promoting inbound baggage entries to the active trace context. 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, Unbounded Baggage Headers Across Ingress 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 Context Propagation of Untrusted, Unbounded Baggage Headers Across Ingress 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

Services MUST ALWAYS enforce an explicit allowlist of acceptable Baggage keys at service ingress boundaries

Services MUST ALWAYS enforce an explicit allowlist of acceptable Baggage keys at service ingress boundaries; unapproved keys MUST be dropped immediately.

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 propagate sensitive credentials, raw tokens, or personally identifiable information (PII) inside distributed Baggage.

Engineers MUST NOT propagate sensitive credentials, raw tokens, or personally identifiable information (PII) inside distributed 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.
3

Services MUST truncate and reject Baggage headers exceeding RFC/W3C limits

Services MUST truncate and reject Baggage headers exceeding RFC/W3C limits: maximum 8192 bytes total, maximum 180 list members, and maximum 4096 bytes per list entry.

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

High-privilege routing keys (e.g., 'tenant-id', 'routing-tier', 'datacenter-affinity') MUST be cryptographically verified using an HMAC signature attribute before being trusted by downstream services.

High-privilege routing keys (e.g., 'tenant-id', 'routing-tier', 'datacenter-affinity') MUST be cryptographically verified using an HMAC signature attribute before being trusted by downstream services.

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

Middleware MUST construct a sanitized, brand-new Baggage instance rather than mutating or passing through raw inbound context.

Middleware MUST construct a sanitized, brand-new Baggage instance rather than mutating or passing through raw inbound 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.
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 Cryptographic Verification critical for AI coding assistants?

Enforces strict boundary sanitization, payload size limits, and cryptographic HMAC signing on OpenTelemetry W3C Baggage across all network ingress points. Prevents denial-of-service via context-bloat (HTTP 431) and eliminates privilege escalation or secret exfiltration via unverified cross-process baggage injection. Mandates deterministic allowlisting and cryptographic signature verification before promoting inbound baggage entries to the active trace context. 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, Unbounded Baggage Headers Across Ingress 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