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

OpenTelemetry W3C Baggage Ingress Quota and Sanitization Boundary

Enforces strict ingress size boundaries, allowlist filtering, and character sanitization on W3C Baggage headers entering distributed service perimeters. Prevents telemetry poisoning, header injection attacks, and memory exhaustion caused by unconstrained baggage propagation.

Prohibited Anti-Pattern: Blind Ingestion and Unbounded Propagation of Untrusted W3C Baggage Headers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry W3C Baggage Ingress Quota and Sanitization Boundary - Enforces strict ingress size boundaries, allowlist filtering, and character sanitization on W3C Baggage headers entering distributed service perimeters. Prevents telemetry poisoning, header injection attacks, and memory exhaustion caused by unconstrained baggage propagation.
globs: src/instrumentation/**/*.{ts,js}, src/telemetry/**/*.{ts,js}, src/middleware/**/*.{ts,js}, src/tracing/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-baggage-quota-sanitization-boundary"
---

# OpenTelemetry W3C Baggage Ingress Quota and Sanitization Boundary

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Blind Ingestion and Unbounded Propagation of Untrusted W3C Baggage Headers

## System Constraints
You are a Principal Observability and Security Architect enforcing OpenTelemetry W3C Baggage Ingress Quota and Sanitization boundaries. You must reject any implementation that accepts, propagates, or mirrors W3C baggage headers across process boundaries without explicit key allowlisting, byte-length limits, total item limits, and character set sanitization.

## Strict Guidelines
- Engineers MUST ALWAYS wrap or intercept the standard W3CBaggagePropagator at public network ingress with a validating boundary that enforces size caps and key allowlists.
- Engineers MUST NOT allow unconstrained baggage extraction to propagate directly into downstream service calls or child trace contexts.
- Code SHOULD enforce strict hard limits: total baggage header size <= 2048 bytes, maximum 16 key-value pairs, key length <= 64 bytes, and value length <= 256 bytes.
- Services MUST reject or strip baggage entries containing non-printable ASCII, control characters, CRLF injections, or keys matching sensitive data patterns (e.g., authorization, token, secret, cookie).
- Components NEVER blindly elevate external baggage entries into span attributes or metrics labels without schema-validated key whitelisting to avoid high-cardinality state exhaustion.

## Bad vs Good Implementations
### Ingress Baggage Sanitization Boundary with Strict Quotas

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accepting unvalidated W3C baggage headers allows external callers to inject arbitrary payload sizes, control characters, and high-cardinality keys. Downstream span processors that automatically convert baggage to span attributes will suffer memory exhaustion and log/telemetry poisoning.
```typescript
import { context, propagation } from '@opentelemetry/api';
import { Request, Response, NextFunction } from 'express';

// ANTI-PATTERN: Blindly extracts untrusted baggage from ingress headers.
// Vulnerable to unbounded memory allocation, CRLF injection, and telemetry-attribute explosion.
export function traceIngressMiddleware(req: Request, _res: Response, next: NextFunction) {
  const extractedContext = propagation.extract(context.active(), req.headers);
  context.with(extractedContext, () => {
    // Automatically syncing untrusted baggage directly to active context without limits
    next();
  });
}
```

