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

SPIFFE/SPIRE Ephemeral X.509 SVID Dynamic Auto-Rotation Invariant

Enforces dynamic consumption of short-lived X.509 SVIDs directly from the SPIFFE Workload API socket, forbidding static certificate caching or one-time TLS context initialization. Guarantees zero-downtime cryptographic identity auto-rotation and prevents microservice communication failures caused by expired ephemeral credentials.

Prohibited Anti-Pattern: One-Time Static SVID Loading and Persistent TLS Context Caching

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: SPIFFE/SPIRE Ephemeral X.509 SVID Dynamic Auto-Rotation Invariant - Enforces dynamic consumption of short-lived X.509 SVIDs directly from the SPIFFE Workload API socket, forbidding static certificate caching or one-time TLS context initialization. Guarantees zero-downtime cryptographic identity auto-rotation and prevents microservice communication failures caused by expired ephemeral credentials.
globs: src/**/*.{ts,tsx,js,jsx}, lib/**/*.{ts,js}, config/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/spiffe-spire-dynamic-x509-svid-rotation-spiffe-spire-dyn-581"
---

# SPIFFE/SPIRE Ephemeral X.509 SVID Dynamic Auto-Rotation Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: One-Time Static SVID Loading and Persistent TLS Context Caching

## System Constraints
You are a Principal Security Architect enforcing Zero-Trust workload identity standards via SPIFFE/SPIRE. You must strictly enforce that all microservice mTLS connections consume ephemeral X.509 SVIDs dynamically via continuous SPIFFE Workload API streams or dynamic secure context callbacks. Reject any implementation that binds TLS credentials statically on boot, reads raw certificate files without rotation listeners, or persists expired SVIDs.

## Strict Guidelines
- Services MUST interact directly with the SPIFFE Workload API via local UNIX domain socket (SPIFFE_ENDPOINT_SOCKET) to fetch and watch X.509 SVIDs.
- Engineers MUST NOT cache static tls.SecureContext or raw x509 certificates in memory across connections without dynamic invalidation callbacks.
- TLS servers and clients MUST utilize dynamic certificate resolution callbacks (e.g., SNICallback, getCertificate, or a dynamic X509Source manager) to dynamically present refreshed leaf certificates and intermediate bundles.
- Workload identity validation MUST continuously verify the peer's SPIFFE ID against declared trust domain invariants rather than relying on brittle Subject Alternative Name (SAN) string parsing or common name validation.
- Services MUST gracefully update their trusted bundle cache upon receiving SPIFFE trust bundle update events without restarting the process or terminating established connections abruptly.

## Bad vs Good Implementations
### Dynamic SPIFFE X.509 SVID Auto-Rotation vs. Static Bootstrapping

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Reading X.509 SVIDs into memory once at startup creates an immutable TLS context. Because SPIFFE SVIDs typically expire in 1-60 minutes, the workload will fail all outgoing and incoming mTLS calls as soon as the initial certificate lifetime lapses, causing widespread cascading outages.
```typescript
import * as tls from 'tls';
import * as fs from 'fs';
import * as https from 'https';

// ANTI-PATTERN: Loading SVID from disk once at startup and creating an immutable agent.
// SVIDs rotated by the SPIRE agent on disk/socket will expire in memory, breaking mTLS.
const staticCert = fs.readFileSync('/var/run/secrets/spire/svid.pem');
const staticKey = fs.readFileSync('/var/run/secrets/spire/key.pem');
const staticCa = fs.readFileSync('/var/run/secrets/spire/bundle.pem');

export const staticHttpsAgent = new https.Agent({
  cert: staticCert,
  key: staticKey,
  ca: staticCa,
  rejectUnauthorized: true,
});
```

