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

OpenTelemetry W3C Baggage Cryptographic Integrity Envelope Standard

Enforces strict HMAC-SHA256 signature verification and deterministic schema whitelisting on outbound and inbound W3C Baggage context propagation. Prevents tenant impersonation, privilege escalation, and log injection attacks across untrusted multi-cloud service mesh boundaries by rejecting forged or unverified contextual key-value pairs.

Prohibited Anti-Pattern: Propagating Unauthenticated W3C Baggage Headers Blindly Across Distributed Service Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry W3C Baggage Cryptographic Integrity Envelope Standard - Enforces strict HMAC-SHA256 signature verification and deterministic schema whitelisting on outbound and inbound W3C Baggage context propagation. Prevents tenant impersonation, privilege escalation, and log injection attacks across untrusted multi-cloud service mesh boundaries by rejecting forged or unverified contextual key-value pairs.
globs: src/**/telemetry/**/*.{ts,js,go,py}, src/**/tracing/**/*.{ts,js,go,py}, src/**/middleware/**/*.{ts,js,go,py}, src/**/instrumentation/**/*.{ts,js,go,py}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-baggage-hmac-integrity-envelope"
---

# OpenTelemetry W3C Baggage Cryptographic Integrity Envelope Standard

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Propagating Unauthenticated W3C Baggage Headers Blindly Across Distributed Service Boundaries

## System Constraints
You are a Principal Security and Telemetry Architect enforcing the OpenTelemetry W3C Baggage Cryptographic Integrity Envelope Standard. Mandate that all contextual propagation headers mutating routing decisions, tenant scope, or audit state are rigorously signed using HMAC-SHA256 signatures, validated against canonical whitelists, and rejected upon signature mismatch or key schema violations.

## Strict Guidelines
- Engineers MUST ALWAYS cryptographically sign outbound W3C Baggage metadata using HMAC-SHA256 and append the signature as a deterministic envelope property (e.g., `sig=<hex>`) prior to transmission across network boundaries.
- Engineers MUST validate and strip all unrecognized or non-whitelisted baggage keys before propagating context to downstream services.
- Services MUST reject incoming baggage headers and scrub context if the cryptographic signature is missing, expired, or fails verification against the active service mesh shared secret rotation set.
- Code SHOULD enforce deterministic key sorting and canonical string serialization before computing or verifying baggage HMAC digests.
- Components NEVER rely on untrusted incoming baggage entries (e.g., `tenant_id`, `role`, `org_id`) for authorization or routing without cryptographically validating their integrity signature.

## Bad vs Good Implementations
### Inbound Baggage Context Sanitization and HMAC Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accepts unverified W3C Baggage headers directly into application context. Malicious actors or breached perimeter nodes can inject arbitrary `tenant_id` baggage values to execute tenant impersonation and poison downstream audit logs.
```typescript
import { Context, Baggage, propagation } from '@opentelemetry/api';
import { Request, Response, NextFunction } from 'express';

export function telemetryMiddleware(req: Request, res: Response, next: NextFunction): void {
  // Anti-pattern: Trusting incoming W3C Baggage implicitly without signature check
  const extractedContext: Context = propagation.extract(req.headers);
  const baggage: Baggage | undefined = propagation.getBaggage(extractedContext);

  if (baggage) {
    // DANGEROUS: Untrusted tenant_id directly accepted from upstream payload
    const tenantId = baggage.getEntry('tenant_id')?.value;
    req.headers['x-tenant-id'] = tenantId;
  }

  propagation.inject(extractedContext, req.headers);
  next();
}
```

