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

SPIFFE/SPIRE In-Memory X.509-SVID Non-Disruptive Rotation Guardrail

Enforces non-disruptive, zero-trust mTLS credential rotation driven directly by the SPIFFE Workload API over UNIX Domain Sockets. Prohibits process restarts, socket re-binding, and disk-bound certificate reads, requiring atomic in-memory TLS context swaps to eliminate race conditions and dropped active connections during aggressive ephemeral SVID rotations.

Prohibited Anti-Pattern: Static Disk-Based Certificate Bootstrapping and Process Recycling on SVID Expiration

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: SPIFFE/SPIRE In-Memory X.509-SVID Non-Disruptive Rotation Guardrail - Enforces non-disruptive, zero-trust mTLS credential rotation driven directly by the SPIFFE Workload API over UNIX Domain Sockets. Prohibits process restarts, socket re-binding, and disk-bound certificate reads, requiring atomic in-memory TLS context swaps to eliminate race conditions and dropped active connections during aggressive ephemeral SVID rotations.
globs: src/**/*.{ts,js}, lib/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/spiffe-spire-workload-attestation-lifecycle"
---

# SPIFFE/SPIRE In-Memory X.509-SVID Non-Disruptive Rotation Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Static Disk-Based Certificate Bootstrapping and Process Recycling on SVID Expiration

## System Constraints
You are a Principal Engineer enforcing the SPIFFE/SPIRE Ephemeral Workload Attestation Lifecycle Invariant. Ephemeral X.509-SVIDs expire rapidly and must be rotated atomically in memory without interrupting active sockets, relying on disk mounts, or tearing down TLS listeners.

## Strict Guidelines
- Engineers MUST ALWAYS consume X509-SVIDs and federated trust bundles by streaming updates over the SPIFFE Workload API UNIX Domain Socket (spiffeWorkloadSocket).
- Engineers MUST NOT write ephemeral SVIDs or keys to temporary filesystems, shared storage, or environment variables.
- Services MUST swap TLS credentials atomically in memory (e.g., using server.setSecureContext() in Node.js or dynamic GetCertificate callbacks) upon receiving SVID renewal events.
- Code SHOULD maintain active TCP sessions without dropping connections or triggering process recycling during SVID rotation cycles.
- Services MUST continuously validate peer SPIFFE IDs against a strict authorization policy matrix during the TLS handshake, rejecting unauthorized trust domains before application-level payload decoding.
- Components NEVER fall back to insecure TLS configurations, disable peer certificate verification, or terminate listener sockets if the SPIRE Agent socket becomes temporarily unavailable.

## Bad vs Good Implementations
### SPIRE Workload API Dynamic In-Memory Context Hot-Swapping vs. Disruptive Process Teardown

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Reading SVIDs from disk creates security vulnerabilities (ephemeral private keys stored in storage) and forcing process exits or socket closures during rapid SVID rotations terminates in-flight client connections, breaking zero-downtime microservice invariants.
```typescript
import tls from 'node:tls';
import fs from 'node:fs';

// Anti-pattern: Loading short-lived SVIDs from disk and killing the process to rotate
const options: tls.TlsOptions = {
  key: fs.readFileSync('/tmp/spiffe/svid.key'),
  cert: fs.readFileSync('/tmp/spiffe/svid.crt'),
  ca: [fs.readFileSync('/tmp/spiffe/bundle.crt')],
  requestCert: true,
  rejectUnauthorized: true,
};

const server = tls.createServer(options, (socket) => {
  socket.write('secure payload');
});

// Flaw: SVID expires, process restarts to pick up newly mounted disk certs,
// dropping all inflight microservice connections
fs.watch('/tmp/spiffe/svid.crt', () => {
  console.warn('SVID updated on disk, restarting process to reload...');
  server.close(() => process.exit(0));
});

server.listen(8443);
```

