This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: openfga-zanzibar-cache-invalidation-invariants

OpenFGA Zanzibar ReBAC Cache Synchronization & Consistency Token Invariants

Prevents authorization bypass and stale permission windows (the 'New Enemy' problem) during rapid ReBAC relationship mutations. Mandates that distributed check caching strictly pairs with transactional tuple invalidation, versioned generation keys, or consistency token propagation rather than uncoordinated static TTLs.

Prohibited Anti-Pattern: Uncoordinated Fixed-TTL Check Caching Allowing Revoked Access During Rapid Mutations

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Zanzibar ReBAC Cache Synchronization & Consistency Token Invariants - Prevents authorization bypass and stale permission windows (the 'New Enemy' problem) during rapid ReBAC relationship mutations. Mandates that distributed check caching strictly pairs with transactional tuple invalidation, versioned generation keys, or consistency token propagation rather than uncoordinated static TTLs.
globs: src/auth/**/*.{ts,tsx}, src/services/**/*.{ts,tsx}, src/lib/fga/**/*.{ts,tsx}, src/middleware/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-zanzibar-cache-invalidation-invariants"
---

# OpenFGA Zanzibar ReBAC Cache Synchronization & Consistency Token Invariants

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Uncoordinated Fixed-TTL Check Caching Allowing Revoked Access During Rapid Mutations

## System Constraints
You are a Principal Security Architect enforcing Google Zanzibar/OpenFGA consistency semantics. You must reject any authorization caching strategy that relies on uncoordinated wall-clock TTLs without transactional invalidation or consistency tokens. Enforce strict cache-key generation containing object version vectors or real-time invalidation hooks via transactional outbox/CDC to eliminate stale authorization checks.

## Strict Guidelines
- Engineers MUST NEVER cache raw OpenFGA `check` responses using arbitrary wall-clock TTLs without a synchronous or transactional invalidation mechanism.
- Engineers MUST ALWAYS invalidate affected entity cache keys atomically or via an established transactional outbox/CDC stream immediately upon issuing `writeTuples` or `deleteTuples`.
- Code MUST embed an object revision counter, entity version, or consistency token (Zookie/SnapToken pattern) into the distributed cache key: `authz:{storeId}:{objectType}:{objectId}:{relation}:{user}:{version}`.
- Services MUST query OpenFGA with `consistency: MINIMALLY_CONSISTENT` or `AT_LEAST_AS_FRESH` referencing the transaction's mutation timestamp when evaluating permissions immediately following state mutations.
- Components NEVER treat a cache failure as an authorization grant; authorization check failures in cache or OpenFGA MUST fail closed (deny by default).

## Bad vs Good Implementations
### Anti-Pattern: Static Redis Check Caching Causing Revocation Leakage

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Caching OpenFGA check evaluations with fixed-duration Redis keys leaves a 5-minute security gap when permissions are revoked via `write`. An attacker retaining the revoked token can continue accessing protected resources until the cache entry expires.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { redis } from './redis';

export async function checkPermission(
  fga: OpenFgaClient,
  user: string,
  relation: string,
  object: string
): Promise<boolean> {
  const cacheKey = `perm:${user}:${relation}:${object}`;
  const cached = await redis.get(cacheKey);
  if (cached !== null) {
    return cached === 'true';
  }

  // DANGEROUS: Caching for 5 minutes without linking to tuple mutation events.
  // If user membership is revoked, permissions persist for up to 300 seconds.
  const { allowed } = await fga.check({ tuple_key: { user, relation, object } });
  await redis.set(cacheKey, String(allowed), 'EX', 300);
  return !!allowed;
}

export async function revokeAccess(fga: OpenFgaClient, user: string, relation: string, object: string) {
  await fga.write({ deletes: [{ user, relation, object }] });
  // Anti-pattern: Redis cache is not purged; stale read window exposed
}
```

#### Production Standard (Correct)
> **Standard**: Incorporating an entity generation counter into the cache key guarantees immediate cache invalidation across all checked relations when an authorization tuple is revoked. Subsequent checks reference the bumped generation, preventing the 'New Enemy' stale cache authorization vulnerability.
```typescript
import { OpenFgaClient, ConsistencyPreference } from '@openfga/sdk';
import { redis } from './redis';

