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

OpenTelemetry W3C Baggage HMAC Cryptographic Attestation Invariant

Enforces cryptographic signing and strict constant-time HMAC validation of cross-boundary OpenTelemetry W3C Baggage entries to prevent header spoofing and privilege escalation. Propagated multi-tenant metadata such as tenant IDs, user identities, and capability scopes must include a deterministic HMAC signature attribute that is verified at trust boundaries. Downstream services must discard unsigned or invalidly signed baggage entries prior to contextual decision-making or log enrichment.

Prohibited Anti-Pattern: Blind Trust of Unsigned W3C Baggage Headers in Multi-Tenant Observability and Routing Pipelines

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry W3C Baggage HMAC Cryptographic Attestation Invariant - Enforces cryptographic signing and strict constant-time HMAC validation of cross-boundary OpenTelemetry W3C Baggage entries to prevent header spoofing and privilege escalation. Propagated multi-tenant metadata such as tenant IDs, user identities, and capability scopes must include a deterministic HMAC signature attribute that is verified at trust boundaries. Downstream services must discard unsigned or invalidly signed baggage entries prior to contextual decision-making or log enrichment.
globs: src/telemetry/**/*.{ts,js}, src/middleware/**/*.{ts,js}, src/tracing/**/*.{ts,js}, src/observability/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-baggage-hmac-attestation-invariant"
---

# OpenTelemetry W3C Baggage HMAC Cryptographic Attestation Invariant

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Blind Trust of Unsigned W3C Baggage Headers in Multi-Tenant Observability and Routing Pipelines

## System Constraints
You are a Principal Security and Observability Architect enforcing the OpenTelemetry W3C Baggage HMAC Cryptographic Attestation Invariant. In multi-tenant distributed systems, tracing headers (specifically W3C Baggage) cross untrusted trust boundaries. You must enforce that critical context items (e.g., tenantId, roles, routing flags) are cryptographically signed using an HMAC-SHA256 signature, validated using constant-time comparisons, and scrubbed immediately if unverified. Unauthenticated baggage mutations or blind ingestion of incoming baggage headers represent severe privilege escalation vulnerabilities and are strictly prohibited.

## Strict Guidelines
- Services MUST cryptographically attest sensitive W3C Baggage entries (e.g., `tenant_id`, `user_id`, `tier`) by appending a companion signature baggage key or signed baggage metadata token using HMAC-SHA256.
- Trust boundary entry points MUST validate incoming baggage signatures using constant-time comparison (`crypto.timingSafeEqual`) before binding context to OpenTelemetry Active Context.
- Engineers MUST NOT trust, forward, or consume baggage key-value pairs at ingress unless valid signature verification succeeds.
- If a signature check fails or is missing, services MUST scrub the compromised baggage entries, record an audit metric/event, and proceed only with clean trace context.
- Propagation logic MUST canonicalize baggage keys and values deterministically prior to HMAC generation to ensure consistency across heterogeneous platform runtimes.

## Bad vs Good Implementations
### Ingress Baggage Validation with HMAC Attestation Check

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly ingests unvalidated W3C baggage headers. Malicious upstream clients or intermediate proxies can inject arbitrary tenant_id or role values into distributed trace contexts, causing cross-tenant data leakage and privilege escalation in downstream services.
```typescript
import { Request, Response, NextFunction } from 'express';
import { baggage, context, propagation } from '@opentelemetry/api';

export function tracingMiddleware(req: Request, res: Response, next: NextFunction) {
  // VULNERABLE: Direct propagation ingestion without cryptographic attestation
  const extractedContext = propagation.extract(context.active(), req.headers);
  const currentBaggage = propagation.getBaggage(extractedContext);

  // Blindly trusting tenant_id from incoming untrusted W3C baggage header
  const tenantId = currentBaggage?.getEntry('tenant_id')?.value;
  if (tenantId) {
    (req as any).tenantId = tenantId; // Privilege escalation: caller can spoof tenantId
  }

  context.with(extractedContext, () => next());
}
```

