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

OpenFGA ReBAC Consistency, Contextual Tuples, and Invalidation Invariants

Enforces strict read-after-write consistency, contextual tuple delegation, and change-driven invalidation across OpenFGA Relationship-Based Access Control (ReBAC) implementations. Prevents the Zanzibar 'New Enemy' vulnerability and eliminates cascading graph expansion latencies across multi-tenant microservices.

Prohibited Anti-Pattern: Stale ReBAC Evaluation via Uncoordinated Eventual Consistency and Unbounded Graph Expansion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA ReBAC Consistency, Contextual Tuples, and Invalidation Invariants - Enforces strict read-after-write consistency, contextual tuple delegation, and change-driven invalidation across OpenFGA Relationship-Based Access Control (ReBAC) implementations. Prevents the Zanzibar 'New Enemy' vulnerability and eliminates cascading graph expansion latencies across multi-tenant microservices.
globs: src/**/auth*/**/*.{ts,tsx}, src/**/policy/**/*.{ts,tsx}, src/**/security/**/*.{ts,tsx}, src/**/services/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-rebac-consistency-invalidation-invariants"
---

# OpenFGA ReBAC Consistency, Contextual Tuples, and Invalidation Invariants

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Stale ReBAC Evaluation via Uncoordinated Eventual Consistency and Unbounded Graph Expansion

## System Constraints
You are a Principal Security Architect enforcing OpenFGA ReBAC Consistency & Invalidation Invariants. Mandate that every authorization evaluation strictly protects against stale permission grants (the 'New Enemy' problem) by enforcing HIGHER_CONSISTENCY on mutation verification, utilizing contextual tuples for dynamic request-scoped metadata, bounding recursive relationship graphs to avert thread exhaustion, and consuming the OpenFGA Changes API to invalidate distributed local authorization caches deterministically.

## Strict Guidelines
- Engineers MUST ALWAYS specify `consistency: ConsistencyPreference.HIGHER_CONSISTENCY` when performing check operations directly following relationship tuple mutations (e.g., membership revocation, ownership transfer).
- Engineers MUST NOT persist ephemeral, request-bound attributes (such as tenant scopes, MFA step-up verification, or IP/temporal assertions) into the central OpenFGA store; these MUST be injected via `contextualTuples` or dynamic context objects at evaluation time.
- Services MUST process OpenFGA relationship mutations via a transactional outbox pattern and consume `readChanges()` streams to drive deterministic cache invalidations across edge nodes.
- Code SHOULD enforce strict timeouts (under 250ms) and bounded traversal heuristics on all OpenFGA checks to mitigate cascading latencies induced by deeply nested group-of-groups expansions.
- Components NEVER fall back to fail-open permission grants upon an OpenFGA client timeout, rate-limit, or network partition; all authorization decisions must default to deny (fail-closed).

## Bad vs Good Implementations
### Stale Read-After-Write and Global Tuples vs Consistent Contextual Authorization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The mutation introduces persistent store pollution by writing temporary IP context to global storage. Crucially, the subsequent check uses default `MINIMIZE_LATENCY` consistency against replica lag, permitting the revoked user to retain read access due to stale distributed replicas (the Zanzibar 'New Enemy' vulnerability).
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

// ANTI-PATTERN: Direct write followed by default eventually consistent check without
// transactional bounds, polluting the persistent store with ephemeral IP/MFA context
export async function transferDocumentOwnership(
  docId: string,
  currentOwnerId: string,
  newOwnerId: string,
  clientIp: string
) {
  // Writing ephemeral contextual conditions directly into central FGA store
  await fgaClient.write({
    writes: [
      { user: `user:${newOwnerId}`, relation: 'owner', _object: `doc:${docId}` },
      { user: `user:${newOwnerId}`, relation: 'verified_ip', _object: `doc:${docId}` }
    ],
    deletes: [
      { user: `user:${currentOwnerId}`, relation: 'owner', _object: `doc:${docId}` }
    ]
  });

  // Stale check: default consistency allows reading from out-of-date read-replicas
  // vulnerable to the 'New Enemy' problem where revoked user still resolves as allowed
  const isOldOwnerAllowed = await fgaClient.check({
    user: `user:${currentOwnerId}`,
    relation: 'viewer',
    _object: `doc:${docId}`
    // Missing consistency preference: defaults to MINIMIZE_LATENCY
  });

  return !isOldOwnerAllowed.allowed;
}
```

#### Production Standard (Correct)
> **Standard**: Uses `ConsistencyPreference.HIGHER_CONSISTENCY` to ensure read-after-write accuracy immediately following relationship changes. Injects short-lived state (`mfa_authenticated`) as a contextual tuple instead of writing to persistent storage, enforces a 250ms timeout abort signal, and guarantees a fail-closed response.
```typescript
import { OpenFgaClient, ConsistencyPreference } from '@openfga/sdk';
import { TRPCError } from '@trpc/server';

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

