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

SPIFFE/SPIRE Ephemeral X.509 SVID Zero-Trust Rotation Boundary

Enforces short-lived mTLS X.509 SVID (SPIFFE Verifiable Identity Document) rotation via the SPIFFE Workload API with sub-hour validity windows. Strictly forbids static certificate persistence, long-lived trust bundles, or indefinite TLS context caching, ensuring fail-closed mutual authentication on SVID stream exhaustion.

Prohibited Anti-Pattern: Static TLS Context Caching and Indefinite X.509 Lifetimes Bypassing SPIFFE Workload API Hot-Reloads

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: SPIFFE/SPIRE Ephemeral X.509 SVID Zero-Trust Rotation Boundary - Enforces short-lived mTLS X.509 SVID (SPIFFE Verifiable Identity Document) rotation via the SPIFFE Workload API with sub-hour validity windows. Strictly forbids static certificate persistence, long-lived trust bundles, or indefinite TLS context caching, ensuring fail-closed mutual authentication on SVID stream exhaustion.
globs: src/**/*.{ts,tsx,js}, pkg/**/*.{go}, internal/**/*.{go}, lib/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/spiffe-spire-x509-svid-rotation-guardrail-spiffe-spire-eph-793"
---

# SPIFFE/SPIRE Ephemeral X.509 SVID Zero-Trust Rotation Boundary

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Static TLS Context Caching and Indefinite X.509 Lifetimes Bypassing SPIFFE Workload API Hot-Reloads

## System Constraints
You are a Principal Security Architect enforcing zero-trust workload identities using SPIFFE/SPIRE specifications. You must reject any static disk-based certificates, permanent in-memory TLS configurations, or non-refreshing connection pools. Mandate continuous Workload API dynamic certificate streaming, strict sub-hour SVID TTLs, deterministic trust domain SAN verification, and fail-closed termination upon rotation degradation.

## Strict Guidelines
- Services MUST ALWAYS connect to the SPIFFE Workload API via a local Unix Domain Socket (UDS) to fetch X.509 SVIDs dynamically.
- Engineers MUST NOT cache TLS SecureContext instances across connection lifecycles without an active hot-reload mechanism bound to the SVID rotation watcher.
- Engineers MUST validate the peer's SPIFFE ID Subject Alternative Name (SAN) strictly against the authorized trust domain and path regex (e.g., spiffe://example.org/ns/prod/sa/*).
- Code SHOULD enforce SVID certificate TTLs <= 3600 seconds (1 hour) and schedule background rotations when 50% of the certificate validity period has elapsed.
- Services MUST fail-closed and actively terminate existing mTLS handshakes if the SPIRE Agent socket becomes unreachable and the current SVID expires.
- Components NEVER fall back to long-lived static PEM files, self-signed developmental certificates, or relaxed rejectUnauthorized: false flags.

## Bad vs Good Implementations
### SPIFFE Dynamic SVID Source vs. Stale Static Context

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Certificates are loaded once synchronously from the filesystem. As soon as the ephemeral SVID expires, the server either drops connections or accepts unvalidated identities due to rejectUnauthorized: false. It lacks hot-reloading from the SPIFFE Workload API and does not assert peer SPIFFE ID SANs.
```typescript
import * as tls from 'node:tls';
import * as fs from 'node:fs';

// ANTI-PATTERN: Static disk read at boot, indefinite in-memory caching,
// missing SPIFFE SAN validation, and dangerous fallback flags.
export function createMtlsServer() {
  const cert = fs.readFileSync('/etc/certs/workload.crt');
  const key = fs.readFileSync('/etc/certs/workload.key');
  const ca = fs.readFileSync('/etc/certs/trust-bundle.crt');

  // Statically initialized SecureContext never refreshes expired certs
  return tls.createServer({
    cert,
    key,
    ca,
    requestCert: true,
    rejectUnauthorized: false // FATAL: bypasses fail-closed invariant
  }, (socket) => {
    // Missing validation of SPIFFE ID in peer certificate SAN
    console.log('Workload connected without identity assertion');
  });
}
```

