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

SPIFFE/SPIRE Dynamic SVID Attestation & Ephemeral mTLS Enforcement

Mandates non-blocking runtime integration with the SPIFFE Workload API via local Unix Domain Socket (UDS) to dynamically stream short-lived X.509 SVIDs and SPIFFE trust bundles. Prohibits mounting static certificates, private keys, or long-lived credentials into workload filesystems. Enforces automated, in-memory rotation of mTLS contexts and strict SPIFFE ID SAN validation on all inter-service communications.

Prohibited Anti-Pattern: Baking Static X.509 PEM Files and Long-Lived Credentials into Container Filesystems

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: SPIFFE/SPIRE Dynamic SVID Attestation & Ephemeral mTLS Enforcement - Mandates non-blocking runtime integration with the SPIFFE Workload API via local Unix Domain Socket (UDS) to dynamically stream short-lived X.509 SVIDs and SPIFFE trust bundles. Prohibits mounting static certificates, private keys, or long-lived credentials into workload filesystems. Enforces automated, in-memory rotation of mTLS contexts and strict SPIFFE ID SAN validation on all inter-service communications.
globs: src/**/*.{ts,tsx,js,mjs}, pkg/**/*.{go}, internal/**/*.{go}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/spiffe-spire-svid-attestation-standard"
---

# SPIFFE/SPIRE Dynamic SVID Attestation & Ephemeral mTLS Enforcement

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Baking Static X.509 PEM Files and Long-Lived Credentials into Container Filesystems

## System Constraints
You are a Principal Security Architect enforcing the SPIFFE/SPIRE Dynamic SVID Ephemeral Workload Attestation Standard. You must mandate zero-trust workload identities where identities are cryptographically attested at runtime via the SPIFFE Workload API over a local Unix domain socket. Forbid any persistence of private keys to persistent disks or container layers. Enforce short-lived X509-SVIDs (<= 1 hour), dynamic in-memory rotation without process restarts, strict trust domain boundary validation, and exact SAN parsing against expected SPIFFE ID patterns.

## Strict Guidelines
- Engineers MUST ALWAYS fetch X.509 SVIDs and federated trust bundles dynamically from the SPIRE Agent Workload API over a local Unix Domain Socket (SPIFFE_ENDPOINT_SOCKET).
- Engineers MUST NOT read static private keys or certificate bundles from local disk, ConfigMaps, or environment variables in microservice runtimes.
- Services MUST subscribe to the Workload API X.509 stream and dynamically reload TLS SecureContexts in-memory prior to SVID expiration without dropping active connections.
- Code SHOULD validate peer certificates by inspecting the Subject Alternative Name (SAN) URI for valid SPIFFE IDs conforming to spiffe://<trust-domain>/<workload-path>.
- Components NEVER accept arbitrary CA certificates or bypass trust domain checks when terminating or initiating mTLS connections.

## Bad vs Good Implementations
### Dynamic SPIFFE SVID In-Memory Rotation vs Static File Loading

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Loads static certificates and private keys from the filesystem into memory once at startup. When credentials expire or are revoked, the service fails or requires a container restart. Does not validate peer SPIFFE IDs, granting broad perimeter access to any workload holding a certificate signed by the shared CA.
```typescript
import fs from 'node:fs';
import https from 'node:https';
import tls from 'node:tls';

// ANTI-PATTERN: Static file mounting with no rotation and unvalidated peer identity
const staticOptions: https.ServerOptions = {
  key: fs.readFileSync('/etc/ssl/certs/service.key'),
  cert: fs.readFileSync('/etc/ssl/certs/service.crt'),
  ca: fs.readFileSync('/etc/ssl/certs/ca.crt'),
  requestCert: true,
  rejectUnauthorized: true
};

export const server = https.createServer(staticOptions, (req, res) => {
  // Flaw: No SPIFFE ID authorization; any client signed by ca.crt can access
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ status: 'ok' }));
});
```