interface AuthorizationContext {
  user: string;
  relation: string;
  objectType: string;
  objectId: string;
  minimumVersion?: number;
}

// Incrementing object generation ensures all sub-relations invalidate simultaneously
export async function revokeAccess(
  fga: OpenFgaClient,
  user: string,
  relation: string,
  objectType: string,
  objectId: string
): Promise<number> {
  const targetObject = `${objectType}:${objectId}`;
  
  // Atomic transaction: delete tuple and advance generation version
  await fga.write({
    deletes: [{ user, relation, object: targetObject }],
  });

  // Atomically bump entity version in Redis to invalidate all derived check caches
  const newVersion = await redis.incr(`fga:version:${targetObject}`);
  return newVersion;
}

export async function checkPermission(
  fga: OpenFgaClient,
  ctx: AuthorizationContext
): Promise<boolean> {
  const targetObject = `${ctx.objectType}:${ctx.objectId}`;
  
  // Fetch current object generation version
  const currentVersion = ctx.minimumVersion ?? 
    Number(await redis.get(`fga:version:${targetObject}`) || '0');

  const cacheKey = `fga:check:${ctx.user}:${ctx.relation}:${targetObject}:v${currentVersion}`;
  const cached = await redis.get(cacheKey);
  if (cached !== null) {
    return cached === '1';
  }

  const { allowed } = await fga.check({
    tuple_key: {
      user: ctx.user,
      relation: ctx.relation,
      object: targetObject,
    },
    consistency: ConsistencyPreference.HigherConsistency,
  });

  // Safe to cache with short TTL as version key guards against stale reads on write
  await redis.set(cacheKey, allowed ? '1' : '0', 'EX', 60);
  return !!allowed;
}
```

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: OpenFGA Zanzibar ReBAC Cache Synchronization & Consistency Token Invariants

OpenFGA Zanzibar ReBAC Cache Synchronization & Consistency Token Invariants defines an industrial-grade behavioral standard for security engineering. Prevents authorization bypass and stale permission windows (the 'New Enemy' problem) during rapid ReBAC relationship mutations. Mandates that distributed check caching strictly pairs with transactional tuple invalidation, versioned generation keys, or consistency token propagation rather than uncoordinated static TTLs. 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: Uncoordinated Fixed-TTL Check Caching Allowing Revoked Access During Rapid Mutations 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 DriftUncoordinated Fixed-TTL Check Caching Allowing Revoked Access During Rapid MutationsCritical
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 NEVER cache raw OpenFGA `check` responses using arbitrary wall-clock TTLs without a synchronous or transactional invalidation mechanism.

Engineers MUST NEVER cache raw OpenFGA `check` responses using arbitrary wall-clock TTLs without a synchronous or transactional invalidation mechanism.

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 ALWAYS invalidate affected entity cache keys atomically or via an established transactional outbox/CDC stream immediately upon issuing `writeTuples` or `deleteTuples`.

Engineers MUST ALWAYS invalidate affected entity cache keys atomically or via an established transactional outbox/CDC stream immediately upon issuing `writeTuples` or `deleteTuples`.

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 MUST embed an object revision counter, entity version, or consistency token (Zookie/SnapToken pattern) into the distributed cache key

Code MUST embed an object revision counter, entity version, or consistency token (Zookie/SnapToken pattern) into the distributed cache key: `authz:{storeId}:{objectType}:{objectId}:{relation}:{user}:{version}`.

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 query OpenFGA with `consistency

Services MUST query OpenFGA with `consistency: MINIMALLY_CONSISTENT` or `AT_LEAST_AS_FRESH` referencing the transaction's mutation timestamp when evaluating permissions immediately following state mutations.

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 treat a cache failure as an authorization grant

Components NEVER treat a cache failure as an authorization grant; authorization check failures in cache or OpenFGA MUST fail closed (deny by default).

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 OpenFGA Zanzibar ReBAC Cache Synchronization & Consistency Token Invariants critical for AI coding assistants?

Prevents authorization bypass and stale permission windows (the 'New Enemy' problem) during rapid ReBAC relationship mutations. Mandates that distributed check caching strictly pairs with transactional tuple invalidation, versioned generation keys, or consistency token propagation rather than uncoordinated static TTLs. 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 (Uncoordinated Fixed-TTL Check Caching Allowing Revoked Access During Rapid Mutations) 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

OpenFGA