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

OpenTelemetry W3C Baggage Ingress/Egress Sanitization & Schema Filtering

Enforces strict allowlist validation, size quotas, and redaction on OpenTelemetry W3C Baggage metadata at service ingress and egress boundaries. Prevents arbitrary downstream data exfiltration, HTTP header amplification attacks (HTTP 431 Request Header Fields Too Large), and PII leaks caused by unconstrained distributed context propagation.

Prohibited Anti-Pattern: Blind Passthrough of Unvalidated W3C Baggage Key-Value Pairs Across Network Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry W3C Baggage Ingress/Egress Sanitization & Schema Filtering - Enforces strict allowlist validation, size quotas, and redaction on OpenTelemetry W3C Baggage metadata at service ingress and egress boundaries. Prevents arbitrary downstream data exfiltration, HTTP header amplification attacks (HTTP 431 Request Header Fields Too Large), and PII leaks caused by unconstrained distributed context propagation.
globs: src/telemetry/**/*.{ts,js}, src/middleware/**/*.{ts,js}, src/tracing/**/*.{ts,js}, **/instrumentation.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-w3c-baggage-sanitization-guardrail-opentelemetry-w3-609"
---

# OpenTelemetry W3C Baggage Ingress/Egress Sanitization & Schema Filtering

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Blind Passthrough of Unvalidated W3C Baggage Key-Value Pairs Across Network Boundaries

## System Constraints
You are a Principal Software Architect enforcing enterprise-grade OpenTelemetry W3C Baggage isolation and sanitization standards. You must ensure that no untrusted, unvalidated, or sensitive context flows across internal or external boundaries via the W3C Baggage header. All distributed tracing baggage entries must be filtered through an immutable allowlist, checked against strict length and character constraints, and stripped of potential PII before serialization or propagation.

## Strict Guidelines
- Engineers MUST ALWAYS implement a custom or wrapped `TextMapPropagator` that validates inbound and outbound Baggage against an immutable schema allowlist.
- Engineers MUST NOT configure raw `W3CBaggagePropagator` as a global propagator without an upstream sanitization filter or wrapping allowlist decorator.
- Services MUST enforce strict length constraints: maximum 16 permitted keys, maximum 64 bytes per key, and maximum 256 bytes per value.
- Components NEVER propagate unverified downstream metadata; unapproved keys received on ingress must be discarded before the active context is established.
- Engineers MUST strip all credentials, authorization tokens, user session tokens, and PII from Baggage contexts prior to any remote HTTP/gRPC invocation.

## Bad vs Good Implementations
### Secure Filtered Baggage Propagator vs Unconstrained Default Baggage

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Defaulting to `W3CBaggagePropagator` without schema controls forwards all received metadata. Adversaries can inject oversized headers or confidential claims (e.g., auth tokens) that get blind-forwarded to third-party endpoints or downstream microservices.
```typescript
import { W3CBaggagePropagator } from '@opentelemetry/core';
import { defaultTextMapGetter, defaultTextMapSetter, Context, ROOT_CONTEXT } from '@opentelemetry/api';

// VULNERABLE: Direct instantiation propagates arbitrary upstream headers downstream,
// enabling context amplification attacks, PII leaks, and HTTP 431 failures.
export const globalPropagator = new W3CBaggagePropagator();

export function injectBaggage(context: Context, carrier: Record<string, string>): void {
  // Forwards untrusted user-controlled headers directly into outgoing requests
  globalPropagator.inject(context, carrier, defaultTextMapSetter);
}
```

