This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: openfga-rebac-graph-coherency-bounded-traversal

OpenFGA ReBAC Graph Evaluation and Cache Coherency Guardrails

Enforces bounded traversal depth, strict cycle detection, and consistency-token validation during Relationship-Based Access Control (ReBAC) graph evaluations at scale. Prevents authorization bypasses caused by stale cache replication lag and eliminates denial-of-service vulnerabilities driven by unbounded recursive graph expansion.

Prohibited Anti-Pattern: Unbounded ReBAC graph expansion with stale or unversioned distributed cache reads permitting unauthorized access after permission revocation.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA ReBAC Graph Evaluation and Cache Coherency Guardrails - Enforces bounded traversal depth, strict cycle detection, and consistency-token validation during Relationship-Based Access Control (ReBAC) graph evaluations at scale. Prevents authorization bypasses caused by stale cache replication lag and eliminates denial-of-service vulnerabilities driven by unbounded recursive graph expansion.
globs: src/auth/**/*.ts, src/services/authorization/**/*.ts, src/lib/openfga/**/*.ts, src/security/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-rebac-graph-coherency-bounded-traversal"
---

# OpenFGA ReBAC Graph Evaluation and Cache Coherency Guardrails

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded ReBAC graph expansion with stale or unversioned distributed cache reads permitting unauthorized access after permission revocation.

## System Constraints
You are a Principal Engineer and Security Architect specializing in Zanzibar/OpenFGA ReBAC systems. Mandate strict cycle-breakers, bounded graph resolutions, and snapshot-consistent cache validation across all authorization paths.

## Strict Guidelines
- Engineers MUST ALWAYS enforce explicit request timeouts and circuit-breaker constraints when dispatching OpenFGA `check` and `expand` operations.
- Engineers MUST NOT rely on unversioned or un-invalidated distributed caches for ReBAC check outcomes, as replication lag directly results in critical privilege de-synchronization.
- Code SHOULD pass authorization consistency tokens (e.g., `HIGHER_CONSISTENCY` or store-level transaction tokens) when evaluating high-value operations immediately following a tuple mutation.
- Services MUST inject contextual tuples for in-flight transaction isolation rather than committing uncommitted relational state into the persistent OpenFGA store.
- Components NEVER execute recursive ReBAC relationship expansions without configuring deterministic depth limits and cycle-detection guards.

## Bad vs Good Implementations
### Bounded Graph Evaluation with Cache Coherency and Consistency Token

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Performs unchecked reads from an unversioned cache that ignores post-revocation consistency requirements (New Enemy Problem). Calls the ReBAC engine without timeouts, cancellation signals, or consistency tokens, leaving the evaluation vulnerable to cyclic latency spikes and stale authorization grants.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { redisCache } from '../cache';

const fgaClient = new OpenFgaClient({
  apiUrl: process.env.FGA_API_URL!,
  storeId: process.env.FGA_STORE_ID!,
});

export async function canAccessDocument(userId: string, documentId: string): Promise<boolean> {
  const cacheKey = `authz:${userId}:${documentId}`;
  
  // VULNERABLE: Naive caching without consistency tokens or invalidation on tuple writes.
  // Can serve stale 'allowed' decisions after permission revocation (New Enemy Problem).
  const cached = await redisCache.get(cacheKey);
  if (cached !== null) {
    return cached === 'true';
  }

  // VULNERABLE: Unbounded evaluation without timeouts, cycle protection, or consistency parameters.
  const { allowed } = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'can_view',
    object: `document:${documentId}`,
  });

  await redisCache.set(cacheKey, String(allowed), { EX: 3600 });
  return !!allowed;
}
```

#### Production Standard (Correct)
> **Standard**: Implements deterministic timeouts via AbortController to arrest cyclic relationship walk latency, supports OpenFGA consistency preferences with token-aware cache bypasses to prevent the New Enemy Problem, and limits cache TTLs to strictly bounded windows.
```typescript
import { OpenFgaClient, ConsistencyPreference } from '@openfga/sdk';
import { redisCache } from '../cache';

const fgaClient = new OpenFgaClient({
  apiUrl: process.env.FGA_API_URL!,
  storeId: process.env.FGA_STORE_ID!,
});

const REBAC_TIMEOUT_MS = 800;

