This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: spiffe-spire-ephemeral-mtls-attestation-standard

Mandate SPIFFE/SPIRE Workload Attestation and Ephemeral X.509-SVID mTLS

Enforces dynamic, kernel-attested workload identities via SPIRE Workload API Unix Domain Sockets, forbidding long-lived credentials, static API secrets, and unverified TLS peer certificates. Mandates continuous SVID rotation in memory and strict SPIFFE ID SAN validation on all inter-service communication.

Prohibited Anti-Pattern: Bypassing Workload Attestation via Static Secrets or Skipping SPIFFE ID Peer Verification in TLS Handshakes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Mandate SPIFFE/SPIRE Workload Attestation and Ephemeral X.509-SVID mTLS - Enforces dynamic, kernel-attested workload identities via SPIRE Workload API Unix Domain Sockets, forbidding long-lived credentials, static API secrets, and unverified TLS peer certificates. Mandates continuous SVID rotation in memory and strict SPIFFE ID SAN validation on all inter-service communication.
globs: src/**/*.{ts,tsx,js,jsx}, infrastructure/**/*.{yaml,json}, proto/**/*.proto
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/spiffe-spire-ephemeral-mtls-attestation-standard"
---

# Mandate SPIFFE/SPIRE Workload Attestation and Ephemeral X.509-SVID mTLS

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Bypassing Workload Attestation via Static Secrets or Skipping SPIFFE ID Peer Verification in TLS Handshakes

## System Constraints
You are a Principal Security Architect enforcing zero-trust SPIFFE/SPIRE microsegmentation with ephemeral mTLS workload attestation. You must reject any hardcoded credentials, long-lived service account tokens, static TLS certificates, or non-attested inter-service communication. Mandate dynamic X.509-SVID streaming via the SPIFFE Workload API Unix Domain Socket, programmatic in-memory key rotation, and strict SPIFFE ID validation against explicit trust domains and workload selectors.