#### Production Standard (Correct)
> **Standard**: Wraps the standard W3CBaggagePropagator with explicit allowlist filtering, cardinality bounds, string-length checks, and safe character constraints, preventing arbitrary context leakage and downstream request amplification.
```typescript
import { TextMapPropagator, TextMapGetter, TextMapSetter, Context, baggageUtils, propagation } from '@opentelemetry/api';
import { W3CBaggagePropagator } from '@opentelemetry/core';

const ALLOWED_BAGGAGE_KEYS = new Set(['tenant.id', 'routing.cell', 'experiment.bucket'] as const);
const MAX_KEY_LENGTH = 64;
const MAX_VALUE_LENGTH = 256;
const MAX_ENTRIES = 8;

export class SanitizedBaggagePropagator implements TextMapPropagator {
  private readonly delegate = new W3CBaggagePropagator();

  inject(context: Context, carrier: unknown, setter: TextMapSetter): void {
    const activeBaggage = propagation.getBaggage(context);
    if (!activeBaggage) return;

    let sanitizedBaggage = propagation.createBaggage();
    let count = 0;

    for (const entry of activeBaggage.getAllEntries()) {
      if (count >= MAX_ENTRIES) break;
      const [key, item] = entry;
      
      if (
        ALLOWED_BAGGAGE_KEYS.has(key as any) &&
        key.length <= MAX_KEY_LENGTH &&
        item.value.length <= MAX_VALUE_LENGTH &&
        /^[a-zA-Z0-9_.-]+$/.test(item.value)
      ) {
        sanitizedBaggage = sanitizedBaggage.setEntry(key, { value: item.value });
        count++;
      }
    }

    const sanitizedContext = propagation.setBaggage(context, sanitizedBaggage);
    this.delegate.inject(sanitizedContext, carrier, setter);
  }

  extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {
    const rawContext = this.delegate.extract(context, carrier, getter);
    const rawBaggage = propagation.getBaggage(rawContext);
    if (!rawBaggage) return context;

    let cleanedBaggage = propagation.createBaggage();
    for (const [key, item] of rawBaggage.getAllEntries()) {
      if (ALLOWED_BAGGAGE_KEYS.has(key as any) && item.value.length <= MAX_VALUE_LENGTH) {
        cleanedBaggage = cleanedBaggage.setEntry(key, { value: item.value });
      }
    }

    return propagation.setBaggage(context, cleanedBaggage);
  }

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

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenTelemetry W3C Baggage Ingress/Egress Sanitization & Schema Filtering

OpenTelemetry W3C Baggage Ingress/Egress Sanitization & Schema Filtering defines an industrial-grade behavioral standard for devops engineering. Enforces strict allowlist validation, size quotas, and redaction on OpenTelemetry W3C Baggage metadata at service ingress and egress boundaries. Prevents arbitrary downstream data exfiltration, HTTP header amplification attacks (HTTP 431 Request Header Fields Too Large), and PII leaks caused by unconstrained distributed context 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 Passthrough of Unvalidated W3C Baggage Key-Value Pairs Across Network 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 Passthrough of Unvalidated W3C Baggage Key-Value Pairs Across Network 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

Engineers MUST ALWAYS implement a custom or wrapped `TextMapPropagator` that validates inbound and outbound Baggage against an immutable schema allowlist.

Engineers MUST ALWAYS implement a custom or wrapped `TextMapPropagator` that validates inbound and outbound Baggage against an immutable schema allowlist.

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 configure raw `W3CBaggagePropagator` as a global propagator without an upstream sanitization filter or wrapping allowlist decorator.

Engineers MUST NOT configure raw `W3CBaggagePropagator` as a global propagator without an upstream sanitization filter or wrapping allowlist decorator.

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 enforce strict length constraints

Services MUST enforce strict length constraints: maximum 16 permitted keys, maximum 64 bytes per key, 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.
4

Components NEVER propagate unverified downstream metadata

Components NEVER propagate unverified downstream metadata; unapproved keys received on ingress must be discarded before the active context is established.

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

Engineers MUST strip all credentials, authorization tokens, user session tokens, and PII from Baggage contexts prior to any remote HTTP/gRPC invocation.

Engineers MUST strip all credentials, authorization tokens, user session tokens, and PII from Baggage contexts prior to any remote HTTP/gRPC invocation.

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/Egress Sanitization & Schema Filtering critical for AI coding assistants?

Enforces strict allowlist validation, size quotas, and redaction on OpenTelemetry W3C Baggage metadata at service ingress and egress boundaries. Prevents arbitrary downstream data exfiltration, HTTP header amplification attacks (HTTP 431 Request Header Fields Too Large), and PII leaks caused by unconstrained distributed context 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 Passthrough of Unvalidated W3C Baggage Key-Value Pairs Across Network 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