This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: openid-caep-realtime-session-revocation-guardrail

OpenID CAEP Real-Time Cross-Boundary Session Revocation Standard

Enforces deterministic, sub-second propagation and enforcement of OpenID Continuous Access Evaluation Profile (CAEP) and Shared Signals and Events (SSE) revocation streams across edge runtimes. Mandates immediate cryptographically verified Security Event Token (SET) ingestion, distributed low-latency revocation tombstoning, and edge-evaluated session termination to eliminate replay vulnerabilities during credential compromise.

Prohibited Anti-Pattern: Relying on Passive JWT Expiration or Asynchronous Polling During Verified Credential Compromise

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenID CAEP Real-Time Cross-Boundary Session Revocation Standard - Enforces deterministic, sub-second propagation and enforcement of OpenID Continuous Access Evaluation Profile (CAEP) and Shared Signals and Events (SSE) revocation streams across edge runtimes. Mandates immediate cryptographically verified Security Event Token (SET) ingestion, distributed low-latency revocation tombstoning, and edge-evaluated session termination to eliminate replay vulnerabilities during credential compromise.
globs: src/auth/**/*.{ts,tsx}, src/middleware/**/*.{ts,tsx}, src/edge/**/*.{ts,tsx}, src/security/**/*.{ts,tsx}, src/api/webhooks/sse/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openid-caep-realtime-session-revocation-guardrail"
---

# OpenID CAEP Real-Time Cross-Boundary Session Revocation Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Relying on Passive JWT Expiration or Asynchronous Polling During Verified Credential Compromise

## System Constraints
You are a Principal Security Architect specializing in Zero Trust Identity and OpenID Shared Signals and Events (SSE / CAEP RFC 8935/8936). You mandate that all decoupled edge runtimes and distributed services immediately ingest, verify, and enforce push-based Security Event Tokens (SETs). You must prevent any architectural reliance on passive token expiration (TTL) or unbounded eventual consistency when processing session-revoked, credential-change, or token-claims-change events.

## Strict Guidelines
- Services MUST cryptographically verify inbound Security Event Tokens (SETs) using the issuer's published JWKS and RFC 7519/8417 specifications prior to parsing the payload.
- Engineers MUST write revoked subject identifiers, session identifiers, and tenant contexts into a distributed, multi-region edge memory tier (e.g., Redis cluster, edge key-value store) with sub-second replication latency.
- Edge authentication middleware MUST perform an O(1) non-blocking check against the localized revocation tombstone registry on every incoming request prior to executing downstream handlers.
- Engineers MUST NOT acknowledge HTTP 202 Accepted on CAEP push endpoints before validating token signatures, verifying issuer/audience claims, and committing the revocation state to the fast distributed store.
- Systems MUST track incoming SET JTI (JWT ID) claims in an anti-replay cache with a sliding-window TTL matching token validity to prevent replay of duplicate or spoofed revocation payloads.
- Components NEVER fall back to standard JWT TTL expiration when handling risk signals indicating account takeover, session hijacking, or credential leakage.

## Bad vs Good Implementations
### CAEP Push Receiver and Edge Middleware Revocation Checking

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The endpoint accepts unverified JWTs, omits JWKS signature and audience validation, schedules revocation asynchronously via slow disk-based persistence, and edge middleware relies solely on local token expiration (TTL), leaving an active window of vulnerability for compromised credentials.
```typescript
import { Request, Response } from 'express';
import jwt from 'jsonwebtoken';

// ANTI-PATTERN: Parsing SET without JWKS verification, updating database asynchronously,
// and relying on standard JWT expiry in middleware without immediate edge cache lookup.
export async function handleCaepEvent(req: Request, res: Response) {
  const rawToken = req.body;
  const decoded = jwt.decode(rawToken) as any;

  // Flaw 1: No cryptographic validation or audience verification
  const eventType = decoded.events['https://schemas.openid.net/secevent/caep/event-type/session-revoked'];
  if (eventType) {
    // Flaw 2: Asynchronously queuing write to slow persistence layer without edge propagation
    setImmediate(async () => {
      await slowDatabase.users.update({
        where: { id: decoded.sub },
        data: { activeSession: false }
      });
    });
  }

  // Premature 202 before state is committed or verified
  return res.status(202).send();
}

export async function edgeAuthMiddleware(req: Request, res: Response, next: Function) {
  const token = req.headers.authorization?.replace('Bearer ', '');
  // Flaw 3: Passive TTL verification allows compromised token usage until expiry
  const payload = jwt.verify(token!, process.env.JWT_SECRET!);
  return next();
}
```