#### Production Standard (Correct)
> **Standard**: Implements an impermeable boundary that enforces maximum total payload length, key-value pair count limits, key name allowlisting via Set membership and regex, value length fences, and strict control-character stripping before baggage is parsed into the OpenTelemetry context.
```typescript
import { Context, TextMapGetter, TextMapPropagator, baggageUtils, propagation } from '@opentelemetry/api';

const MAX_TOTAL_BYTES = 2048;
const MAX_PAIRS = 16;
const MAX_KEY_LEN = 64;
const MAX_VAL_LEN = 256;
const ALLOWED_KEY_PATTERN = /^[a-z0-9_-]{1,64}$/i;
const ALLOWLISTED_KEYS = new Set(['tenant_id', 'env', 'client_version', 'traffic_type']);

export class QuotaSanitizedBaggagePropagator implements TextMapPropagator {
  constructor(private readonly delegate: TextMapPropagator) {}

  inject(context: Context, carrier: unknown, setter: unknown): void {
    this.delegate.inject(context, carrier, setter as any);
  }

  extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {
    const rawHeader = getter.get(carrier, 'baggage');
    const baggageValue = Array.isArray(rawHeader) ? rawHeader.join(',') : rawHeader;

    if (!baggageValue || typeof baggageValue !== 'string' || baggageValue.length > MAX_TOTAL_BYTES) {
      return context;
    }

    const parsedBaggage = baggageUtils.parseKeyPairsIntoRecord(baggageValue);
    const sanitizedEntries = Object.entries(parsedBaggage)
      .slice(0, MAX_PAIRS)
      .filter(([key, val]) => {
        return (
          ALLOWLISTED_KEYS.has(key) &&
          ALLOWED_KEY_PATTERN.test(key) &&
          key.length <= MAX_KEY_LEN &&
          val.value.length <= MAX_VAL_LEN &&
          !/[\r\n\x00-\x1F\x7F]/.test(val.value)
        );
      });

    if (sanitizedEntries.length === 0) {
      return context;
    }

    const sanitizedSerialized = sanitizedEntries
      .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v.value)}`)
      .join(',');

    const sanitizedCarrier = { baggage: sanitizedSerialized };
    return this.delegate.extract(context, sanitizedCarrier, {
      get: (c: Record<string, string>, k: string) => c[k.toLowerCase()],
      keys: (c: Record<string, string>) => Object.keys(c)
    });
  }

  fields(): string[] {
    return this.delegate.fields();
  }
}
```

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 W3C Baggage Ingress Quota and Sanitization Boundary

OpenTelemetry W3C Baggage Ingress Quota and Sanitization Boundary defines an industrial-grade behavioral standard for devops engineering. Enforces strict ingress size boundaries, allowlist filtering, and character sanitization on W3C Baggage headers entering distributed service perimeters. Prevents telemetry poisoning, header injection attacks, and memory exhaustion caused by unconstrained baggage propagation. 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 Ingestion and Unbounded Propagation of Untrusted W3C Baggage Headers 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 Ingestion and Unbounded Propagation of Untrusted W3C Baggage HeadersCritical
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 wrap or intercept the standard W3CBaggagePropagator at public network ingress with a validating boundary that enforces size caps and key allowlists.

Engineers MUST ALWAYS wrap or intercept the standard W3CBaggagePropagator at public network ingress with a validating boundary that enforces size caps and key allowlists.

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 allow unconstrained baggage extraction to propagate directly into downstream service calls or child trace contexts.

Engineers MUST NOT allow unconstrained baggage extraction to propagate directly into downstream service calls or child trace contexts.

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 strict hard limits

Code SHOULD enforce strict hard limits: total baggage header size <= 2048 bytes, maximum 16 key-value pairs, key length <= 64 bytes, and value length <= 256 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 reject or strip baggage entries containing non-printable ASCII, control characters, CRLF injections, or keys matching sensitive data patterns (e.g., authorization, token, secret, cookie).

Services MUST reject or strip baggage entries containing non-printable ASCII, control characters, CRLF injections, or keys matching sensitive data patterns (e.g., authorization, token, secret, cookie).

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 blindly elevate external baggage entries into span attributes or metrics labels without schema-validated key whitelisting to avoid high-cardinality state exhaustion.

Components NEVER blindly elevate external baggage entries into span attributes or metrics labels without schema-validated key whitelisting to avoid high-cardinality state exhaustion.

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

Enforces strict ingress size boundaries, allowlist filtering, and character sanitization on W3C Baggage headers entering distributed service perimeters. Prevents telemetry poisoning, header injection attacks, and memory exhaustion caused by unconstrained baggage propagation. 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 Ingestion and Unbounded Propagation of Untrusted W3C Baggage Headers) 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