export async function transferDocumentOwnership(
  docId: string,
  currentOwnerId: string,
  newOwnerId: string,
  isMfaVerified: boolean
): Promise<boolean> {
  // 1. Mutate only core structural relationships
  await fgaClient.write({
    writes: [{ user: `user:${newOwnerId}`, relation: 'owner', _object: `doc:${docId}` }],
    deletes: [{ user: `user:${currentOwnerId}`, relation: 'owner', _object: `doc:${docId}` }]
  });

  // 2. Perform validation with explicit HIGHER_CONSISTENCY to bypass replica lag
  // 3. Inject dynamic request-scoped metadata via contextualTuples
  const abortController = new AbortController();
  const timeout = setTimeout(() => abortController.abort(), 250);

  try {
    const checkResponse = await fgaClient.check({
      user: `user:${newOwnerId}`,
      relation: 'can_edit',
      _object: `doc:${docId}`,
      contextualTuples: isMfaVerified ? [{
        user: `user:${newOwnerId}`,
        relation: 'mfa_authenticated',
        _object: `doc:${docId}`
      }] : [],
      consistency: ConsistencyPreference.HIGHER_CONSISTENCY
    }, {
      signal: abortController.signal
    });

    return checkResponse.allowed ?? false;
  } catch (error) {
    // Fail closed on evaluation timeout, network partition, or traversal errors
    throw new TRPCError({
      code: 'INTERNAL_SERVER_ERROR',
      message: 'Authorization evaluation timed out or failed; denying access by invariant.'
    });
  } finally {
    clearTimeout(timeout);
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA ReBAC Consistency, Contextual Tuples, and Invalidation Invariants

OpenFGA ReBAC Consistency, Contextual Tuples, and Invalidation Invariants defines an industrial-grade behavioral standard for security engineering. Enforces strict read-after-write consistency, contextual tuple delegation, and change-driven invalidation across OpenFGA Relationship-Based Access Control (ReBAC) implementations. Prevents the Zanzibar 'New Enemy' vulnerability and eliminates cascading graph expansion latencies across multi-tenant microservices. 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: Stale ReBAC Evaluation via Uncoordinated Eventual Consistency and Unbounded Graph Expansion 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 DriftStale ReBAC Evaluation via Uncoordinated Eventual Consistency and Unbounded Graph ExpansionCritical
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 specify `consistency

Engineers MUST ALWAYS specify `consistency: ConsistencyPreference.HIGHER_CONSISTENCY` when performing check operations directly following relationship tuple mutations (e.g., membership revocation, ownership transfer).

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 persist ephemeral, request-bound attributes (such as tenant scopes, MFA step-up verification, or IP/temporal assertions) into the central OpenFGA store

Engineers MUST NOT persist ephemeral, request-bound attributes (such as tenant scopes, MFA step-up verification, or IP/temporal assertions) into the central OpenFGA store; these MUST be injected via `contextualTuples` or dynamic context objects at evaluation time.

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 process OpenFGA relationship mutations via a transactional outbox pattern and consume `readChanges()` streams to drive deterministic cache invalidations across edge nodes.

Services MUST process OpenFGA relationship mutations via a transactional outbox pattern and consume `readChanges()` streams to drive deterministic cache invalidations across edge nodes.

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 SHOULD enforce strict timeouts (under 250ms) and bounded traversal heuristics on all OpenFGA checks to mitigate cascading latencies induced by deeply nested group-of-groups expansions.

Code SHOULD enforce strict timeouts (under 250ms) and bounded traversal heuristics on all OpenFGA checks to mitigate cascading latencies induced by deeply nested group-of-groups expansions.

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 fall back to fail-open permission grants upon an OpenFGA client timeout, rate-limit, or network partition

Components NEVER fall back to fail-open permission grants upon an OpenFGA client timeout, rate-limit, or network partition; all authorization decisions must default to deny (fail-closed).

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 Consistency, Contextual Tuples, and Invalidation Invariants critical for AI coding assistants?

Enforces strict read-after-write consistency, contextual tuple delegation, and change-driven invalidation across OpenFGA Relationship-Based Access Control (ReBAC) implementations. Prevents the Zanzibar 'New Enemy' vulnerability and eliminates cascading graph expansion latencies across multi-tenant microservices. 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 (Stale ReBAC Evaluation via Uncoordinated Eventual Consistency and Unbounded Graph Expansion) 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