This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: caep-sse-subsecond-revocation-pipeline

Continuous Access Evaluation Protocol (CAEP) & OpenID SSE Sub-Second Revocation Standard

Enforces cryptographic ingestion, validation, and sub-second distributed propagation of OpenID Shared Signals and Events (SSE) and Continuous Access Evaluation Protocol (CAEP) Security Event Tokens (SET). Decoupled microservices must intercept requests against an L1/L2 revocation tier indexed by subject (sub), session (sid), and token (jti) to invalidate compromised sessions immediately without awaiting JWT expiration.

Prohibited Anti-Pattern: Blind Stateless JWT Acceptance and Unchecked Trust Window Post-Identity Compromise

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Continuous Access Evaluation Protocol (CAEP) & OpenID SSE Sub-Second Revocation Standard - Enforces cryptographic ingestion, validation, and sub-second distributed propagation of OpenID Shared Signals and Events (SSE) and Continuous Access Evaluation Protocol (CAEP) Security Event Tokens (SET). Decoupled microservices must intercept requests against an L1/L2 revocation tier indexed by subject (sub), session (sid), and token (jti) to invalidate compromised sessions immediately without awaiting JWT expiration.
globs: src/auth/**/*.{ts,tsx}, src/middleware/**/*.{ts,tsx}, src/security/**/*.{ts,tsx}, src/events/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/caep-sse-subsecond-revocation-pipeline"
---

# Continuous Access Evaluation Protocol (CAEP) & OpenID SSE Sub-Second Revocation Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Blind Stateless JWT Acceptance and Unchecked Trust Window Post-Identity Compromise

## System Constraints
You are a Principal Security Architect enforcing RFC 8417 (Security Event Token) and the OpenID Continuous Access Evaluation Profile (CAEP). You must prevent services from relying solely on standard JWT expiration (`exp`). You must mandate that all microservices ingest SSE/CAEP events, verify cryptographic SET provenance, broadcast invalidations across a tiered distributed caching layer (L1 memory + L2 distributed KV), and evaluate revocation status in sub-millisecond request intercepts with fail-closed security policies.

## Strict Guidelines
- Engineers MUST ALWAYS cryptographically verify incoming CAEP Security Event Tokens (SETs) against the Identity Provider's published JWKS, validating `iss`, `aud`, and `events` claims before processing.
- Engineers MUST NOT rely solely on stateless JWT `exp` claims for authorization decisions in zero-trust boundaries; token checks MUST query an ultra-low-latency revocation index.
- Services MUST implement a dual-tier cache strategy (L1 in-process LRU cache synchronized via Redis Pub/Sub, backed by L2 Redis Cluster) to evaluate token revocation in < 1ms.
- Engineers MUST index revocations by `sub` (subject), `sid` (session ID), and `jti` (JWT ID) to handle fine-grained (single device/session) and coarse-grained (full account lockout) invalidations.
- Revocation entries MUST set a Time-To-Live (TTL) equivalent to the maximum remaining validity window of active access tokens (`token.exp - current_timestamp`), preventing unbounded memory growth.
- Services MUST operate in a fail-closed posture: if the distributed revocation lookup times out or fails during high-assurance actions, the request MUST be rejected with HTTP 401/403.

## Bad vs Good Implementations
### Naive JWT Verification vs. Resilient CAEP/SSE Revocation Engine

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: This naive implementation relies completely on stateless JWT claims and cryptographic verification of the public key. If the Identity Provider fires a CAEP 'session-revoked' or 'credential-change' event, this service remains vulnerable to replay attacks and stolen bearer tokens until the token naturally expires.
```typescript
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';

interface AuthenticatedUser {
  sub: string;
  sid: string;
  role: string;
}

// ANTI-PATTERN: Verifies standard claims but ignores IdP session state or CAEP signals.
// Compromised sessions or revoked devices remain fully authorized until token TTL expires.
export function authenticateRequest(req: Request, res: Response, next: NextFunction): void {
  const authHeader = req.headers.authorization;
  if (!authHeader?.startsWith('Bearer ')) {
    res.status(401).json({ error: 'Missing token' });
    return;
  }

  const token = authHeader.substring(7);
  try {
    const payload = jwt.verify(token, process.env.IDP_PUBLIC_KEY!, {
      algorithms: ['RS256'],
    }) as AuthenticatedUser;

    (req as any).user = payload;
    next();
  } catch (err) {
    res.status(401).json({ error: 'Invalid or expired token' });
  }
}
```

