This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: openfga-rebac-edge-cache-consistency-boundary

OpenFGA Distributed ReBAC Edge Cache Invalidation & Consistency Boundary

Enforces strict transactional consistency tokens and atomic cache invalidation semantics for OpenFGA relationship-based access control evaluations deployed at edge nodes. Eliminates stale authorization window vulnerabilities (the Zanzibar 'New Enemy' problem) by prohibiting unversioned TTL-only caching and requiring snapshot epoch validation across distributed evaluation points.

Prohibited Anti-Pattern: Naive TTL Edge Caching of OpenFGA Evaluations Without Monotonic Consistency Token Validation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Distributed ReBAC Edge Cache Invalidation & Consistency Boundary - Enforces strict transactional consistency tokens and atomic cache invalidation semantics for OpenFGA relationship-based access control evaluations deployed at edge nodes. Eliminates stale authorization window vulnerabilities (the Zanzibar 'New Enemy' problem) by prohibiting unversioned TTL-only caching and requiring snapshot epoch validation across distributed evaluation points.
globs: src/auth/**/*.{ts,tsx}, src/security/**/*.{ts,tsx}, src/services/fga/**/*.{ts,tsx}, src/edge/**/*.{ts,tsx}, src/middleware/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-rebac-edge-cache-consistency-boundary"
---

# OpenFGA Distributed ReBAC Edge Cache Invalidation & Consistency Boundary

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Naive TTL Edge Caching of OpenFGA Evaluations Without Monotonic Consistency Token Validation

## System Constraints
You are a Principal Security Architect specializing in Google Zanzibar implementations and OpenFGA distributed systems. Your objective is to enforce zero-tolerance invariants against stale ReBAC authorization decisions at distributed edge nodes. You must mandate snapshot token propagation, atomic write-invalidation barriers, and deterministic cache key hashing that includes transaction epochs.

## Strict Guidelines
- Engineers MUST ALWAYS include a monotonic consistency token (e.g., OpenFGA `consistency_token`, snapshot token, or high-watermark changelog revision) in distributed edge cache keys.
- Engineers MUST NOT employ static, unversioned Time-To-Live (TTL) caching for OpenFGA `check` or `expand` operations at edge runtimes.
- Services MUST publish transactional tuple mutation events to a globally distributed invalidation bus (e.g., Redis Pub/Sub, Kafka CDC) before acknowledging tuple write operations to the client.
- Code MUST fall back to a strictly consistent upstream OpenFGA evaluation whenever the edge client presents a consistency token newer than the edge node's local snapshot watermark.
- Components NEVER evaluate authorization decisions using cached results when the request context involves privilege revocation or critical security boundary crossing (e.g., tenant transfer, role downgrades).

## Bad vs Good Implementations
### Edge ReBAC Evaluation: Naive TTL Cache vs. Snapshot-Versioned Token Guardrail

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Evaluating access with a naive unversioned key and fixed 300s TTL creates a stale authorization window. If a user is removed from an organization or their role is revoked in the primary database, edge nodes continue granting access until the local TTL expires, directly violating Zanzibar consistency guarantees.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { edgeCache } from './edgeCache';

const fga = new OpenFgaClient({ apiUrl: process.env.FGA_API_URL! });