#### Production Standard (Correct)
> **Standard**: Validates the cryptographic HMAC signature against a strictly whitelisted subset of canonical baggage entries using constant-time comparison. Rejects replayed timestamps and drops unverified context before downstream propagation.
```typescript
import { Context, Baggage, propagation, trace } from '@opentelemetry/api';
import { Request, Response, NextFunction } from 'express';
import { createHmac, timingSafeEqual } from 'crypto';

const ALLOWED_KEYS = new Set(['tenant_id', 'tier', 'sig', 'ts']);
const BAGGAGE_SECRET = process.env.MESH_BAGGAGE_HMAC_SECRET!;
const MAX_BAGGAGE_SKEW_MS = 60_000;

function verifyAndSanitizeBaggage(incomingBaggage: Baggage): Baggage | undefined {
  const entries = incomingBaggage.getAllEntries();
  const signatureEntry = incomingBaggage.getEntry('sig');
  const timestampEntry = incomingBaggage.getEntry('ts');

  if (!signatureEntry || !timestampEntry) return undefined;

  const timestamp = parseInt(timestampEntry.value, 10);
  if (Number.isNaN(timestamp) || Math.abs(Date.now() - timestamp) > MAX_BAGGAGE_SKEW_MS) {
    return undefined;
  }

  const payload = entries
    .filter(([k]) => ALLOWED_KEYS.has(k) && k !== 'sig')
    .sort(([a], [b]) => a.localeCompare(b))
    .map(([k, v]) => `${k}=${v.value}`)
    .join(';');

  const expectedSig = createHmac('sha256', BAGGAGE_SECRET).update(payload).digest('hex');
  const actualSig = signatureEntry.value;

  if (expectedSig.length !== actualSig.length || !timingSafeEqual(Buffer.from(expectedSig), Buffer.from(actualSig))) {
    return undefined;
  }

  let sanitized = propagation.createBaggage();
  for (const [k, v] of entries) {
    if (ALLOWED_KEYS.has(k)) {
      sanitized = sanitized.setEntry(k, v);
    }
  }
  return sanitized;
}

export function secureTelemetryMiddleware(req: Request, res: Response, next: NextFunction): void {
  const extractedContext: Context = propagation.extract(req.headers);
  const incomingBaggage: Baggage | undefined = propagation.getBaggage(extractedContext);

  let safeContext = extractedContext;
  if (incomingBaggage) {
    const verifiedBaggage = verifyAndSanitizeBaggage(incomingBaggage);
    safeContext = verifiedBaggage 
      ? propagation.setBaggage(extractedContext, verifiedBaggage) 
      : propagation.deleteBaggage(extractedContext);
  }

  trace.setSpan(safeContext, trace.getSpan(extractedContext)!);
  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 Cryptographic Integrity Envelope Standard

OpenTelemetry W3C Baggage Cryptographic Integrity Envelope Standard defines an industrial-grade behavioral standard for devops engineering. Enforces strict HMAC-SHA256 signature verification and deterministic schema whitelisting on outbound and inbound W3C Baggage context propagation. Prevents tenant impersonation, privilege escalation, and log injection attacks across untrusted multi-cloud service mesh boundaries by rejecting forged or unverified contextual key-value pairs. 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: Propagating Unauthenticated W3C Baggage Headers Blindly Across Distributed Service 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 DriftPropagating Unauthenticated W3C Baggage Headers Blindly Across Distributed Service 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 cryptographically sign outbound W3C Baggage metadata using HMAC-SHA256 and append the signature as a deterministic envelope property (e.g., `sig=<hex>`) prior to transmission across network boundaries.

Engineers MUST ALWAYS cryptographically sign outbound W3C Baggage metadata using HMAC-SHA256 and append the signature as a deterministic envelope property (e.g., `sig=<hex>`) prior to transmission across 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.
2

Engineers MUST validate and strip all unrecognized or non-whitelisted baggage keys before propagating context to downstream services.

Engineers MUST validate and strip all unrecognized or non-whitelisted baggage keys before propagating context to 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.
3

Services MUST reject incoming baggage headers and scrub context if the cryptographic signature is missing, expired, or fails verification against the active service mesh shared secret rotation set.

Services MUST reject incoming baggage headers and scrub context if the cryptographic signature is missing, expired, or fails verification against the active service mesh shared secret rotation set.

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

Code SHOULD enforce deterministic key sorting and canonical string serialization before computing or verifying baggage HMAC digests.

Code SHOULD enforce deterministic key sorting and canonical string serialization before computing or verifying baggage HMAC digests.

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 rely on untrusted incoming baggage entries (e.g., `tenant_id`, `role`, `org_id`) for authorization or routing without cryptographically validating their integrity signature.

Components NEVER rely on untrusted incoming baggage entries (e.g., `tenant_id`, `role`, `org_id`) for authorization or routing without cryptographically validating their integrity signature.

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 Cryptographic Integrity Envelope Standard critical for AI coding assistants?

Enforces strict HMAC-SHA256 signature verification and deterministic schema whitelisting on outbound and inbound W3C Baggage context propagation. Prevents tenant impersonation, privilege escalation, and log injection attacks across untrusted multi-cloud service mesh boundaries by rejecting forged or unverified contextual key-value pairs. 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 (Propagating Unauthenticated W3C Baggage Headers Blindly Across Distributed Service 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