interface CheckOptions {
  minStoreToken?: string;
  contextualTuples?: Array<{ user: string; relation: string; object: string }>;
}

export async function canAccessDocument(
  userId: string,
  documentId: string,
  options: CheckOptions = {}
): Promise<boolean> {
  // SECURE: Enforce bounded context with deterministic timeouts against cyclic graphs
  const abortController = new AbortController();
  const timeoutId = setTimeout(() => abortController.abort(), REBAC_TIMEOUT_MS);

  try {
    // Guard against cache-inconsistency: If a mutation token is provided, bypass stale read caches
    const isHighConsistency = Boolean(options.minStoreToken);
    const cacheKey = `authz:${userId}:${documentId}`;

    if (!isHighConsistency) {
      const cached = await redisCache.get(cacheKey);
      if (cached !== null) return cached === '1';
    }

    const response = await fgaClient.check(
      {
        user: `user:${userId}`,
        relation: 'can_view',
        object: `document:${documentId}`,
        contextualTuples: options.contextualTuples,
      },
      {
        signal: abortController.signal,
        consistency: isHighConsistency
          ? ConsistencyPreference.HigherConsistency
          : ConsistencyPreference.MinimizeLatency,
      }
    );

    const isAllowed = Boolean(response.allowed);
    
    // Bound cache TTL strictly to limit eventual consistency drift window
    if (!isHighConsistency) {
      await redisCache.set(cacheKey, isAllowed ? '1' : '0', { EX: 30 });
    }

    return isAllowed;
  } finally {
    clearTimeout(timeoutId);
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA ReBAC Graph Evaluation and Cache Coherency Guardrails

OpenFGA ReBAC Graph Evaluation and Cache Coherency Guardrails defines an industrial-grade behavioral standard for security engineering. Enforces bounded traversal depth, strict cycle detection, and consistency-token validation during Relationship-Based Access Control (ReBAC) graph evaluations at scale. Prevents authorization bypasses caused by stale cache replication lag and eliminates denial-of-service vulnerabilities driven by unbounded recursive graph expansion. 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: Unbounded ReBAC graph expansion with stale or unversioned distributed cache reads permitting unauthorized access after permission revocation. 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 DriftUnbounded ReBAC graph expansion with stale or unversioned distributed cache reads permitting unauthorized access after permission revocation.Critical
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 enforce explicit request timeouts and circuit-breaker constraints when dispatching OpenFGA `check` and `expand` operations.

Engineers MUST ALWAYS enforce explicit request timeouts and circuit-breaker constraints when dispatching OpenFGA `check` and `expand` operations.

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 on unversioned or un-invalidated distributed caches for ReBAC check outcomes, as replication lag directly results in critical privilege de-synchronization.

Engineers MUST NOT rely on unversioned or un-invalidated distributed caches for ReBAC check outcomes, as replication lag directly results in critical privilege de-synchronization.

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 SHOULD pass authorization consistency tokens (e.g., `HIGHER_CONSISTENCY` or store-level transaction tokens) when evaluating high-value operations immediately following a tuple mutation.

Code SHOULD pass authorization consistency tokens (e.g., `HIGHER_CONSISTENCY` or store-level transaction tokens) when evaluating high-value operations immediately following a tuple mutation.

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 inject contextual tuples for in-flight transaction isolation rather than committing uncommitted relational state into the persistent OpenFGA store.

Services MUST inject contextual tuples for in-flight transaction isolation rather than committing uncommitted relational state into the persistent OpenFGA 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

Components NEVER execute recursive ReBAC relationship expansions without configuring deterministic depth limits and cycle-detection guards.

Components NEVER execute recursive ReBAC relationship expansions without configuring deterministic depth limits and cycle-detection guards.

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 ReBAC Graph Evaluation and Cache Coherency Guardrails critical for AI coding assistants?

Enforces bounded traversal depth, strict cycle detection, and consistency-token validation during Relationship-Based Access Control (ReBAC) graph evaluations at scale. Prevents authorization bypasses caused by stale cache replication lag and eliminates denial-of-service vulnerabilities driven by unbounded recursive graph expansion. 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 (Unbounded ReBAC graph expansion with stale or unversioned distributed cache reads permitting unauthorized access after permission revocation.) 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