export async function evaluateAccess(userId: string, objectId: string, relation: string): Promise<boolean> {
  const cacheKey = `fga:${userId}:${relation}:${objectId}`;
  
  // CRITICAL VULNERABILITY: Naive TTL caching without consistency tokens.
  // Revoked permissions remain valid for up to 5 minutes across distributed edge nodes.
  const cached = await edgeCache.get<boolean>(cacheKey);
  if (cached !== null) {
    return cached;
  }

  const { allowed } = await fga.check({
    user: `user:${userId}`,
    relation,
    object: objectId,
  });

  await edgeCache.set(cacheKey, allowed, { ttlSeconds: 300 });
  return allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: The authorization decision embeds the monotonic snapshot watermark into the cache key. If the client carries a newer snapshot token indicating a recent write, the edge detects synchronization lag and delegates to the primary upstream OpenFGA instance with HigherConsistency, eliminating stale access windows.
```typescript
import { OpenFgaClient, ConsistencyPreference } from '@openfga/sdk';
import { edgeCache } from './edgeCache';
import { getEdgeWatermarkToken } from './watermarkService';

const fga = new OpenFgaClient({ apiUrl: process.env.FGA_API_URL! });

interface EvaluationContext {
  userId: string;
  objectId: string;
  relation: string;
  clientConsistencyToken?: string;
}

export async function evaluateAccess(ctx: EvaluationContext): Promise<boolean> {
  const edgeWatermark = await getEdgeWatermarkToken();
  
  // If client token is newer than edge watermark, force strict upstream evaluation
  const isEdgeLagging = ctx.clientConsistencyToken && ctx.clientConsistencyToken > edgeWatermark;
  
  if (!isEdgeLagging) {
    // Composite cache key bound strictly to the current monotonic snapshot watermark
    const cacheKey = `fga:v1:${edgeWatermark}:${ctx.userId}:${ctx.relation}:${ctx.objectId}`;
    const cached = await edgeCache.get<boolean>(cacheKey);
    if (cached !== null) {
      return cached;
    }
  }

  // Evaluate upstream with snapshot consistency preference
  const response = await fga.check(
    {
      user: `user:${ctx.userId}`,
      relation: ctx.relation,
      object: ctx.objectId,
    },
    {
      consistency: ConsistencyPreference.HigherConsistency,
    }
  );

  const allowed = response.allowed ?? false;
  
  // Cache bounded to current watermark epoch with bounded TTL
  if (!isEdgeLagging) {
    const activeKey = `fga:v1:${edgeWatermark}:${ctx.userId}:${ctx.relation}:${ctx.objectId}`;
    await edgeCache.set(activeKey, allowed, { ttlSeconds: 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 Distributed ReBAC Edge Cache Invalidation & Consistency Boundary

OpenFGA Distributed ReBAC Edge Cache Invalidation & Consistency Boundary defines an industrial-grade behavioral standard for security engineering. Enforces strict transactional consistency tokens and atomic cache invalidation semantics for OpenFGA relationship-based access control evaluations deployed at edge nodes. Eliminates stale authorization window vulnerabilities (the Zanzibar 'New Enemy' problem) by prohibiting unversioned TTL-only caching and requiring snapshot epoch validation across distributed evaluation points. 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: Naive TTL Edge Caching of OpenFGA Evaluations Without Monotonic Consistency Token Validation 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 DriftNaive TTL Edge Caching of OpenFGA Evaluations Without Monotonic Consistency Token ValidationCritical
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 include a monotonic consistency token (e.g., OpenFGA `consistency_token`, snapshot token, or high-watermark changelog revision) in distributed edge cache keys.

Engineers MUST ALWAYS include a monotonic consistency token (e.g., OpenFGA `consistency_token`, snapshot token, or high-watermark changelog revision) in distributed edge cache keys.

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 employ static, unversioned Time-To-Live (TTL) caching for OpenFGA `check` or `expand` operations at edge runtimes.

Engineers MUST NOT employ static, unversioned Time-To-Live (TTL) caching for OpenFGA `check` or `expand` operations at edge runtimes.

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 publish transactional tuple mutation events to a globally distributed invalidation bus (e.g., Redis Pub/Sub, Kafka CDC) before acknowledging tuple write operations to the client.

Services MUST publish transactional tuple mutation events to a globally distributed invalidation bus (e.g., Redis Pub/Sub, Kafka CDC) before acknowledging tuple write operations to the client.

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

Code MUST fall back to a strictly consistent upstream OpenFGA evaluation whenever the edge client presents a consistency token newer than the edge node's local snapshot watermark.

Code MUST fall back to a strictly consistent upstream OpenFGA evaluation whenever the edge client presents a consistency token newer than the edge node's local snapshot watermark.

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 evaluate authorization decisions using cached results when the request context involves privilege revocation or critical security boundary crossing (e.g., tenant transfer, role downgrades).

Components NEVER evaluate authorization decisions using cached results when the request context involves privilege revocation or critical security boundary crossing (e.g., tenant transfer, role downgrades).

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 Distributed ReBAC Edge Cache Invalidation & Consistency Boundary critical for AI coding assistants?

Enforces strict transactional consistency tokens and atomic cache invalidation semantics for OpenFGA relationship-based access control evaluations deployed at edge nodes. Eliminates stale authorization window vulnerabilities (the Zanzibar 'New Enemy' problem) by prohibiting unversioned TTL-only caching and requiring snapshot epoch validation across distributed evaluation points. 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 (Naive TTL Edge Caching of OpenFGA Evaluations Without Monotonic Consistency Token Validation) 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