#### Production Standard (Correct)
> **Standard**: Consumes SVID updates in-memory directly from the SPIRE agent, validates peer SPIFFE IDs via SAN checks on the TLS handshake, and atomically replaces the TLS context using server.setSecureContext() without terminating active sockets or writing private keys to disk.
```typescript
import tls from 'node:tls';
import { EventEmitter } from 'node:events';

interface X509SvidUpdate {
  svidCertChain: string;
  privateKey: string;
  bundle: string;
  spiffeId: string;
}

// Workload API watcher emitting in-memory rotations via UDS stream
class SpireWorkloadWatcher extends EventEmitter {
  public start(): void {
    // Connects to SPIFFE_ENDPOINT_SOCKET over UDS
  }
}

const watcher = new SpireWorkloadWatcher();
const initialContext = tls.createSecureContext({
  // Seeded securely during attestation initialization
});

const server = tls.createServer({
  secureContext: initialContext,
  requestCert: true,
  rejectUnauthorized: true,
  checkServerIdentity: (host, cert) => {
    const peerSpiffeId = cert.subjectaltname?.match(/URI:(spiffe:\/\/[^,\s]+)/)?.[1];
    const allowedDomain = 'spiffe://prod.internal/ns/workloads/sa/payments-worker';
    if (!peerSpiffeId || peerSpiffeId !== allowedDomain) {
      const err = new Error(`SPIFFE ID mismatch: unauthorized client identity ${peerSpiffeId}`);
      Object.assign(err, { code: 'ERR_TLS_CERT_ALTNAME_INVALID' });
      return err;
    }
    return undefined;
  },
});

// Atomic in-memory context swap on SPIRE SVID update
watcher.on('svid_updated', (update: X509SvidUpdate) => {
  try {
    const newContext = tls.createSecureContext({
      key: update.privateKey,
      cert: update.svidCertChain,
      ca: [update.bundle],
    });
    // Zero-downtime hot swap: active sockets continue uninterrupted,
    // subsequent handshakes use updated credentials
    server.setSecureContext(newContext);
  } catch (err) {
    console.error('Failed to atomically hot-swap SVID context:', err);
  }
});

server.listen(8443);
```

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 In-Memory X.509-SVID Non-Disruptive Rotation Guardrail

SPIFFE/SPIRE In-Memory X.509-SVID Non-Disruptive Rotation Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces non-disruptive, zero-trust mTLS credential rotation driven directly by the SPIFFE Workload API over UNIX Domain Sockets. Prohibits process restarts, socket re-binding, and disk-bound certificate reads, requiring atomic in-memory TLS context swaps to eliminate race conditions and dropped active connections during aggressive ephemeral SVID rotations. 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 Disk-Based Certificate Bootstrapping and Process Recycling on SVID Expiration 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 Disk-Based Certificate Bootstrapping and Process Recycling on SVID ExpirationCritical
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 consume X509-SVIDs and federated trust bundles by streaming updates over the SPIFFE Workload API UNIX Domain Socket (spiffeWorkloadSocket).

Engineers MUST ALWAYS consume X509-SVIDs and federated trust bundles by streaming updates over the SPIFFE Workload API UNIX Domain Socket (spiffeWorkloadSocket).

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 write ephemeral SVIDs or keys to temporary filesystems, shared storage, or environment variables.

Engineers MUST NOT write ephemeral SVIDs or keys to temporary filesystems, shared storage, or environment variables.

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 swap TLS credentials atomically in memory (e.g., using server.setSecureContext() in Node.js or dynamic GetCertificate callbacks) upon receiving SVID renewal events.

Services MUST swap TLS credentials atomically in memory (e.g., using server.setSecureContext() in Node.js or dynamic GetCertificate callbacks) upon receiving SVID renewal events.

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 maintain active TCP sessions without dropping connections or triggering process recycling during SVID rotation cycles.

Code SHOULD maintain active TCP sessions without dropping connections or triggering process recycling during SVID rotation cycles.

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 continuously validate peer SPIFFE IDs against a strict authorization policy matrix during the TLS handshake, rejecting unauthorized trust domains before application-level payload decoding.

Services MUST continuously validate peer SPIFFE IDs against a strict authorization policy matrix during the TLS handshake, rejecting unauthorized trust domains before application-level payload decoding.

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 insecure TLS configurations, disable peer certificate verification, or terminate listener sockets if the SPIRE Agent socket becomes temporarily unavailable.

Components NEVER fall back to insecure TLS configurations, disable peer certificate verification, or terminate listener sockets if the SPIRE Agent socket becomes temporarily unavailable.

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 In-Memory X.509-SVID Non-Disruptive Rotation Guardrail critical for AI coding assistants?

Enforces non-disruptive, zero-trust mTLS credential rotation driven directly by the SPIFFE Workload API over UNIX Domain Sockets. Prohibits process restarts, socket re-binding, and disk-bound certificate reads, requiring atomic in-memory TLS context swaps to eliminate race conditions and dropped active connections during aggressive ephemeral SVID rotations. 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 Disk-Based Certificate Bootstrapping and Process Recycling on SVID Expiration) 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