#### Production Standard (Correct)
> **Standard**: Implements an active Workload API watcher over a UNIX socket. TLS contexts are hot-swapped dynamically prior to expiry via SNICallback, enforce TLS 1.3, invalidate contexts upon stream failure (fail-closed), and strictly authenticate client SPIFFE IDs in the SAN against the authorized trust domain.
```typescript
import * as tls from 'node:tls';
import { WorkloadApiClient, X509Svid, X509Bundle } from '@spiffe/spiffe-node';

export class DynamicSpiffeServer {
  private currentContext: tls.SecureContext | null = null;
  private readonly authorizedTrustDomain = 'example.org';
  private readonly client: WorkloadApiClient;

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

  public async initialize(): Promise<tls.Server> {
    // Establish persistent streaming connection to the SPIFFE Workload API
    const watcher = await this.client.watchX509Context();

    watcher.on('change', (svidContext: { defaultSvid: X509Svid; bundles: Map<string, X509Bundle> }) => {
      const trustBundle = svidContext.bundles.get(this.authorizedTrustDomain);
      if (!trustBundle) {
        throw new Error(`Trust bundle missing for domain ${this.authorizedTrustDomain}`);
      }

      // Hot-swap secure context dynamically before SVID expiry
      this.currentContext = tls.createSecureContext({
        cert: svidContext.defaultSvid.certBuffer,
        key: svidContext.defaultSvid.keyBuffer,
        ca: trustBundle.bundleBuffer,
        minVersion: 'TLSv1.3'
      });
    });

    watcher.on('error', (err: Error) => {
      // Fail-closed: Invalidate context to prevent serving on stale credentials
      this.currentContext = null;
      throw new Error(`SPIFFE Workload API stream disrupted: ${err.message}`);
    });

    return tls.createServer({
      requestCert: true,
      rejectUnauthorized: true,
      SNICallback: (_serverName, cb) => {
        if (!this.currentContext) {
          return cb(new Error('Fail-closed: No active valid SVID context available'), null);
        }
        cb(null, this.currentContext);
      }
    }, (socket) => {
      const peerCert = (socket as tls.TLSSocket).getPeerCertificate();
      const spiffeSan = peerCert.subjectaltname?.split(', ').find(s => s.startsWith('URI:spiffe://'));
      
      if (!spiffeSan || !spiffeSan.startsWith(`URI:spiffe://${this.authorizedTrustDomain}/workload/`)) {
        socket.destroy(new Error('Unauthorized SPIFFE ID SAN: Handshake aborted'));
      }
    });
  }
}
```

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: SPIFFE/SPIRE Ephemeral X.509 SVID Zero-Trust Rotation Boundary

SPIFFE/SPIRE Ephemeral X.509 SVID Zero-Trust Rotation Boundary defines an industrial-grade behavioral standard for security engineering. Enforces short-lived mTLS X.509 SVID (SPIFFE Verifiable Identity Document) rotation via the SPIFFE Workload API with sub-hour validity windows. Strictly forbids static certificate persistence, long-lived trust bundles, or indefinite TLS context caching, ensuring fail-closed mutual authentication on SVID stream exhaustion. 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 TLS Context Caching and Indefinite X.509 Lifetimes Bypassing SPIFFE Workload API Hot-Reloads 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 TLS Context Caching and Indefinite X.509 Lifetimes Bypassing SPIFFE Workload API Hot-ReloadsCritical
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 ALWAYS connect to the SPIFFE Workload API via a local Unix Domain Socket (UDS) to fetch X.509 SVIDs dynamically.

Services MUST ALWAYS connect to the SPIFFE Workload API via a local Unix Domain Socket (UDS) to fetch X.509 SVIDs dynamically.

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 cache TLS SecureContext instances across connection lifecycles without an active hot-reload mechanism bound to the SVID rotation watcher.

Engineers MUST NOT cache TLS SecureContext instances across connection lifecycles without an active hot-reload mechanism bound to the SVID rotation watcher.

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 validate the peer's SPIFFE ID Subject Alternative Name (SAN) strictly against the authorized trust domain and path regex (e.g., spiffe

Engineers MUST validate the peer's SPIFFE ID Subject Alternative Name (SAN) strictly against the authorized trust domain and path regex (e.g., spiffe://example.org/ns/prod/sa/*).

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 SVID certificate TTLs <= 3600 seconds (1 hour) and schedule background rotations when 50% of the certificate validity period has elapsed.

Code SHOULD enforce SVID certificate TTLs <= 3600 seconds (1 hour) and schedule background rotations when 50% of the certificate validity period has elapsed.

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

Services MUST fail-closed and actively terminate existing mTLS handshakes if the SPIRE Agent socket becomes unreachable and the current SVID expires.

Services MUST fail-closed and actively terminate existing mTLS handshakes if the SPIRE Agent socket becomes unreachable and the current SVID expires.

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 long-lived static PEM files, self-signed developmental certificates, or relaxed rejectUnauthorized

Components NEVER fall back to long-lived static PEM files, self-signed developmental certificates, or relaxed rejectUnauthorized: false flags.

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 Ephemeral X.509 SVID Zero-Trust Rotation Boundary critical for AI coding assistants?

Enforces short-lived mTLS X.509 SVID (SPIFFE Verifiable Identity Document) rotation via the SPIFFE Workload API with sub-hour validity windows. Strictly forbids static certificate persistence, long-lived trust bundles, or indefinite TLS context caching, ensuring fail-closed mutual authentication on SVID stream exhaustion. 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 TLS Context Caching and Indefinite X.509 Lifetimes Bypassing SPIFFE Workload API Hot-Reloads) 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