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

SPIFFE/SPIRE Ephemeral SVID Dynamic Rotation and Overlap Handshake Guardrail

Enforces non-disruptive, atomic X.509 SVID and trust bundle rotation for ephemeral identities in distributed service meshes. Mandates overlap validation windows and thread-safe dynamic TLS context swapping to guarantee zero-downtime mTLS handshakes during aggressive sub-hour rotation cycles.

Prohibited Anti-Pattern: Static TLS Context Initialization and Destructive Listener Restarts During SVID Rotations

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: SPIFFE/SPIRE Ephemeral SVID Dynamic Rotation and Overlap Handshake Guardrail - Enforces non-disruptive, atomic X.509 SVID and trust bundle rotation for ephemeral identities in distributed service meshes. Mandates overlap validation windows and thread-safe dynamic TLS context swapping to guarantee zero-downtime mTLS handshakes during aggressive sub-hour rotation cycles.
globs: src/**/*.{ts,tsx,js,jsx}, lib/**/*.{ts,js}, services/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/spiffe-spire-svid-rotation-overlap-invariant"
---

# SPIFFE/SPIRE Ephemeral SVID Dynamic Rotation and Overlap Handshake Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Static TLS Context Initialization and Destructive Listener Restarts During SVID Rotations

## System Constraints
You are a Principal Security Architect enforcing the SPIFFE/SPIRE Ephemeral SVID Rotation Handshake Invariant. You must reject any implementation that requires restarting network listeners, mutating TLS contexts non-atomically, or failing to maintain overlapping trust bundles during X.509 SVID lifecycles. Ensure that in-flight and concurrent TLS handshakes never encounter race conditions or expired peer validations during mid-handshake rotations.

## Strict Guidelines
- Engineers MUST ALWAYS implement atomic pointer or reference swaps when updating X.509 SVIDs and SPIFFE trust bundles in memory.
- Engineers MUST NOT tear down, close, or restart TCP/mTLS listeners to apply rotated SVIDs or updated trust bundles.
- Code SHOULD utilize dynamic TLS context generation callbacks (e.g., SNICallback, getSecureContext, or GetCertificate hooks) to serve the latest valid SVID without blocking I/O.
- Services MUST validate peer certificates against both the active bundle and upcoming rotation bundle during overlap grace windows.
- Components NEVER drop in-flight TLS handshakes when a new SVID is streamed from the SPIFFE Workload API.

## Bad vs Good Implementations
### Dynamic Ephemeral SVID and Trust Bundle Rotation via Atomic SecureContext Swap

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Tearing down the TLS server listener upon receiving an SVID rotation event terminates all in-flight TCP connections and fails concurrent mTLS handshakes. It creates an availability outage every rotation interval (often every 10–30 minutes in zero-trust architectures).
```typescript
import tls from 'node:tls';

let server: tls.Server;

// ANTI-PATTERN: Restarting the server on SVID rotation causes connection drops,
// introduces race conditions during in-flight handshakes, and loses active connections.
export function setupSpiffeListener(initialCert: string, initialKey: string, initialBundle: string) {
  server = tls.createServer({
    cert: initialCert,
    key: initialKey,
    ca: [initialBundle],
    requestCert: true,
    rejectUnauthorized: true,
  });

  server.listen(8443);
}

export function onSvidRotated(newCert: string, newKey: string, newBundle: string) {
  // Flaw: Listener teardown drops concurrent requests
  server.close(() => {
    setupSpiffeListener(newCert, newKey, newBundle);
  });
}
```

#### Production Standard (Correct)
> **Standard**: Uses an atomic reference swap to update the node:tls SecureContext dynamically via SNICallback. Existing TCP connections and in-flight handshakes proceed uninterrupted with their bound context, guaranteeing zero-downtime during sub-hour SVID rotations.
```typescript
import tls from 'node:tls';
import { EventEmitter } from 'node:events';

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

export class SpiffeMtlsManager {
  private currentContext: SvidBundleState | null = null;

  constructor(private readonly workloadWatcher: EventEmitter) {
    this.workloadWatcher.on('svidRotated', (cert: string, key: string, bundles: string[], expiresAt: number) => {
      this.updateSecureContext(cert, key, bundles, expiresAt);
    });
  }

  // Atomic context swap: In-flight handshakes retain reference to their initial context
  private updateSecureContext(cert: string, key: string, bundles: string[], expiresAt: number): void {
    const secureContext = tls.createSecureContext({
      cert,
      key,
      ca: bundles,
      minVersion: 'TLSv1.3',
    });

    this.currentContext = { secureContext, expiresAt };
  }

  public createServer(handler: (socket: tls.TLSSocket) => void): tls.Server {
    if (!this.currentContext) {
      throw new Error('Cannot initialize server: SPIFFE Workload API has not yielded an SVID.');
    }

    return tls.createServer(
      {
        requestCert: true,
        rejectUnauthorized: true,
        // Dynamic context resolution per handshake prevents listener restarts
        SNICallback: (_servername, cb) => {
          if (!this.currentContext) {
            return cb(new Error('No active SPIFFE SecureContext available'), null);
          }
          return cb(null, this.currentContext.secureContext);
        },
      },
      handler
    );
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: SPIFFE/SPIRE Ephemeral SVID Dynamic Rotation and Overlap Handshake Guardrail

SPIFFE/SPIRE Ephemeral SVID Dynamic Rotation and Overlap Handshake Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces non-disruptive, atomic X.509 SVID and trust bundle rotation for ephemeral identities in distributed service meshes. Mandates overlap validation windows and thread-safe dynamic TLS context swapping to guarantee zero-downtime mTLS handshakes during aggressive sub-hour rotation cycles. 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 Initialization and Destructive Listener Restarts During SVID Rotations 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 Initialization and Destructive Listener Restarts During SVID RotationsCritical
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 implement atomic pointer or reference swaps when updating X.509 SVIDs and SPIFFE trust bundles in memory.

Engineers MUST ALWAYS implement atomic pointer or reference swaps when updating X.509 SVIDs and SPIFFE trust bundles in 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.
2

Engineers MUST NOT tear down, close, or restart TCP/mTLS listeners to apply rotated SVIDs or updated trust bundles.

Engineers MUST NOT tear down, close, or restart TCP/mTLS listeners to apply rotated SVIDs or updated trust 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.
3

Code SHOULD utilize dynamic TLS context generation callbacks (e.g., SNICallback, getSecureContext, or GetCertificate hooks) to serve the latest valid SVID without blocking I/O.

Code SHOULD utilize dynamic TLS context generation callbacks (e.g., SNICallback, getSecureContext, or GetCertificate hooks) to serve the latest valid SVID without blocking I/O.

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 validate peer certificates against both the active bundle and upcoming rotation bundle during overlap grace windows.

Services MUST validate peer certificates against both the active bundle and upcoming rotation bundle during overlap grace windows.

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 drop in-flight TLS handshakes when a new SVID is streamed from the SPIFFE Workload API.

Components NEVER drop in-flight TLS handshakes when a new SVID is streamed from the SPIFFE 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.
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 Dynamic Rotation and Overlap Handshake Guardrail critical for AI coding assistants?

Enforces non-disruptive, atomic X.509 SVID and trust bundle rotation for ephemeral identities in distributed service meshes. Mandates overlap validation windows and thread-safe dynamic TLS context swapping to guarantee zero-downtime mTLS handshakes during aggressive sub-hour rotation cycles. 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 Initialization and Destructive Listener Restarts During SVID Rotations) 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