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

SPIFFE/SPIRE Dynamic SVID Ephemeral Rotation and Connection Draining Invariant

Enforces zero-downtime mTLS identity rotation via SPIFFE Workload API by requiring dynamic TLS context swapping and non-destructive connection draining. Systems must hot-swap X509-SVIDs and trust bundles atomically without dropping in-flight multiplexed HTTP/2 or gRPC streams or closing active sockets. Abrupt listener recreation or synchronous socket drops during SVID updates violate zero-trust availability guarantees.

Prohibited Anti-Pattern: Hard Restart of Network Listeners or Abrupt Socket Termination on SPIFFE SVID Renewal

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: SPIFFE/SPIRE Dynamic SVID Ephemeral Rotation and Connection Draining Invariant - Enforces zero-downtime mTLS identity rotation via SPIFFE Workload API by requiring dynamic TLS context swapping and non-destructive connection draining. Systems must hot-swap X509-SVIDs and trust bundles atomically without dropping in-flight multiplexed HTTP/2 or gRPC streams or closing active sockets. Abrupt listener recreation or synchronous socket drops during SVID updates violate zero-trust availability guarantees.
globs: src/**/tls/**/*.{ts,js,go}, src/**/security/**/*.{ts,js,go}, src/**/network/**/*.{ts,js,go}, src/**/server/**/*.{ts,js,go}, src/**/spiffe/**/*.{ts,js,go}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/spiffe-spire-dynamic-svid-rotation-draining-standard"
---

# SPIFFE/SPIRE Dynamic SVID Ephemeral Rotation and Connection Draining Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Hard Restart of Network Listeners or Abrupt Socket Termination on SPIFFE SVID Renewal

## System Constraints
You are a Principal Security Architect enforcing the SPIFFE/SPIRE Dynamic SVID Ephemeral Rotation and Connection Draining Invariant. Mandate that all incoming and outgoing mTLS connections hot-swap X509-SVID certificates and trust bundles dynamically in memory without restarting listeners or dropping active sessions. Enforce HTTP/2 graceful draining via GOAWAY frames when sunsetting aged connections, ensuring in-flight RPCs are uninterrupted.

## Strict Guidelines
- Engineers MUST ALWAYS reload X509-SVIDs and federated trust bundles dynamically in memory via atomic context swaps (e.g., dynamic SNICallback or tls.createSecureContext) without restarting the underlying network listener.
- Engineers MUST NOT invoke server.close(), process restarts, or abruptly sever existing TCP/TLS sockets when a new SVID is issued by the SPIRE Workload API.
- Services MUST handle multiplexed protocols (HTTP/2, gRPC) by issuing graceful GOAWAY frames with monotonic stream IDs when retiring connections near SVID expiration, permitting in-flight transactions to conclude.
- Components NEVER execute blocking synchronous file reads or blocking cryptographic key parsing during runtime TLS handshake callbacks; pre-parsed contexts must be prepared asynchronously upon Workload API stream events.
- Code SHOULD enforce minimum overlap grace periods between SVID updates and certificate expiration to guarantee rotation completes well before validity windows lapse.

## Bad vs Good Implementations
### Dynamic TLS SecureContext Swapping vs. Listener Recreation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Recreating the server or tearing down the TLS listener on certificate rotation abruptly terminates long-lived HTTP/2 streams, causes connection refused errors during socket re-binding, and breaks ephemeral SVID zero-downtime requirements.
```typescript
import tls from 'tls';
import http2 from 'http2';

let server: http2.Http2SecureServer | null = null;

// ANTI-PATTERN: Recreating the server listener on SPIFFE SVID rotation kills active connections and drops HTTP/2 streams
export function onSvidRotated(newCert: string, newKey: string, trustBundle: string): void {
  if (server) {
    // Drops in-flight requests and abruptly closes established TCP sockets
    server.close();
  }

  server = http2.createSecureServer({
    cert: newCert,
    key: newKey,
    ca: trustBundle,
    requestCert: true,
    rejectUnauthorized: true
  });

  server.listen(8443);
}
```