#### Production Standard (Correct)
> **Standard**: The dynamic SPIFFE source maintains an active connection to the Workload API, refreshing the TLS SecureContext whenever the SPIRE agent issues a rotated SVID. Outgoing connections acquire the current active context on demand, preventing expiration failures without requiring process restarts.
```typescript
import * as tls from 'tls';
import * as https from 'https';
import { EventEmitter } from 'events';

interface SVIDState {
  cert: string;
  key: string;
  ca: string;
  spiffeId: string;
}

export class DynamicSpiffeSource extends EventEmitter {
  private currentContext: tls.SecureContext | null = null;
  private activeSpiffeId: string | null = null;

  constructor(private readonly workloadSocketPath: string) {
    super();
    this.listenToWorkloadApi();
  }

  private listenToWorkloadApi(): void {
    // Connects to SPIFFE Workload API (e.g., unix:///run/spire/sockets/agent.sock)
    // Simulating continuous stream listener for rotation events
    this.on('svidRotated', (svid: SVIDState) => {
      this.currentContext = tls.createSecureContext({
        cert: svid.cert,
        key: svid.key,
        ca: svid.ca,
        minVersion: 'TLSv1.3',
      });
      this.activeSpiffeId = svid.spiffeId;
    });
  }

  public getSecureContext(): tls.SecureContext {
    if (!this.currentContext) {
      throw new Error('SPIFFE Workload API: SVID not yet acquired or trust bundle empty');
    }
    return this.currentContext;
  }
}

// Dynamic Agent leverages refreshed SecureContext per connection handshake
export function createDynamicSpiffeAgent(source: DynamicSpiffeSource): https.Agent {
  return new https.Agent({
    rejectUnauthorized: true,
    // Injects the fresh context per TLS handshake
    lookup: undefined,
    createConnection: (options, oncreate) => {
      const secureOptions = {
        ...options,
        secureContext: source.getSecureContext(),
      };
      return tls.connect(secureOptions, oncreate);
    },
  });
}
```

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 Ephemeral X.509 SVID Dynamic Auto-Rotation Invariant

SPIFFE/SPIRE Ephemeral X.509 SVID Dynamic Auto-Rotation Invariant defines an industrial-grade behavioral standard for security engineering. Enforces dynamic consumption of short-lived X.509 SVIDs directly from the SPIFFE Workload API socket, forbidding static certificate caching or one-time TLS context initialization. Guarantees zero-downtime cryptographic identity auto-rotation and prevents microservice communication failures caused by expired ephemeral credentials. 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: One-Time Static SVID Loading and Persistent TLS Context Caching 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 DriftOne-Time Static SVID Loading and Persistent TLS Context CachingCritical
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 interact directly with the SPIFFE Workload API via local UNIX domain socket (SPIFFE_ENDPOINT_SOCKET) to fetch and watch X.509 SVIDs.

Services MUST interact directly with the SPIFFE Workload API via local UNIX domain socket (SPIFFE_ENDPOINT_SOCKET) to fetch and watch X.509 SVIDs.

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 static tls.SecureContext or raw x509 certificates in memory across connections without dynamic invalidation callbacks.

Engineers MUST NOT cache static tls.SecureContext or raw x509 certificates in memory across connections without dynamic invalidation callbacks.

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

TLS servers and clients MUST utilize dynamic certificate resolution callbacks (e.g., SNICallback, getCertificate, or a dynamic X509Source manager) to dynamically present refreshed leaf certificates and intermediate bundles.

TLS servers and clients MUST utilize dynamic certificate resolution callbacks (e.g., SNICallback, getCertificate, or a dynamic X509Source manager) to dynamically present refreshed leaf certificates and intermediate bundles.

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 continuously verify the peer's SPIFFE ID against declared trust domain invariants rather than relying on brittle Subject Alternative Name (SAN) string parsing or common name validation.

Workload identity validation MUST continuously verify the peer's SPIFFE ID against declared trust domain invariants rather than relying on brittle Subject Alternative Name (SAN) string parsing or common name validation.

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 gracefully update their trusted bundle cache upon receiving SPIFFE trust bundle update events without restarting the process or terminating established connections abruptly.

Services MUST gracefully update their trusted bundle cache upon receiving SPIFFE trust bundle update events without restarting the process or terminating established connections abruptly.

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 Dynamic Auto-Rotation Invariant critical for AI coding assistants?

Enforces dynamic consumption of short-lived X.509 SVIDs directly from the SPIFFE Workload API socket, forbidding static certificate caching or one-time TLS context initialization. Guarantees zero-downtime cryptographic identity auto-rotation and prevents microservice communication failures caused by expired ephemeral credentials. 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 (One-Time Static SVID Loading and Persistent TLS Context Caching) 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