#### Production Standard (Correct)
> **Standard**: Extracts context and enforces HMAC-SHA256 verification using constant-time string comparison over canonicalized baggage values. Any missing or invalid signature strips sensitive context keys, preventing tenant spoofing across perimeter boundaries.
```typescript
import { Request, Response, NextFunction } from 'express';
import { baggage, context, propagation } from '@opentelemetry/api';
import { createHmac, timingSafeEqual } from 'crypto';

const BAGGAGE_HMAC_SECRET = process.env.TELEMETRY_HMAC_SECRET!;
const SIGNED_KEYS = ['tenant_id', 'tier'] as const;

function verifyBaggageAttestation(entries: Record<string, string>, signature: string): boolean {
  if (!signature) return false;
  const canonicalPayload = SIGNED_KEYS
    .filter((k) => entries[k] !== undefined)
    .sort()
    .map((k) => `${k}=${entries[k]}`)
    .join(';');
  
  const expected = createHmac('sha256', BAGGAGE_HMAC_SECRET).update(canonicalPayload).digest('hex');
  const expectedBuf = Buffer.from(expected, 'hex');
  const incomingBuf = Buffer.from(signature, 'hex');

  return expectedBuf.length === incomingBuf.length && timingSafeEqual(expectedBuf, incomingBuf);
}

export function attestedTracingMiddleware(req: Request, res: Response, next: NextFunction) {
  const extractedContext = propagation.extract(context.active(), req.headers);
  const currentBaggage = propagation.getBaggage(extractedContext);

  const entries: Record<string, string> = {};
  currentBaggage?.getAllEntries().forEach(([k, v]) => {
    entries[k] = v.value;
  });

  const incomingSig = entries['sec_sig'] ?? '';
  const isValid = verifyBaggageAttestation(entries, incomingSig);

  let sanitizedBaggage = baggage.createBaggage();
  if (isValid) {
    currentBaggage?.getAllEntries().forEach(([k, v]) => {
      sanitizedBaggage = sanitizedBaggage.setEntry(k, v);
    });
    (req as any).tenantId = entries['tenant_id'];
  } else {
    // Drop unsigned or tampered claims; preserve non-sensitive operational fields only
    currentBaggage?.getAllEntries().forEach(([k, v]) => {
      if (!SIGNED_KEYS.includes(k as any) && k !== 'sec_sig') {
        sanitizedBaggage = sanitizedBaggage.setEntry(k, v);
      }
    });
  }

  const sanitizedContext = propagation.setBaggage(extractedContext, sanitizedBaggage);
  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 W3C Baggage HMAC Cryptographic Attestation Invariant

OpenTelemetry W3C Baggage HMAC Cryptographic Attestation Invariant defines an industrial-grade behavioral standard for devops engineering. Enforces cryptographic signing and strict constant-time HMAC validation of cross-boundary OpenTelemetry W3C Baggage entries to prevent header spoofing and privilege escalation. Propagated multi-tenant metadata such as tenant IDs, user identities, and capability scopes must include a deterministic HMAC signature attribute that is verified at trust boundaries. Downstream services must discard unsigned or invalidly signed baggage entries prior to contextual decision-making or log enrichment. 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 Trust of Unsigned W3C Baggage Headers in Multi-Tenant Observability and Routing Pipelines 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 Trust of Unsigned W3C Baggage Headers in Multi-Tenant Observability and Routing PipelinesCritical
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 cryptographically attest sensitive W3C Baggage entries (e.g., `tenant_id`, `user_id`, `tier`) by appending a companion signature baggage key or signed baggage metadata token using HMAC-SHA256.

Services MUST cryptographically attest sensitive W3C Baggage entries (e.g., `tenant_id`, `user_id`, `tier`) by appending a companion signature baggage key or signed baggage metadata token using HMAC-SHA256.

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

Trust boundary entry points MUST validate incoming baggage signatures using constant-time comparison (`crypto.timingSafeEqual`) before binding context to OpenTelemetry Active Context.

Trust boundary entry points MUST validate incoming baggage signatures using constant-time comparison (`crypto.timingSafeEqual`) before binding context to OpenTelemetry Active 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.
3

Engineers MUST NOT trust, forward, or consume baggage key-value pairs at ingress unless valid signature verification succeeds.

Engineers MUST NOT trust, forward, or consume baggage key-value pairs at ingress unless valid signature verification succeeds.

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

If a signature check fails or is missing, services MUST scrub the compromised baggage entries, record an audit metric/event, and proceed only with clean trace context.

If a signature check fails or is missing, services MUST scrub the compromised baggage entries, record an audit metric/event, and proceed only with clean trace 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.
5

Propagation logic MUST canonicalize baggage keys and values deterministically prior to HMAC generation to ensure consistency across heterogeneous platform runtimes.

Propagation logic MUST canonicalize baggage keys and values deterministically prior to HMAC generation to ensure consistency across heterogeneous platform runtimes.

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 HMAC Cryptographic Attestation Invariant critical for AI coding assistants?

Enforces cryptographic signing and strict constant-time HMAC validation of cross-boundary OpenTelemetry W3C Baggage entries to prevent header spoofing and privilege escalation. Propagated multi-tenant metadata such as tenant IDs, user identities, and capability scopes must include a deterministic HMAC signature attribute that is verified at trust boundaries. Downstream services must discard unsigned or invalidly signed baggage entries prior to contextual decision-making or log enrichment. 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 Trust of Unsigned W3C Baggage Headers in Multi-Tenant Observability and Routing Pipelines) 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