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

SPIFFE/SPIRE Ephemeral SVID Dual-Buffer Zero-Downtime Rotation Guardrail

Enforces dual-buffer active/standby X.509 SVID rotation to eliminate transient TLS handshake failures in zero-trust mesh topologies. Guarantees atomic certificate context swapping when ephemeral SVIDs enter their rotation window (>= 50% TTL elapsed) without terminating active sockets or dropping incoming client handshakes. Mandates that cryptographic material updates never mutate existing TLS contexts in-place during in-flight handshakes.

Prohibited Anti-Pattern: Reactive Single-Buffer SVID In-Place Mutation Causing Dropped In-Flight TLS Handshakes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: SPIFFE/SPIRE Ephemeral SVID Dual-Buffer Zero-Downtime Rotation Guardrail - Enforces dual-buffer active/standby X.509 SVID rotation to eliminate transient TLS handshake failures in zero-trust mesh topologies. Guarantees atomic certificate context swapping when ephemeral SVIDs enter their rotation window (>= 50% TTL elapsed) without terminating active sockets or dropping incoming client handshakes. Mandates that cryptographic material updates never mutate existing TLS contexts in-place during in-flight handshakes.
globs: src/**/spiffe/**/*.{ts,js,go}, src/**/identity/**/*.{ts,js,go}, src/**/tls/**/*.{ts,js,go}, src/**/security/**/*.{ts,js,go}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/spiffe-spire-svid-rotation-zero-downtime"
---

# SPIFFE/SPIRE Ephemeral SVID Dual-Buffer Zero-Downtime Rotation Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Reactive Single-Buffer SVID In-Place Mutation Causing Dropped In-Flight TLS Handshakes

## System Constraints
You are a Principal Security and Mesh Architect enforcing SPIFFE/SPIRE ephemeral X.509 SVID rotation invariants. You must mandate atomic pointer swapping, dual-buffer active/standby keypair tracking, proactive refresh scheduling prior to certificate expiry, and non-blocking in-flight TLS handshake preservation.

## Strict Guidelines
- Engineers MUST ALWAYS initiate SVID refresh proactively when no more than 50% of the certificate's validity lifetime remains.
- Engineers MUST NOT restart network listeners, tear down active sockets, or block I/O event loops when receiving new X.509 SVID bundles from the SPIRE Workload API.
- Code SHOULD atomically swap pointers to pre-warmed, fully validated TLS SecureContext instances using an atomic reference or read-copy-update (RCU) semantic.
- Services MUST preserve the prior SVID buffer in standby state until existing in-flight TLS handshakes complete or reach their socket timeout.
- Components NEVER mutate TLS context configuration or cryptographic private keys in-place within shared memory.

## Bad vs Good Implementations
### Atomic Dual-Buffer SVID Dynamic Context Provider vs Disruptive In-Place Replacement

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad pattern polls reactively when the cert is already expired or near expiry, recreates the TLS listener, and drops active client connections. Any TLS handshake in-flight during listener recreation will fail with ECONNRESET or certificate validation errors.
```typescript
import tls from 'node:tls';

interface SVIDBundle {
  cert: string;
  key: string;
  expiresAt: number;
}

export class VulnerableTLSManager {
  private server: tls.Server | null = null;
  private currentSvid: SVIDBundle | null = null;

  // BAD: Reactive check on expiration and disruptive server recreation
  public async updateSvidOnExpire(fetchSvid: () => Promise<SVIDBundle>): Promise<void> {
    setInterval(async () => {
      // Flaw 1: Waiting until expiration or near-zero TTL guarantees handshake failures
      if (!this.currentSvid || Date.now() >= this.currentSvid.expiresAt) {
        this.currentSvid = await fetchSvid();
        
        // Flaw 2: Tearing down and rebuilding the server drops all active connections
        if (this.server) {
          this.server.close();
        }
        
        // Flaw 3: Mutating options in-place or bouncing the listener introduces downtime
        this.server = tls.createServer({
          cert: this.currentSvid.cert,
          key: this.currentSvid.key,
          rejectUnauthorized: true,
        });
        this.server.listen(8443);
      }
    }, 1000);
  }
}
```