#### Production Standard (Correct)
> **Standard**: The production implementation introduces a dual-layer L1/L2 revocation pipeline that evaluates incoming requests against revoked `sub`, `sid`, and `jti` identifiers within sub-millisecond bounds. It uses a fail-closed execution model: if the distributed revocation registry is unreachable, it denies access instead of blindly relying on stale JWT validity.
```typescript
import { Request, Response, NextFunction } from 'express';
import jwt, { JwtPayload } from 'jsonwebtoken';
import Redis from 'ioredis';
import { LRUCache } from 'lru-cache';

interface CustomJwtPayload extends JwtPayload {
  sub: string;
  sid: string;
  jti: string;
}

export class CaepRevocationEngine {
  private l1Cache: LRUCache<string, boolean>;
  private l2Redis: Redis;

  constructor(redisClient: Redis) {
    this.l2Redis = redisClient;
    this.l1Cache = new LRUCache<string, boolean>({
      max: 50_000,
      ttl: 60 * 1000, // 60s micro-cache; invalidated via Pub/Sub
    });
  }

  public async isRevoked(sub: string, sid?: string, jti?: string): Promise<boolean> {
    const keysToCheck = [`revoked:sub:${sub}`];
    if (sid) keysToCheck.push(`revoked:sid:${sid}`);
    if (jti) keysToCheck.push(`revoked:jti:${jti}`);

    // 1. Fast L1 In-Memory Check
    for (const key of keysToCheck) {
      if (this.l1Cache.get(key) === true) {
        return true;
      }
    }

    // 2. L2 Distributed Cluster Check with strict timeout (Fail-Closed)
    try {
      const results = await Promise.race([
        this.l2Redis.mget(...keysToCheck),
        new Promise<null>((_, reject) => setTimeout(() => reject(new Error('Redis timeout')), 25)),
      ]);

      if (results && results.some((val) => val !== null)) {
        for (const key of keysToCheck) {
          this.l1Cache.set(key, true);
        }
        return true;
      }
      return false;
    } catch (error) {
      // Fail-closed policy for zero-trust resilience
      throw new Error('RevocationEngineUnavailable');
    }
  }
}

export function createZeroTrustAuthMiddleware(engine: CaepRevocationEngine, publicKey: string) {
  return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    const authHeader = req.headers.authorization;
    if (!authHeader?.startsWith('Bearer ')) {
      res.status(401).json({ error: 'Missing or malformed Authorization header' });
      return;
    }

    const token = authHeader.substring(7);
    try {
      const payload = jwt.verify(token, publicKey, { algorithms: ['RS256'] }) as CustomJwtPayload;

      const revoked = await engine.isRevoked(payload.sub, payload.sid, payload.jti);
      if (revoked) {
        res.status(401).json({ error: 'Session revoked via continuous access evaluation' });
        return;
      }

      (req as any).user = payload;
      next();
    } catch (err: any) {
      if (err.message === 'RevocationEngineUnavailable') {
        res.status(503).json({ error: 'Service Unavailable: Identity verification timeout' });
        return;
      }
      res.status(401).json({ error: 'Invalid authentication context' });
    }
  };
}
```

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: Continuous Access Evaluation Protocol (CAEP) & OpenID SSE Sub-Second Revocation Standard

Continuous Access Evaluation Protocol (CAEP) & OpenID SSE Sub-Second Revocation Standard defines an industrial-grade behavioral standard for security engineering. Enforces cryptographic ingestion, validation, and sub-second distributed propagation of OpenID Shared Signals and Events (SSE) and Continuous Access Evaluation Protocol (CAEP) Security Event Tokens (SET). Decoupled microservices must intercept requests against an L1/L2 revocation tier indexed by subject (sub), session (sid), and token (jti) to invalidate compromised sessions immediately without awaiting JWT expiration. 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: Blind Stateless JWT Acceptance and Unchecked Trust Window Post-Identity Compromise 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 DriftBlind Stateless JWT Acceptance and Unchecked Trust Window Post-Identity CompromiseCritical
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 cryptographically verify incoming CAEP Security Event Tokens (SETs) against the Identity Provider's published JWKS, validating `iss`, `aud`, and `events` claims before processing.

Engineers MUST ALWAYS cryptographically verify incoming CAEP Security Event Tokens (SETs) against the Identity Provider's published JWKS, validating `iss`, `aud`, and `events` claims before processing.

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 rely solely on stateless JWT `exp` claims for authorization decisions in zero-trust boundaries

Engineers MUST NOT rely solely on stateless JWT `exp` claims for authorization decisions in zero-trust boundaries; token checks MUST query an ultra-low-latency revocation index.

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 implement a dual-tier cache strategy (L1 in-process LRU cache synchronized via Redis Pub/Sub, backed by L2 Redis Cluster) to evaluate token revocation in < 1ms.

Services MUST implement a dual-tier cache strategy (L1 in-process LRU cache synchronized via Redis Pub/Sub, backed by L2 Redis Cluster) to evaluate token revocation in < 1ms.

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

Engineers MUST index revocations by `sub` (subject), `sid` (session ID), and `jti` (JWT ID) to handle fine-grained (single device/session) and coarse-grained (full account lockout) invalidations.

Engineers MUST index revocations by `sub` (subject), `sid` (session ID), and `jti` (JWT ID) to handle fine-grained (single device/session) and coarse-grained (full account lockout) invalidations.

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

Revocation entries MUST set a Time-To-Live (TTL) equivalent to the maximum remaining validity window of active access tokens (`token.exp - current_timestamp`), preventing unbounded memory growth.

Revocation entries MUST set a Time-To-Live (TTL) equivalent to the maximum remaining validity window of active access tokens (`token.exp - current_timestamp`), preventing unbounded memory growth.

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

Services MUST operate in a fail-closed posture

Services MUST operate in a fail-closed posture: if the distributed revocation lookup times out or fails during high-assurance actions, the request MUST be rejected with HTTP 401/403.

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 Continuous Access Evaluation Protocol (CAEP) & OpenID SSE Sub-Second Revocation Standard critical for AI coding assistants?

Enforces cryptographic ingestion, validation, and sub-second distributed propagation of OpenID Shared Signals and Events (SSE) and Continuous Access Evaluation Protocol (CAEP) Security Event Tokens (SET). Decoupled microservices must intercept requests against an L1/L2 revocation tier indexed by subject (sub), session (sid), and token (jti) to invalidate compromised sessions immediately without awaiting JWT expiration. 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 (Blind Stateless JWT Acceptance and Unchecked Trust Window Post-Identity Compromise) 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

Continuous