#### Production Standard (Correct)
> **Standard**: Connects to the SPIFFE Workload API via Unix Domain Socket, streams ephemeral X509-SVIDs, updates TLS SecureContexts dynamically in memory on rotation, enforces TLS 1.3, and validates the exact peer SPIFFE ID SAN on incoming mTLS handshakes.
```typescript
import tls from 'node:tls';
import https from 'node:https';
import { WorkloadApiClient } from '@spiffe/spiffe-sdk';

interface SpiffeContextState {
  currentContext: tls.SecureContext;
  expectedPeerSpiffeId: string;
}

export class SpiffeTlsServer {
  private secureContext!: tls.SecureContext;
  private readonly expectedPeerId = 'spiffe://example.org/ns/prod/sa/payment-worker';

  constructor(private readonly socketPath: string = process.env.SPIFFE_ENDPOINT_SOCKET || 'unix:///run/spire/sockets/agent.sock') {}

  public async initialize(): Promise<https.Server> {
    const client = new WorkloadApiClient({ socketPath: this.socketPath });
    
    // Establish streaming watcher for dynamic X509-SVID and Trust Bundle updates
    const watcher = await client.watchX509Context();
    
    watcher.on('update', (svidContext) => {
      const defaultSvid = svidContext.defaultSvid;
      const bundle = svidContext.bundle;

      // In-memory hot reload of TLS context without server restart
      this.secureContext = tls.createSecureContext({
        key: defaultSvid.privateKey,
        cert: defaultSvid.certificateChain,
        ca: bundle.certificates,
        minVersion: 'TLSv1.3'
      });
    });

    const server = https.createServer({
      SNICallback: (_servername, cb) => cb(null, this.secureContext),
      requestCert: true,
      rejectUnauthorized: true,
      checkServerIdentity: (host, cert) => {
        const sanUri = cert.subjectaltname?.split(', ').find(s => s.startsWith('URI:spiffe://'));
        if (!sanUri || sanUri.replace('URI:', '') !== this.expectedPeerId) {
          const err = new Error(`Unauthorized SPIFFE ID: ${sanUri}`);
          (err as any).code = 'ERR_TLS_UNAUTHORIZED_SPIFFE_ID';
          return err;
        }
        return undefined;
      }
    });

    return server;
  }
}
```

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: SPIFFE/SPIRE Dynamic SVID Attestation & Ephemeral mTLS Enforcement

SPIFFE/SPIRE Dynamic SVID Attestation & Ephemeral mTLS Enforcement defines an industrial-grade behavioral standard for security engineering. Mandates non-blocking runtime integration with the SPIFFE Workload API via local Unix Domain Socket (UDS) to dynamically stream short-lived X.509 SVIDs and SPIFFE trust bundles. Prohibits mounting static certificates, private keys, or long-lived credentials into workload filesystems. Enforces automated, in-memory rotation of mTLS contexts and strict SPIFFE ID SAN validation on all inter-service communications. 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: Baking Static X.509 PEM Files and Long-Lived Credentials into Container Filesystems 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 DriftBaking Static X.509 PEM Files and Long-Lived Credentials into Container FilesystemsCritical
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 and federated trust bundles dynamically from the SPIRE Agent Workload API over a local Unix Domain Socket (SPIFFE_ENDPOINT_SOCKET).

Engineers MUST ALWAYS fetch X.509 SVIDs and federated trust bundles dynamically from the SPIRE Agent Workload API over a local Unix Domain Socket (SPIFFE_ENDPOINT_SOCKET).

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 read static private keys or certificate bundles from local disk, ConfigMaps, or environment variables in microservice runtimes.

Engineers MUST NOT read static private keys or certificate bundles from local disk, ConfigMaps, or environment variables in microservice 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.
3

Services MUST subscribe to the Workload API X.509 stream and dynamically reload TLS SecureContexts in-memory prior to SVID expiration without dropping active connections.

Services MUST subscribe to the Workload API X.509 stream and dynamically reload TLS SecureContexts in-memory prior to SVID expiration without dropping active 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.
4

Code SHOULD validate peer certificates by inspecting the Subject Alternative Name (SAN) URI for valid SPIFFE IDs conforming to spiffe

Code SHOULD validate peer certificates by inspecting the Subject Alternative Name (SAN) URI for valid SPIFFE IDs conforming to spiffe://<trust-domain>/<workload-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.
5

Components NEVER accept arbitrary CA certificates or bypass trust domain checks when terminating or initiating mTLS connections.

Components NEVER accept arbitrary CA certificates or bypass trust domain checks when terminating or initiating mTLS 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.
Technical Questions & Answers

Frequently Asked Technical Questions

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

Q:Why is SPIFFE/SPIRE Dynamic SVID Attestation & Ephemeral mTLS Enforcement critical for AI coding assistants?

Mandates non-blocking runtime integration with the SPIFFE Workload API via local Unix Domain Socket (UDS) to dynamically stream short-lived X.509 SVIDs and SPIFFE trust bundles. Prohibits mounting static certificates, private keys, or long-lived credentials into workload filesystems. Enforces automated, in-memory rotation of mTLS contexts and strict SPIFFE ID SAN validation on all inter-service communications. 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 (Baking Static X.509 PEM Files and Long-Lived Credentials into Container Filesystems) 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

SPIFFE/SPIRE