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

Automated Sub-Hour SPIFFE/SPIRE X.509 SVID Dynamic Workload Identity Rotation

Workloads across heterogeneous cloud meshes must eliminate all static long-lived credentials by continuously leasing short-lived X.509 SVIDs from the SPIFFE Workload API over a secure UNIX domain socket. Applications and mTLS transport layers must implement in-memory dynamic keypair hot-reloading via persistent streaming watchers, strictly binding maximum SVID lifetime to under 60 minutes. Storing SVID private keys on persistent non-volatile disks, bypassing the SPIFFE Workload API, or caching TLS contexts without automated rotation violates zero-trust isolation invariants.

Prohibited Anti-Pattern: Static Cloud Credentials and Unwatched, Stale X.509 Certificate Loading

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Automated Sub-Hour SPIFFE/SPIRE X.509 SVID Dynamic Workload Identity Rotation - Workloads across heterogeneous cloud meshes must eliminate all static long-lived credentials by continuously leasing short-lived X.509 SVIDs from the SPIFFE Workload API over a secure UNIX domain socket. Applications and mTLS transport layers must implement in-memory dynamic keypair hot-reloading via persistent streaming watchers, strictly binding maximum SVID lifetime to under 60 minutes. Storing SVID private keys on persistent non-volatile disks, bypassing the SPIFFE Workload API, or caching TLS contexts without automated rotation violates zero-trust isolation invariants.
globs: **/security/**, **/transport/**, **/mesh/**, **/tls/**, **/*spiffe*, **/*mtls*, **/*client*.ts, **/*server*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/spiffe-spire-x509-svid-automated-rotation-invariant"
---

# Automated Sub-Hour SPIFFE/SPIRE X.509 SVID Dynamic Workload Identity Rotation

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Static Cloud Credentials and Unwatched, Stale X.509 Certificate Loading

## System Constraints
You are a Principal Security Architect enforcing SPIFFE/SPIRE Cryptographic Workload Identity Rotation invariants. Mandate dynamic X.509 SVID streaming over the Workload API UNIX domain socket, zero disk-bound private keys, sub-hour rotation cycles, and zero-downtime in-memory TLS context reloading.

## Strict Guidelines
- Services MUST connect exclusively to the SPIFFE Workload API via local UNIX domain socket (SPIFFE_ENDPOINT_SOCKET) to acquire cryptographic workload identity.
- Engineers MUST NEVER persist SVID X.509 leaf certificates, private keys, or intermediate bundles to non-volatile disk storage.
- Transport layers MUST watch the SPIFFE Workload API stream continuously and hot-swap TLS Context certificates and trust bundles in-memory before expiration without terminating active socket connections.
- Workload identity validation MUST verify the peer's SPIFFE ID string format ('spiffe://<trust-domain>/<workload-path>') using explicit pattern matching or SANURI validators, not conventional Common Name (CN) matching.
- Maximum SVID TTL MUST be configured for sub-hour lifetimes (default <= 60 minutes) to eliminate reliance on Certificate Revocation Lists (CRLs) or OCSP stapling.
- Components NEVER fall back to static API keys, cloud provider static IAM secrets, or long-lived Kubernetes Service Account tokens when the SPIFFE Workload API is unreachable; fail closed immediately.

## Bad vs Good Implementations
### Node.js / TypeScript mTLS Dynamic SVID Rotation vs Static Disk Certificate Loading

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Loads static certificates synchronously from disk with no rotation capability. When the certificate expires, the service fails or requires a restart. It exposes the private key to persistent filesystem storage and lacks SAN-based SPIFFE ID verification.
```typescript
import tls from 'node:tls';
import fs from 'node:fs';

// ANTI-PATTERN: Static certificate loading from persistent disk
// Creates vulnerability to stale credentials, disk exfiltration, and requires process restarts for renewal
export class LegacySecureTransport {
  private tlsContext: tls.SecureContext;

  constructor() {
    this.tlsContext = tls.createSecureContext({
      key: fs.readFileSync('/etc/certs/service-account.key'),
      cert: fs.readFileSync('/etc/certs/service-account.crt'),
      ca: fs.readFileSync('/etc/certs/ca.crt'),
      minVersion: 'TLSv1.3'
    });
  }

  public createServer() {
    return tls.createServer({ secureContext: this.tlsContext }, (socket) => {
      // No dynamic identity verification or SPIFFE ID SAN validation
      console.log('Client connected:', socket.remoteAddress);
    });
  }
}
```

#### Production Standard (Correct)
> **Standard**: Connects directly to the SPIFFE Workload API via a local UNIX socket. Certificates and private keys reside exclusively in memory, actively rotated using a streaming listener. Incoming connections check the peer's SPIFFE ID SAN format and SNI dynamically provisions the freshest SecureContext.
```typescript
import tls from 'node:tls';
import { WorkloadApiClient, X509SVID } from '@spiffe/spiffe-sdk'; // Hypothetical standard SPIFFE Workload API client

// PRODUCTION INVARIANT: Ephemeral, streaming in-memory SVID rotation via UNIX Domain Socket
export class SpiffeSecureTransport {
  private secureContext: tls.SecureContext | null = null;
  private readonly expectedPeerDomain = 'spiffe://internal.infra.mesh/workload/';
  private client: WorkloadApiClient;

  constructor(socketPath: string = process.env.SPIFFE_ENDPOINT_SOCKET || 'unix:///run/spire/sockets/agent.sock') {
    this.client = new WorkloadApiClient({ address: socketPath });
  }

  public async initialize(): Promise<void> {
    // Stream updates continuously: Sub-hour automated rotation
    const watcher = await this.client.watchX509Context();

    watcher.on('update', (context: { svid: X509SVID; trustBundles: Map<string, string> }) => {
      const spiffeId = context.svid.id;
      const rawKey = context.svid.privateKey;
      const certChain = context.svid.certificateChain;
      const bundle = context.trustBundles.get('internal.infra.mesh');

      if (!bundle) {
        throw new Error(`Trust bundle missing for mesh domain`);
      }

      // In-memory atomic swap of TLS context without restarting server
      this.secureContext = tls.createSecureContext({
        key: rawKey,
        cert: certChain,
        ca: bundle,
        minVersion: 'TLSv1.3'
      });
    });

    watcher.on('error', (err: Error) => {
      // Fail closed immediately; do not fallback to static secrets
      console.error('Fatal SPIFFE Workload API stream error', err);
      process.exit(1);
    });
  }

  public createServer() {
    return tls.createServer({
      SNICallback: (_serverName, cb) => {
        if (!this.secureContext) {
          return cb(new Error('SVID not initialized or unready'), null);
        }
        cb(null, this.secureContext);
      },
      requestCert: true,
      rejectUnauthorized: true,
      checkServerIdentity: (_host, cert) => {
        const sanUris = (cert.subjectaltname || '').split(',').map((s) => s.trim());
        const hasValidSpiffeId = sanUris.some((uri) => uri.startsWith(`URI:${this.expectedPeerDomain}`));
        if (!hasValidSpiffeId) {
          return new Error(`Unauthorized peer SPIFFE ID: ${cert.subjectaltname}`);
        }
        return undefined;
      }
    });
  }
}
```

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: Automated Sub-Hour SPIFFE/SPIRE X.509 SVID Dynamic Workload Identity Rotation

Automated Sub-Hour SPIFFE/SPIRE X.509 SVID Dynamic Workload Identity Rotation defines an industrial-grade behavioral standard for security engineering. Workloads across heterogeneous cloud meshes must eliminate all static long-lived credentials by continuously leasing short-lived X.509 SVIDs from the SPIFFE Workload API over a secure UNIX domain socket. Applications and mTLS transport layers must implement in-memory dynamic keypair hot-reloading via persistent streaming watchers, strictly binding maximum SVID lifetime to under 60 minutes. Storing SVID private keys on persistent non-volatile disks, bypassing the SPIFFE Workload API, or caching TLS contexts without automated rotation violates zero-trust isolation invariants. 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: Static Cloud Credentials and Unwatched, Stale X.509 Certificate Loading 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 DriftStatic Cloud Credentials and Unwatched, Stale X.509 Certificate LoadingCritical
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 connect exclusively to the SPIFFE Workload API via local UNIX domain socket (SPIFFE_ENDPOINT_SOCKET) to acquire cryptographic workload identity.

Services MUST connect exclusively to the SPIFFE Workload API via local UNIX domain socket (SPIFFE_ENDPOINT_SOCKET) to acquire cryptographic workload identity.

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 NEVER persist SVID X.509 leaf certificates, private keys, or intermediate bundles to non-volatile disk storage.

Engineers MUST NEVER persist SVID X.509 leaf certificates, private keys, or intermediate bundles to non-volatile disk storage.

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

Transport layers MUST watch the SPIFFE Workload API stream continuously and hot-swap TLS Context certificates and trust bundles in-memory before expiration without terminating active socket connections.

Transport layers MUST watch the SPIFFE Workload API stream continuously and hot-swap TLS Context certificates and trust bundles in-memory before expiration without terminating active socket 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

Workload identity validation MUST verify the peer's SPIFFE ID string format ('spiffe

Workload identity validation MUST verify the peer's SPIFFE ID string format ('spiffe://<trust-domain>/<workload-path>') using explicit pattern matching or SANURI validators, not conventional Common Name (CN) 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.
5

Maximum SVID TTL MUST be configured for sub-hour lifetimes (default <= 60 minutes) to eliminate reliance on Certificate Revocation Lists (CRLs) or OCSP stapling.

Maximum SVID TTL MUST be configured for sub-hour lifetimes (default <= 60 minutes) to eliminate reliance on Certificate Revocation Lists (CRLs) or OCSP stapling.

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

Components NEVER fall back to static API keys, cloud provider static IAM secrets, or long-lived Kubernetes Service Account tokens when the SPIFFE Workload API is unreachable

Components NEVER fall back to static API keys, cloud provider static IAM secrets, or long-lived Kubernetes Service Account tokens when the SPIFFE Workload API is unreachable; fail closed immediately.

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 Automated Sub-Hour SPIFFE/SPIRE X.509 SVID Dynamic Workload Identity Rotation critical for AI coding assistants?

Workloads across heterogeneous cloud meshes must eliminate all static long-lived credentials by continuously leasing short-lived X.509 SVIDs from the SPIFFE Workload API over a secure UNIX domain socket. Applications and mTLS transport layers must implement in-memory dynamic keypair hot-reloading via persistent streaming watchers, strictly binding maximum SVID lifetime to under 60 minutes. Storing SVID private keys on persistent non-volatile disks, bypassing the SPIFFE Workload API, or caching TLS contexts without automated rotation violates zero-trust isolation invariants. 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 (Static Cloud Credentials and Unwatched, Stale X.509 Certificate Loading) 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

Automated