#### Production Standard (Correct)
> **Standard**: Validates the SET cryptographically via remote JWKS, validates audience and issuer, enforces JTI deduplication, and commits revocation keys to a high-speed distributed cache before returning 202. Middleware verifies token validity against the edge revocation cache on every request within single-digit milliseconds.
```typescript
import { Request, Response, NextFunction } from 'express';
import { createRemoteJWKSet, jwtVerify } from 'jose';
import Redis from 'ioredis';

interface CaepSessionRevokedEvent {
  subject: { format: string; sub: string };
  session_id?: string;
  initiator?: 'admin' | 'user' | 'system';
  reason_admin?: { en: string };
}

const redis = new Redis(process.env.REDIS_EDGE_CLUSTER_URL!);
const JWKS = createRemoteJWKSet(new URL(process.env.IDP_JWKS_URI!));
const EXPECTED_ISSUER = process.env.IDP_ISSUER!;
const EXPECTED_AUDIENCE = process.env.SERVICE_CLIENT_ID!;
const CAEP_REVOCATION_URI = 'https://schemas.openid.net/secevent/caep/event-type/session-revoked';

export async function handleCaepPushEvent(req: Request, res: Response): Promise<Response> {
  try {
    const rawSet = req.body?.toString('utf-8') || req.body;
    const { payload } = await jwtVerify(rawSet, JWKS, {
      issuer: EXPECTED_ISSUER,
      audience: EXPECTED_AUDIENCE,
      algorithms: ['RS256', 'ES256']
    });

    const jti = payload.jti;
    const events = payload.events as Record<string, CaepSessionRevokedEvent>;
    
    if (!jti || !events || !events[CAEP_REVOCATION_URI]) {
      return res.status(400).json({ error: 'invalid_event_structure' });
    }

    // Guard against SET replay attacks
    const isNew = await redis.set(`set_jti:${jti}`, '1', 'EX', 86400, 'NX');
    if (!isNew) {
      return res.status(200).send(); // Idempotent acknowledgment
    }

    const eventData = events[CAEP_REVOCATION_URI];
    const subject = eventData.subject.sub;
    const sessionId = eventData.session_id;
    const ttlSeconds = 86400; // Matches max session lifetime

    const pipeline = redis.pipeline();
    if (sessionId) {
      pipeline.set(`revoked:session:${sessionId}`, '1', 'EX', ttlSeconds);
    } else {
      // Revoke all sessions for subject if specific session omitted
      pipeline.set(`revoked:user:${subject}`, Date.now().toString(), 'EX', ttlSeconds);
    }

    await pipeline.exec();
    return res.status(202).send();
  } catch (err) {
    return res.status(400).json({ error: 'invalid_token_signature_or_claims' });
  }
}

export async function edgeAuthMiddleware(req: Request, res: Response, next: NextFunction): Promise<void> {
  const authHeader = req.headers.authorization;
  if (!authHeader?.startsWith('Bearer ')) {
    res.status(401).json({ error: 'missing_or_invalid_authorization' });
    return;
  }

  const token = authHeader.substring(7);
  try {
    const { payload } = await jwtVerify(token, JWKS, {
      issuer: EXPECTED_ISSUER,
      audience: EXPECTED_AUDIENCE
    });

    const sub = payload.sub as string;
    const sid = payload.sid as string | undefined;
    const tokenIssuedAt = (payload.iat ?? 0) * 1000;

    // Multi-key check executed in single low-latency roundtrip
    const [sessionRevoked, userRevocationTimestamp] = await redis.mget(
      sid ? `revoked:session:${sid}` : 'nonexistent_key',
      `revoked:user:${sub}`
    );

    if (sessionRevoked) {
      res.status(401).json({ error: 'session_revoked', reason: 'caep_invalidation' });
      return;
    }

    if (userRevocationTimestamp && tokenIssuedAt <= parseInt(userRevocationTimestamp, 10)) {
      res.status(401).json({ error: 'token_revoked', reason: 'user_credentials_revoked' });
      return;
    }

    (req as any).user = payload;
    next();
  } catch {
    res.status(401).json({ error: 'invalid_token' });
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenID CAEP Real-Time Cross-Boundary Session Revocation Standard

OpenID CAEP Real-Time Cross-Boundary Session Revocation Standard defines an industrial-grade behavioral standard for security engineering. Enforces deterministic, sub-second propagation and enforcement of OpenID Continuous Access Evaluation Profile (CAEP) and Shared Signals and Events (SSE) revocation streams across edge runtimes. Mandates immediate cryptographically verified Security Event Token (SET) ingestion, distributed low-latency revocation tombstoning, and edge-evaluated session termination to eliminate replay vulnerabilities during credential compromise. 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: Relying on Passive JWT Expiration or Asynchronous Polling During Verified Credential 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 DriftRelying on Passive JWT Expiration or Asynchronous Polling During Verified Credential 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

Services MUST cryptographically verify inbound Security Event Tokens (SETs) using the issuer's published JWKS and RFC 7519/8417 specifications prior to parsing the payload.

Services MUST cryptographically verify inbound Security Event Tokens (SETs) using the issuer's published JWKS and RFC 7519/8417 specifications prior to parsing the payload.

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 write revoked subject identifiers, session identifiers, and tenant contexts into a distributed, multi-region edge memory tier (e.g., Redis cluster, edge key-value store) with sub-second replication latency.

Engineers MUST write revoked subject identifiers, session identifiers, and tenant contexts into a distributed, multi-region edge memory tier (e.g., Redis cluster, edge key-value store) with sub-second replication latency.

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

Edge authentication middleware MUST perform an O(1) non-blocking check against the localized revocation tombstone registry on every incoming request prior to executing downstream handlers.

Edge authentication middleware MUST perform an O(1) non-blocking check against the localized revocation tombstone registry on every incoming request prior to executing downstream handlers.

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 NOT acknowledge HTTP 202 Accepted on CAEP push endpoints before validating token signatures, verifying issuer/audience claims, and committing the revocation state to the fast distributed store.

Engineers MUST NOT acknowledge HTTP 202 Accepted on CAEP push endpoints before validating token signatures, verifying issuer/audience claims, and committing the revocation state to the fast distributed store.

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

Systems MUST track incoming SET JTI (JWT ID) claims in an anti-replay cache with a sliding-window TTL matching token validity to prevent replay of duplicate or spoofed revocation payloads.

Systems MUST track incoming SET JTI (JWT ID) claims in an anti-replay cache with a sliding-window TTL matching token validity to prevent replay of duplicate or spoofed revocation payloads.

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 standard JWT TTL expiration when handling risk signals indicating account takeover, session hijacking, or credential leakage.

Components NEVER fall back to standard JWT TTL expiration when handling risk signals indicating account takeover, session hijacking, or credential leakage.

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 OpenID CAEP Real-Time Cross-Boundary Session Revocation Standard critical for AI coding assistants?

Enforces deterministic, sub-second propagation and enforcement of OpenID Continuous Access Evaluation Profile (CAEP) and Shared Signals and Events (SSE) revocation streams across edge runtimes. Mandates immediate cryptographically verified Security Event Token (SET) ingestion, distributed low-latency revocation tombstoning, and edge-evaluated session termination to eliminate replay vulnerabilities during credential compromise. 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 (Relying on Passive JWT Expiration or Asynchronous Polling During Verified Credential 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

OpenID