#### Production Standard (Correct)
> **Standard**: This pattern achieves zero downtime by computing a proactive rotation trigger at 50% of the SVID's validity window. It uses SNICallback to dynamically fetch the pre-warmed SecureContext without mutating existing memory in-place or closing listening sockets. The prior context remains available during transition to ensure zero dropped handshakes.
```typescript
import tls from 'node:tls';

interface X509SVIDBundle {
  cert: string;
  key: string;
  issuedAt: number;
  expiresAt: number;
  bundle: string;
}

interface SVIDContextBuffer {
  readonly secureContext: tls.SecureContext;
  readonly expiresAt: number;
  readonly issuedAt: number;
}

export class ZeroDowntimeSVIDManager {
  private activeBuffer: SVIDContextBuffer | null = null;
  private standbyBuffer: SVIDContextBuffer | null = null;

  public createSecureContext(bundle: X509SVIDBundle): tls.SecureContext {
    return tls.createSecureContext({
      cert: bundle.cert,
      key: bundle.key,
      ca: bundle.bundle,
      minVersion: 'TLSv1.3',
    });
  }

  // GOOD: Proactive rotation at 50% TTL with atomic buffer swap
  public rotateSVID(newBundle: X509SVIDBundle): void {
    const newContext = this.createSecureContext(newBundle);
    const newBuffer: SVIDContextBuffer = {
      secureContext: newContext,
      issuedAt: newBundle.issuedAt,
      expiresAt: newBundle.expiresAt,
    };

    // Retain previous active buffer as standby to let in-flight handshakes settle
    this.standbyBuffer = this.activeBuffer;
    // Atomic pointer update ensures no lock contention or mutation race conditions
    this.activeBuffer = newBuffer;
  }

  public isRotationDue(now: number = Date.now()): boolean {
    if (!this.activeBuffer) return true;
    const totalLifetime = this.activeBuffer.expiresAt - this.activeBuffer.issuedAt;
    const rotationThreshold = this.activeBuffer.issuedAt + totalLifetime * 0.5;
    return now >= rotationThreshold;
  }

  public attachToTLSServer(serverOptions: tls.TlsOptions): tls.TlsOptions {
    return {
      ...serverOptions,
      // Dynamic SNI/context callback resolves atomic reference without server restart
      SNICallback: (_servername: string, cb: (err: Error | null, ctx?: tls.SecureContext) => void) => {
        if (!this.activeBuffer) {
          return cb(new Error('No valid SPIFFE SVID secure context available'));
        }
        cb(null, this.activeBuffer.secureContext);
      },
    };
  }
}
```

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 SVID Dual-Buffer Zero-Downtime Rotation Guardrail

SPIFFE/SPIRE Ephemeral SVID Dual-Buffer Zero-Downtime Rotation Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces dual-buffer active/standby X.509 SVID rotation to eliminate transient TLS handshake failures in zero-trust mesh topologies. Guarantees atomic certificate context swapping when ephemeral SVIDs enter their rotation window (>= 50% TTL elapsed) without terminating active sockets or dropping incoming client handshakes. Mandates that cryptographic material updates never mutate existing TLS contexts in-place during in-flight handshakes. 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: Reactive Single-Buffer SVID In-Place Mutation Causing Dropped In-Flight TLS Handshakes 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 DriftReactive Single-Buffer SVID In-Place Mutation Causing Dropped In-Flight TLS HandshakesCritical
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 initiate SVID refresh proactively when no more than 50% of the certificate's validity lifetime remains.

Engineers MUST ALWAYS initiate SVID refresh proactively when no more than 50% of the certificate's validity lifetime remains.

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 restart network listeners, tear down active sockets, or block I/O event loops when receiving new X.509 SVID bundles from the SPIRE Workload API.

Engineers MUST NOT restart network listeners, tear down active sockets, or block I/O event loops when receiving new X.509 SVID bundles from the SPIRE Workload API.

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

Code SHOULD atomically swap pointers to pre-warmed, fully validated TLS SecureContext instances using an atomic reference or read-copy-update (RCU) semantic.

Code SHOULD atomically swap pointers to pre-warmed, fully validated TLS SecureContext instances using an atomic reference or read-copy-update (RCU) semantic.

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

Services MUST preserve the prior SVID buffer in standby state until existing in-flight TLS handshakes complete or reach their socket timeout.

Services MUST preserve the prior SVID buffer in standby state until existing in-flight TLS handshakes complete or reach their socket timeout.

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 mutate TLS context configuration or cryptographic private keys in-place within shared memory.

Components NEVER mutate TLS context configuration or cryptographic private keys in-place within shared memory.

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 SVID Dual-Buffer Zero-Downtime Rotation Guardrail critical for AI coding assistants?

Enforces dual-buffer active/standby X.509 SVID rotation to eliminate transient TLS handshake failures in zero-trust mesh topologies. Guarantees atomic certificate context swapping when ephemeral SVIDs enter their rotation window (>= 50% TTL elapsed) without terminating active sockets or dropping incoming client handshakes. Mandates that cryptographic material updates never mutate existing TLS contexts in-place during in-flight handshakes. 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 (Reactive Single-Buffer SVID In-Place Mutation Causing Dropped In-Flight TLS Handshakes) 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