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

OpenTelemetry Ingress Baggage Sanitization and Cardinality Gate Enforcement

Enforces strict validation, allowlisting, and cardinality bounds on W3C Baggage headers at ingress service boundaries. Prevents cross-tenant context injection, telemetry store index explosion, and memory exhaustion by stripping untrusted keys before propagating OpenTelemetry Context downstream.

Prohibited Anti-Pattern: Blind Ingress Baggage Propagation Leading to Multi-Tenant Spoofing and Telemetry DoS

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry Ingress Baggage Sanitization and Cardinality Gate Enforcement - Enforces strict validation, allowlisting, and cardinality bounds on W3C Baggage headers at ingress service boundaries. Prevents cross-tenant context injection, telemetry store index explosion, and memory exhaustion by stripping untrusted keys before propagating OpenTelemetry Context downstream.
globs: src/middleware/**/*.{ts,js}, src/tracing/**/*.{ts,js}, src/gateway/**/*.{ts,js}, src/server/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-ingress-baggage-sanitization-cardinality-gate"
---

# OpenTelemetry Ingress Baggage Sanitization and Cardinality Gate Enforcement

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Blind Ingress Baggage Propagation Leading to Multi-Tenant Spoofing and Telemetry DoS

## System Constraints
You are a Principal Software Architect enforcing zero-trust OpenTelemetry context propagation. Public ingress boundaries must never blindly accept or propagate unvetted W3C baggage headers. Enforce an invariant that requires all incoming baggage to be stripped or filtered through a strict allowlist with bounded cardinality, safe string lengths, and schema validation before injecting into downstream spans or telemetry contexts.

## Strict Guidelines
- Services MUST NEVER extract and forward untrusted client baggage headers directly into active trace contexts without explicit schema validation.
- Engineers MUST configure ingress middleware to strip unauthenticated `baggage` headers and only reconstruct safe baggage entries from verified identity claims (e.g., validated JWT tokens).
- If public baggage ingestion is required, middleware MUST enforce a strict key allowlist, limit baggage key count (MAX 5 keys), limit value length (MAX 64 chars), and enforce alphanumeric regex matching.
- Engineers MUST NEVER propagate high-cardinality identifiers (such as raw UUIDs, user-controlled timestamps, or unindexed payloads) into downstream baggage or span attributes.
- Internal propagators SHOULD separate external edge context extraction from internal microservice hop extraction to enforce zero-trust network boundaries.

## Bad vs Good Implementations
### Ingress Baggage Sanitization and Cardinality Gate Middleware

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly calling propagation.extract() on untrusted edge headers allows clients to inject forged baggage keys (e.g., tenant_id=compromised-tenant) and arbitrary high-cardinality strings that pollute downstream spans, memory pools, and telemetry storage indices.
```typescript
import { Request, Response, NextFunction } from 'express';
import { ROOT_CONTEXT, propagation, trace } from '@opentelemetry/api';

export function tracingMiddleware(req: Request, res: Response, next: NextFunction) {
  // VULNERABILITY: Blindly extracts untrusted W3C baggage from public HTTP headers.
  // Malicious clients can inject arbitrary tenant_id, bypass access boundaries, or trigger OOM
  // in downstream trace indexers via high-cardinality payload floods.
  const extractedContext = propagation.extract(ROOT_CONTEXT, req.headers);
  
  const tracer = trace.getTracer('ingress-gateway');
  const span = tracer.startSpan('HTTP ' + req.method + ' ' + req.path, {}, extractedContext);

  trace.setSpan(extractedContext, span);
  next();
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly strips unknown baggage keys, enforces a strict alphanumeric regex, caps value sizes and key counts, and ensures sensitive identity attributes (such as tenant_id) are sourced exclusively from cryptographically verified server-side tokens.
```typescript
import { Request, Response, NextFunction } from 'express';
import { ROOT_CONTEXT, propagation, trace, baggageEntryMetadataEmpty } from '@opentelemetry/api';

const ALLOWED_BAGGAGE_KEYS = new Set(['region', 'client_tier']);
const MAX_KEY_COUNT = 3;
const MAX_VALUE_LENGTH = 64;
const SAFE_VALUE_REGEX = /^[a-zA-Z0-9_-]+$/;