## Strict Guidelines
- Engineers MUST ALWAYS fetch X.509-SVIDs (SPIFFE Verifiable Identity Documents) dynamically over the SPIFFE Workload API Unix Domain Socket (e.g., unix:///run/spire/sockets/agent.sock).
- Engineers MUST NOT persist private keys or X.509-SVID certificates to local disk, environment variables, or config maps.
- Services MUST validate the peer's SPIFFE ID in the Subject Alternative Name (SAN) URI extension against an explicit whitelist of allowed trust domains and service paths during the mTLS handshake.
- Code SHOULD implement continuous X509Source listeners to automatically reload renewed certificates in memory without restarting the process or dropping connections.
- Components NEVER accept incoming mTLS traffic or initiate outbound requests using default TLS trust stores; trust bundles MUST be sourced directly from the SPIFFE Workload API bundle stream.

## Bad vs Good Implementations
### Configuring Node.js mTLS Client with SPIFFE Workload Attestation vs. Static Certs

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Relies on static certificates on disk and long-lived API secrets in environment variables. Lacks kernel-level workload attestation (cgroups, UID/GID, namespace) and fails to validate the peer's SPIFFE identity SAN, leaving the connection vulnerable to secret theft and lateral movement.
```typescript
import https from 'node:https';
import fs from 'node:fs';

// ANTI-PATTERN: Using static filesystem certificates and API keys
// Certificates are long-lived, not kernel-attested, and prone to leakage
const agent = new https.Agent({
  cert: fs.readFileSync('/etc/ssl/certs/service.crt'),
  key: fs.readFileSync('/etc/ssl/certs/service.key'),
  ca: fs.readFileSync('/etc/ssl/certs/ca.crt'),
  rejectUnauthorized: true,
});

export async function callPaymentService(payload: unknown): Promise<void> {
  const req = https.request('https://payment-service.internal:8443/process', {
    method: 'POST',
    agent,
    headers: {
      'Authorization': `Bearer ${process.env.PAYMENT_API_SECRET}`,
      'Content-Type': 'application/json',
    },
  });
  req.write(JSON.stringify(payload));
  req.end();
}
```

#### Production Standard (Correct)
> **Standard**: Connects to the SPIRE agent via Unix Domain Socket to acquire dynamically rotated X.509-SVIDs and trust bundles attested at the kernel level. Validates the peer's SPIFFE ID URI in the Subject Alternative Name and avoids static tokens or long-lived secrets.
```typescript
import tls from 'node:tls';
import https from 'node:https';
import { WorkloadApiClient } from '@spiffe/spiffe-client';

// PRODUCTION FIX: Dynamically stream ephemeral X.509-SVIDs from local SPIRE agent UDS
const EXPECTED_PEER_SPIFFE_ID = 'spiffe://prod.internal/ns/payments/sa/payment-service';
const SPIRE_SOCKET_PATH = 'unix:///run/spire/sockets/agent.sock';

export class SpiffeMtlsClient {
  private workloadClient: WorkloadApiClient;
  private httpsAgent!: https.Agent;

  constructor() {
    this.workloadClient = new WorkloadApiClient({ socketPath: SPIRE_SOCKET_PATH });
  }

  public async initialize(): Promise<void> {
    // Watch X509Context stream from SPIRE agent for auto-rotation
    const svidWatcher = await this.workloadClient.watchX509Context();

    svidWatcher.on('data', (x509Context) => {
      const defaultSvid = x509Context.getDefaultSvid();
      const trustBundle = x509Context.getTrustBundle();

      this.httpsAgent = new https.Agent({
        cert: defaultSvid.certBuffer,
        key: defaultSvid.keyBuffer,
        ca: trustBundle.bundleBuffer,
        rejectUnauthorized: true,
        checkServerIdentity: (host, cert) => {
          // Invariant: Verify peer SPIFFE ID in Subject Alternative Name (SAN)
          const altNames = cert.subjectaltname?.split(', ').map(s => s.trim()) ?? [];
          const uriSans = altNames
            .filter(san => san.startsWith('URI:'))
            .map(san => san.replace('URI:', ''));

          if (!uriSans.includes(EXPECTED_PEER_SPIFFE_ID)) {
            throw new Error(`SPIFFE ID verification failed. Expected ${EXPECTED_PEER_SPIFFE_ID}, received ${uriSans.join(', ')}`);
          }
          return undefined; // Hostname check passed via SPIFFE SAN validation
        },
      });
    });
  }

  public getAgent(): https.Agent {
    if (!this.httpsAgent) {
      throw new Error('SpiffeMtlsClient has not received initial X.509-SVID from agent socket');
    }
    return this.httpsAgent;
  }
}
```

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: Mandate SPIFFE/SPIRE Workload Attestation and Ephemeral X.509-SVID mTLS

Mandate SPIFFE/SPIRE Workload Attestation and Ephemeral X.509-SVID mTLS defines an industrial-grade behavioral standard for security engineering. Enforces dynamic, kernel-attested workload identities via SPIRE Workload API Unix Domain Sockets, forbidding long-lived credentials, static API secrets, and unverified TLS peer certificates. Mandates continuous SVID rotation in memory and strict SPIFFE ID SAN validation on all inter-service communication. 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: Bypassing Workload Attestation via Static Secrets or Skipping SPIFFE ID Peer Verification in TLS Handshakes 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 DriftBypassing Workload Attestation via Static Secrets or Skipping SPIFFE ID Peer Verification in TLS HandshakesCritical
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 fetch X.509-SVIDs (SPIFFE Verifiable Identity Documents) dynamically over the SPIFFE Workload API Unix Domain Socket (e.g., unix

Engineers MUST ALWAYS fetch X.509-SVIDs (SPIFFE Verifiable Identity Documents) dynamically over the SPIFFE Workload API Unix Domain Socket (e.g., unix:///run/spire/sockets/agent.sock).

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 persist private keys or X.509-SVID certificates to local disk, environment variables, or config maps.

Engineers MUST NOT persist private keys or X.509-SVID certificates to local disk, environment variables, or config 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.
3

Services MUST validate the peer's SPIFFE ID in the Subject Alternative Name (SAN) URI extension against an explicit whitelist of allowed trust domains and service paths during the mTLS handshake.

Services MUST validate the peer's SPIFFE ID in the Subject Alternative Name (SAN) URI extension against an explicit whitelist of allowed trust domains and service paths during the mTLS handshake.

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 implement continuous X509Source listeners to automatically reload renewed certificates in memory without restarting the process or dropping connections.

Code SHOULD implement continuous X509Source listeners to automatically reload renewed certificates in memory without restarting the process or dropping connections.

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 accept incoming mTLS traffic or initiate outbound requests using default TLS trust stores

Components NEVER accept incoming mTLS traffic or initiate outbound requests using default TLS trust stores; trust bundles MUST be sourced directly from the SPIFFE Workload API bundle stream.

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 Mandate SPIFFE/SPIRE Workload Attestation and Ephemeral X.509-SVID mTLS critical for AI coding assistants?

Enforces dynamic, kernel-attested workload identities via SPIRE Workload API Unix Domain Sockets, forbidding long-lived credentials, static API secrets, and unverified TLS peer certificates. Mandates continuous SVID rotation in memory and strict SPIFFE ID SAN validation on all inter-service communication. 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 (Bypassing Workload Attestation via Static Secrets or Skipping SPIFFE ID Peer Verification in TLS Handshakes) 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

Mandate