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

OpenFGA 1.8 Causal Consistency Token Protocol for Multi-Region Checks

Enforces read-after-write causal consistency across multi-region OpenFGA/Zanzibar deployments by propagating and evaluating consistency tokens during authorization checks. Prevents authorization bypasses and privilege escalations resulting from stale read replicas evaluating authorization state before tuple writes or revocations replicate globally.

Prohibited Anti-Pattern: Unbounded Eventual Consistency Check Permitting Revoked Access via Stale Replica Evaluation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA 1.8 Causal Consistency Token Protocol for Multi-Region Checks - Enforces read-after-write causal consistency across multi-region OpenFGA/Zanzibar deployments by propagating and evaluating consistency tokens during authorization checks. Prevents authorization bypasses and privilege escalations resulting from stale read replicas evaluating authorization state before tuple writes or revocations replicate globally.
globs: src/auth/**/*.ts, src/services/auth*.ts, src/middleware/auth*.ts, src/lib/openfga/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-causal-consistency-token-check"
---

# OpenFGA 1.8 Causal Consistency Token Protocol for Multi-Region Checks

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded Eventual Consistency Check Permitting Revoked Access via Stale Replica Evaluation

## System Constraints
You are a Principal Security Architect enforcing the OpenFGA 1.8 Consistency Protocol. All authorization checks executed within a causal execution context following a write, grant, or revoke mutation MUST pass the received consistency token or explicitly declare `HIGHER_CONSISTENCY`. Never permit default `MINIMIZE_LATENCY` evaluations when checking access on newly mutated or session-sensitive resources.

## Strict Guidelines
- Engineers MUST ALWAYS capture and return the `consistency_token` produced by OpenFGA write or delete tuple operations.
- Engineers MUST propagate the latest session `consistency_token` through execution contexts (e.g., AsyncLocalStorage, HTTP headers, or request contexts).
- Services MUST pass the causal `consistency_token` in OpenFGA `check`, `batchCheck`, and `listObjects` calls when the request context depends on recent mutations.
- Engineers MUST NOT default to `ConsistencyPreference.MINIMIZE_LATENCY` for security-sensitive post-mutation checks where a stale read could lead to unauthorized data access or failed immediate revocation.
- Components NEVER execute raw OpenFGA checks without specifying an explicit consistency level (`HIGHER_CONSISTENCY` or providing a monotonic `consistency_token`).

## Bad vs Good Implementations
### Enforce Causal Consistency Token on Post-Write Authorization Check

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The check uses default consistency settings without propagating the write token or requesting higher consistency. In multi-region deployments, read replicas can lag behind the primary datastore by hundreds of milliseconds, returning `allowed: true` on an already-revoked relationship.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

export async function revokeAndVerifyAccess(
  fgaClient: OpenFgaClient,
  userId: string,
  documentId: string
): Promise<boolean> {
  // Anti-pattern: Writes tuple and discards returned consistency metadata
  await fgaClient.write({
    deletes: [{
      user: `user:${userId}`,
      relation: 'editor',
      object: `document:${documentId}`
    }]
  });

  // Stale read: Default check hits read replica where deletion has not replicated,
  // returning { allowed: true } and permitting unauthorized access.
  const { allowed } = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'editor',
    object: `document:${documentId}`
  });

  return allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: The write operation extracts the causal `continuation_token` (or consistency token in OpenFGA 1.8), passing it to the check invocation alongside `ConsistencyPreference.HIGHER_CONSISTENCY`. This forces the replica to wait for replication sync or forward the check to a causal snapshot, guaranteeing linearizable read-after-write security.
```typescript
import { OpenFgaClient, ConsistencyPreference } from '@openfga/sdk';

export async function revokeAndVerifyAccess(
  fgaClient: OpenFgaClient,
  userId: string,
  documentId: string
): Promise<boolean> {
  // Invariant: Capture write transaction consistency token
  const writeResult = await fgaClient.write({
    deletes: [{
      user: `user:${userId}`,
      relation: 'editor',
      object: `document:${documentId}`
    }]
  });

  const consistencyToken = writeResult.continuation_token;

  // Causal Check: Pass consistency token and require HIGHER_CONSISTENCY
  // Ensures read replica evaluates at or after the revocation snapshot
  const { allowed } = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'editor',
    object: `document:${documentId}`,
    consistency: ConsistencyPreference.HIGHER_CONSISTENCY,
    consistency_token: consistencyToken
  });

  return allowed ?? false;
}
```

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 1.8 Causal Consistency Token Protocol for Multi-Region Checks

OpenFGA 1.8 Causal Consistency Token Protocol for Multi-Region Checks defines an industrial-grade behavioral standard for security engineering. Enforces read-after-write causal consistency across multi-region OpenFGA/Zanzibar deployments by propagating and evaluating consistency tokens during authorization checks. Prevents authorization bypasses and privilege escalations resulting from stale read replicas evaluating authorization state before tuple writes or revocations replicate globally. 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 Eventual Consistency Check Permitting Revoked Access via Stale Replica Evaluation 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 Eventual Consistency Check Permitting Revoked Access via Stale Replica EvaluationCritical
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 capture and return the `consistency_token` produced by OpenFGA write or delete tuple operations.

Engineers MUST ALWAYS capture and return the `consistency_token` produced by OpenFGA write or delete tuple 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 propagate the latest session `consistency_token` through execution contexts (e.g., AsyncLocalStorage, HTTP headers, or request contexts).

Engineers MUST propagate the latest session `consistency_token` through execution contexts (e.g., AsyncLocalStorage, HTTP headers, or request contexts).

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 pass the causal `consistency_token` in OpenFGA `check`, `batchCheck`, and `listObjects` calls when the request context depends on recent mutations.

Services MUST pass the causal `consistency_token` in OpenFGA `check`, `batchCheck`, and `listObjects` calls when the request context depends on recent 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.
4

Engineers MUST NOT default to `ConsistencyPreference.MINIMIZE_LATENCY` for security-sensitive post-mutation checks where a stale read could lead to unauthorized data access or failed immediate revocation.

Engineers MUST NOT default to `ConsistencyPreference.MINIMIZE_LATENCY` for security-sensitive post-mutation checks where a stale read could lead to unauthorized data access or failed immediate revocation.

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 raw OpenFGA checks without specifying an explicit consistency level (`HIGHER_CONSISTENCY` or providing a monotonic `consistency_token`).

Components NEVER execute raw OpenFGA checks without specifying an explicit consistency level (`HIGHER_CONSISTENCY` or providing a monotonic `consistency_token`).

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 1.8 Causal Consistency Token Protocol for Multi-Region Checks critical for AI coding assistants?

Enforces read-after-write causal consistency across multi-region OpenFGA/Zanzibar deployments by propagating and evaluating consistency tokens during authorization checks. Prevents authorization bypasses and privilege escalations resulting from stale read replicas evaluating authorization state before tuple writes or revocations replicate globally. 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 Eventual Consistency Check Permitting Revoked Access via Stale Replica Evaluation) 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