This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: rfc-9421-http-message-signatures-gateway-verification

RFC 9421 HTTP Message Signatures End-to-End Cryptographic Invariants

Enforces deterministic, non-repudiable RFC 9421 HTTP Message Signature verification at edge gateways and multi-cluster mesh boundaries. Prevents man-in-the-middle header tampering, request replay attacks, and content alteration across untrusted ingress networks by binding derived components, canonical headers, and raw digest hashes to cryptographic public key infrastructures. Guarantees end-to-end payload immutability prior to microservice dispatch.

Prohibited Anti-Pattern: Trusting Ingress Proxies Without Full RFC 9421 Canonical Component and Content-Digest Verification

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: RFC 9421 HTTP Message Signatures End-to-End Cryptographic Invariants - Enforces deterministic, non-repudiable RFC 9421 HTTP Message Signature verification at edge gateways and multi-cluster mesh boundaries. Prevents man-in-the-middle header tampering, request replay attacks, and content alteration across untrusted ingress networks by binding derived components, canonical headers, and raw digest hashes to cryptographic public key infrastructures. Guarantees end-to-end payload immutability prior to microservice dispatch.
globs: src/middleware/**/*.{ts,js}, src/gateway/**/*.{ts,js}, src/security/**/*.{ts,js}, src/plugins/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/rfc-9421-http-message-signatures-gateway-verification"
---

# RFC 9421 HTTP Message Signatures End-to-End Cryptographic Invariants

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Trusting Ingress Proxies Without Full RFC 9421 Canonical Component and Content-Digest Verification

## System Constraints
You are a Principal Security Architect enforcing RFC 9421 HTTP Message Signatures across all gateway and mesh boundary implementations. You must reject any signature verification pipeline that relies on parsed or mutated request bodies, omits cryptographic Content-Digest checks, skips RFC 9421 derived components (@method, @target-uri, @authority), or permits timestamp skew beyond strict TTL envelopes. Mandate Ed25519 or ECDSA P-256 with deterministic canonical serialization matching RFC 8941 Structured Fields.

## Strict Guidelines
- Engineers MUST ALWAYS verify the 'content-digest' (RFC 9530) over the exact raw byte stream before executing RFC 9421 signature verification on incoming requests containing a payload.
- Engineers MUST ALWAYS include and validate mandatory derived components in signature coverage: '@method', '@authority', and '@target-uri' or '@path'.
- Engineers MUST ALWAYS enforce the '@signature-params' component and reject signatures missing explicit 'created', 'keyid', and 'alg' parameters.
- Engineers MUST NOT accept signature creation timestamps ('created') older than 300 seconds, nor signatures with 'expires' timestamps exceeding the verified gateway epoch.
- Engineers MUST NOT read incoming HTTP headers as mutable objects or perform signature validation on transformed/re-serialized header maps.
- Services MUST verify signatures using pre-registered public keys indexed by 'keyid' fetched exclusively via authenticated, cached key stores (JWKS/KMS) and never from unauthenticated remote URLs provided in request headers.
- Components NEVER proceed with route dispatching if any covered component in the 'Signature-Input' specification fails canonical serialization or signature matching.

## Bad vs Good Implementations
### RFC 9421 Edge Verification Middleware with Canonical Signature Input Reconstruction

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The vulnerable code bypasses RFC 9421 specifications entirely. It validates parsed, re-serialized JSON (enabling JSON parameter injection), ignores derived components like @method and @target-uri, does not enforce the RFC 9530 Content-Digest header, skips canonical Structured Field Serialization, and lacks expiration/replay protections.
```typescript
import { Request, Response, NextFunction } from 'express';
import * as crypto from 'crypto';

export function badVerifySignature(req: Request, res: Response, next: NextFunction) {
  const sig = req.headers['signature'] as string;
  const keyId = req.headers['x-key-id'] as string;
  
  // VULNERABILITY 1: Trusting arbitrary keyId from custom header without structured parse
  // VULNERABILITY 2: Verifying parsed JSON body instead of raw bytes (allows JSON malleability)
  // VULNERABILITY 3: Missing RFC 9421 canonicalization (Structured Field Values) and derived components (@method, @target-uri)
  // VULNERABILITY 4: Missing replay check and created/expires timestamp validation
  const rawData = JSON.stringify(req.body);
  const publicKey = getPublicKey(keyId);

  const verifier = crypto.createVerify('RSA-SHA256');
  verifier.update(rawData);
  
  if (!verifier.verify(publicKey, Buffer.from(sig, 'base64'))) {
    return res.status(401).send('Invalid Signature');
  }
  next();
}

declare function getPublicKey(id: string): string;
```