#### Production Standard (Correct)
> **Standard**: Uses `tls.createSecureContext` and `SNICallback` to atomically swap TLS credentials for new connections while leaving established sockets intact. Active HTTP/2 sessions receive non-destructive `GOAWAY` frames, permitting in-flight streams to complete naturally.
```typescript
import tls from 'tls';
import http2 from 'http2';

interface SecureContextBundle {
  readonly context: tls.SecureContext;
  readonly serialNumber: string;
  readonly expiresAt: number;
}

class DynamicSpiffeTlsManager {
  private currentBundle: SecureContextBundle | null = null;
  private readonly server: http2.Http2SecureServer;

  constructor() {
    this.server = http2.createSecureServer({
      // Invariant: Dynamically resolve secure context per handshake without dropping existing sockets
      SNICallback: (_servername, cb) => {
        if (!this.currentBundle) {
          return cb(new Error('SVID not initialized from Workload API'), undefined);
        }
        cb(null, this.currentBundle.context);
      },
      requestCert: true,
      rejectUnauthorized: true
    });
  }

  // Invariant: Hot-swap secure context atomically; drain existing HTTP/2 sessions gracefully
  public updateSvid(newCert: string, newKey: string, trustBundle: string, serial: string, expiresAt: number): void {
    const newContext = tls.createSecureContext({
      cert: newCert,
      key: newKey,
      ca: trustBundle,
      minVersion: 'TLSv1.3'
    });

    // Atomic pointer update for subsequent TLS handshakes
    this.currentBundle = {
      context: newContext,
      serialNumber: serial,
      expiresAt
    };

    // Gracefully drain existing sessions without disrupting in-flight RPCs
    for (const session of this.server.sessions) {
      if (!session.destroyed && !session.closed) {
        session.goaway(http2.constants.NGHTTP2_NO_ERROR);
      }
    }
  }

  public listen(port: number): void {
    this.server.listen(port);
  }
}
```

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 Dynamic SVID Ephemeral Rotation and Connection Draining Invariant

SPIFFE/SPIRE Dynamic SVID Ephemeral Rotation and Connection Draining Invariant defines an industrial-grade behavioral standard for security engineering. Enforces zero-downtime mTLS identity rotation via SPIFFE Workload API by requiring dynamic TLS context swapping and non-destructive connection draining. Systems must hot-swap X509-SVIDs and trust bundles atomically without dropping in-flight multiplexed HTTP/2 or gRPC streams or closing active sockets. Abrupt listener recreation or synchronous socket drops during SVID updates violate zero-trust availability guarantees. 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: Hard Restart of Network Listeners or Abrupt Socket Termination on SPIFFE SVID Renewal 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 DriftHard Restart of Network Listeners or Abrupt Socket Termination on SPIFFE SVID RenewalCritical
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 reload X509-SVIDs and federated trust bundles dynamically in memory via atomic context swaps (e.g., dynamic SNICallback or tls.createSecureContext) without restarting the underlying network listener.

Engineers MUST ALWAYS reload X509-SVIDs and federated trust bundles dynamically in memory via atomic context swaps (e.g., dynamic SNICallback or tls.createSecureContext) without restarting the underlying network listener.

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 invoke server.close(), process restarts, or abruptly sever existing TCP/TLS sockets when a new SVID is issued by the SPIRE Workload API.

Engineers MUST NOT invoke server.close(), process restarts, or abruptly sever existing TCP/TLS sockets when a new SVID is issued by 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

Services MUST handle multiplexed protocols (HTTP/2, gRPC) by issuing graceful GOAWAY frames with monotonic stream IDs when retiring connections near SVID expiration, permitting in-flight transactions to conclude.

Services MUST handle multiplexed protocols (HTTP/2, gRPC) by issuing graceful GOAWAY frames with monotonic stream IDs when retiring connections near SVID expiration, permitting in-flight transactions to conclude.

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

Components NEVER execute blocking synchronous file reads or blocking cryptographic key parsing during runtime TLS handshake callbacks

Components NEVER execute blocking synchronous file reads or blocking cryptographic key parsing during runtime TLS handshake callbacks; pre-parsed contexts must be prepared asynchronously upon Workload API stream 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.
5

Code SHOULD enforce minimum overlap grace periods between SVID updates and certificate expiration to guarantee rotation completes well before validity windows lapse.

Code SHOULD enforce minimum overlap grace periods between SVID updates and certificate expiration to guarantee rotation completes well before validity windows lapse.

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 Dynamic SVID Ephemeral Rotation and Connection Draining Invariant critical for AI coding assistants?

Enforces zero-downtime mTLS identity rotation via SPIFFE Workload API by requiring dynamic TLS context swapping and non-destructive connection draining. Systems must hot-swap X509-SVIDs and trust bundles atomically without dropping in-flight multiplexed HTTP/2 or gRPC streams or closing active sockets. Abrupt listener recreation or synchronous socket drops during SVID updates violate zero-trust availability guarantees. 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 (Hard Restart of Network Listeners or Abrupt Socket Termination on SPIFFE SVID Renewal) 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