export function secureTracingMiddleware(req: Request, res: Response, next: NextFunction) {
  // 1. Extract raw context (traceparent) but isolate and scrub baggage
  const extractedContext = propagation.extract(ROOT_CONTEXT, req.headers);
  const incomingBaggage = propagation.getBaggage(extractedContext);

  // 2. Enforce strict allowlist and cardinality gate
  let sanitizedBaggage = propagation.createBaggage();
  let validKeyCount = 0;

  if (incomingBaggage) {
    for (const [key, entry] of incomingBaggage.getAllEntries()) {
      if (ALLOWED_BAGGAGE_KEYS.has(key) && validKeyCount < MAX_KEY_COUNT) {
        if (entry.value.length <= MAX_VALUE_LENGTH && SAFE_VALUE_REGEX.test(entry.value)) {
          sanitizedBaggage = sanitizedBaggage.setEntry(key, entry);
          validKeyCount++;
        }
      }
    }
  }

  // 3. Authenticated tenant injection (override client claims from verified auth context)
  const verifiedTenant = req.user?.tenantId;
  if (verifiedTenant && SAFE_VALUE_REGEX.test(verifiedTenant)) {
    sanitizedBaggage = sanitizedBaggage.setEntry('tenant_id', {
      value: verifiedTenant,
      metadata: baggageEntryMetadataEmpty()
    });
  }

  // 4. Bind sanitized baggage back into execution context
  const cleanContext = propagation.setBaggage(extractedContext, sanitizedBaggage);
  const tracer = trace.getTracer('ingress-gateway');
  const span = tracer.startSpan(`HTTP ${req.method} ${req.route?.path ?? 'unmatched'}`, {}, cleanContext);

  trace.withContext(trace.setSpan(cleanContext, span), () => next());
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenTelemetry Ingress Baggage Sanitization and Cardinality Gate Enforcement

OpenTelemetry Ingress Baggage Sanitization and Cardinality Gate Enforcement defines an industrial-grade behavioral standard for devops engineering. Enforces strict validation, allowlisting, and cardinality bounds on W3C Baggage headers at ingress service boundaries. Prevents cross-tenant context injection, telemetry store index explosion, and memory exhaustion by stripping untrusted keys before propagating OpenTelemetry Context downstream. 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 Baggage Propagation Leading to Multi-Tenant Spoofing and Telemetry DoS 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 Baggage Propagation Leading to Multi-Tenant Spoofing and Telemetry DoSCritical
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 NEVER extract and forward untrusted client baggage headers directly into active trace contexts without explicit schema validation.

Services MUST NEVER extract and forward untrusted client baggage headers directly into active trace contexts without explicit schema validation.

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 configure ingress middleware to strip unauthenticated `baggage` headers and only reconstruct safe baggage entries from verified identity claims (e.g., validated JWT tokens).

Engineers MUST configure ingress middleware to strip unauthenticated `baggage` headers and only reconstruct safe baggage entries from verified identity claims (e.g., validated JWT tokens).

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

If public baggage ingestion is required, middleware MUST enforce a strict key allowlist, limit baggage key count (MAX 5 keys), limit value length (MAX 64 chars), and enforce alphanumeric regex matching.

If public baggage ingestion is required, middleware MUST enforce a strict key allowlist, limit baggage key count (MAX 5 keys), limit value length (MAX 64 chars), and enforce alphanumeric regex matching.

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

Engineers MUST NEVER propagate high-cardinality identifiers (such as raw UUIDs, user-controlled timestamps, or unindexed payloads) into downstream baggage or span attributes.

Engineers MUST NEVER propagate high-cardinality identifiers (such as raw UUIDs, user-controlled timestamps, or unindexed payloads) into downstream baggage or span attributes.

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

Internal propagators SHOULD separate external edge context extraction from internal microservice hop extraction to enforce zero-trust network boundaries.

Internal propagators SHOULD separate external edge context extraction from internal microservice hop extraction to enforce zero-trust network boundaries.

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 and Cardinality Gate Enforcement critical for AI coding assistants?

Enforces strict validation, allowlisting, and cardinality bounds on W3C Baggage headers at ingress service boundaries. Prevents cross-tenant context injection, telemetry store index explosion, and memory exhaustion by stripping untrusted keys before propagating OpenTelemetry Context downstream. 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 Baggage Propagation Leading to Multi-Tenant Spoofing and Telemetry DoS) 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