#### Production Standard (Correct)
> **Standard**: Implements RFC 9421 invariants by verifying the RFC 9530 Content-Digest over immutable raw payload bytes via constant-time comparisons, verifying mandatory derived components (@method, @target-uri), checking timestamp replay boundaries (<300s skew), and executing signature verification over the strict canonical Structured Field base.
```typescript
import { Request, Response, NextFunction } from 'express';
import * as crypto from 'crypto';

interface SignatureParams {
  components: string[];
  created: number;
  expires?: number;
  keyId: string;
  alg: string;
}

export async function rfc9421VerificationMiddleware(
  req: Request & { rawBody?: Buffer },
  res: Response,
  next: NextFunction
): Promise<void> {
  try {
    const sigInputHeader = req.headers['signature-input'] as string | undefined;
    const sigHeader = req.headers['signature'] as string | undefined;

    if (!sigInputHeader || !sigHeader || !req.rawBody) {
      res.status(401).json({ error: 'Missing RFC 9421 verification components' });
      return;
    }

    // 1. Enforce RFC 9530 Content-Digest validation on raw bytes
    const incomingDigest = req.headers['content-digest'] as string | undefined;
    if (req.method !== 'GET' && req.method !== 'HEAD') {
      if (!incomingDigest) {
        res.status(401).json({ error: 'Missing Content-Digest header' });
        return;
      }
      const expectedDigest = `sha-256=:${crypto.createHash('sha256').update(req.rawBody).digest('base64')}:`;
      if (!crypto.timingSafeEqual(Buffer.from(incomingDigest), Buffer.from(expectedDigest))) {
        res.status(401).json({ error: 'Content-Digest mismatch' });
        return;
      }
    }

    // 2. Parse Signature-Input label: sig1=("@method" "@target-uri" "content-digest");created=1618884475;keyid="key-1";alg="ed25519"
    const parsedParams = parseSignatureInput(sigInputHeader, 'sig1');
    const now = Math.floor(Date.now() / 1000);
    if (now - parsedParams.created > 300 || (parsedParams.expires && now > parsedParams.expires)) {
      res.status(401).json({ error: 'Signature expired or timestamp skewed' });
      return;
    }

    // 3. Construct Canonical RFC 9421 Signature Base
    const canonicalBase = constructSignatureBase(req, parsedParams, sigInputHeader);
    const signatureBytes = extractSignatureBytes(sigHeader, 'sig1');
    const publicKey = await fetchTrustedPublicKey(parsedParams.keyId);

    // 4. Verify cryptographic signature over deterministic canonical base
    const isValid = crypto.verify(null, Buffer.from(canonicalBase, 'utf8'), publicKey, signatureBytes);
    if (!isValid) {
      res.status(401).json({ error: 'RFC 9421 Signature verification failed' });
      return;
    }

    next();
  } catch (err) {
    res.status(401).json({ error: 'Cryptographic validation error' });
  }
}

declare function parseSignatureInput(header: string, label: string): SignatureParams;
declare function constructSignatureBase(req: Request, params: SignatureParams, header: string): string;
declare function extractSignatureBytes(header: string, label: string): Buffer;
declare function fetchTrustedPublicKey(keyId: string): Promise<crypto.KeyObject>;
```

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: RFC 9421 HTTP Message Signatures End-to-End Cryptographic Invariants

RFC 9421 HTTP Message Signatures End-to-End Cryptographic Invariants defines an industrial-grade behavioral standard for security engineering. Enforces deterministic, non-repudiable RFC 9421 HTTP Message Signature verification at edge gateways and multi-cluster mesh boundaries. Prevents man-in-the-middle header tampering, request replay attacks, and content alteration across untrusted ingress networks by binding derived components, canonical headers, and raw digest hashes to cryptographic public key infrastructures. Guarantees end-to-end payload immutability prior to microservice dispatch. 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: Trusting Ingress Proxies Without Full RFC 9421 Canonical Component and Content-Digest Verification 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 DriftTrusting Ingress Proxies Without Full RFC 9421 Canonical Component and Content-Digest VerificationCritical
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 verify the 'content-digest' (RFC 9530) over the exact raw byte stream before executing RFC 9421 signature verification on incoming requests containing a payload.

Engineers MUST ALWAYS verify the 'content-digest' (RFC 9530) over the exact raw byte stream before executing RFC 9421 signature verification on incoming requests containing a payload.

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 ALWAYS include and validate mandatory derived components in signature coverage

Engineers MUST ALWAYS include and validate mandatory derived components in signature coverage: '@method', '@authority', and '@target-uri' or '@path'.

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 ALWAYS enforce the '@signature-params' component and reject signatures missing explicit 'created', 'keyid', and 'alg' parameters.

Engineers MUST ALWAYS enforce the '@signature-params' component and reject signatures missing explicit 'created', 'keyid', and 'alg' parameters.

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 NOT accept signature creation timestamps ('created') older than 300 seconds, nor signatures with 'expires' timestamps exceeding the verified gateway epoch.

Engineers MUST NOT accept signature creation timestamps ('created') older than 300 seconds, nor signatures with 'expires' timestamps exceeding the verified gateway epoch.

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 NOT read incoming HTTP headers as mutable objects or perform signature validation on transformed/re-serialized header maps.

Engineers MUST NOT read incoming HTTP headers as mutable objects or perform signature validation on transformed/re-serialized header maps.

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.
6

Services MUST verify signatures using pre-registered public keys indexed by 'keyid' fetched exclusively via authenticated, cached key stores (JWKS/KMS) and never from unauthenticated remote URLs provided in request headers.

Services MUST verify signatures using pre-registered public keys indexed by 'keyid' fetched exclusively via authenticated, cached key stores (JWKS/KMS) and never from unauthenticated remote URLs provided in request headers.

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.
7

Components NEVER proceed with route dispatching if any covered component in the 'Signature-Input' specification fails canonical serialization or signature matching.

Components NEVER proceed with route dispatching if any covered component in the 'Signature-Input' specification fails canonical serialization or signature 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is RFC 9421 HTTP Message Signatures End-to-End Cryptographic Invariants critical for AI coding assistants?

Enforces deterministic, non-repudiable RFC 9421 HTTP Message Signature verification at edge gateways and multi-cluster mesh boundaries. Prevents man-in-the-middle header tampering, request replay attacks, and content alteration across untrusted ingress networks by binding derived components, canonical headers, and raw digest hashes to cryptographic public key infrastructures. Guarantees end-to-end payload immutability prior to microservice dispatch. 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 (Trusting Ingress Proxies Without Full RFC 9421 Canonical Component and Content-Digest Verification) 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

RFC