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

OpenFGA Zanzibar Consistency Token (zed_token) Evaluation Invariant

Enforces snapshot consistency token propagation or HIGHER_CONSISTENCY evaluation on all OpenFGA checks following state mutations. Eliminates read-after-write replication lag vulnerabilities such as stale authorization evaluations and the Zanzibar 'New Enemy' security flaw.

Prohibited Anti-Pattern: Executing authorization checks with default minimize-latency consistency immediately after tuple writes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Zanzibar Consistency Token (zed_token) Evaluation Invariant - Enforces snapshot consistency token propagation or HIGHER_CONSISTENCY evaluation on all OpenFGA checks following state mutations. Eliminates read-after-write replication lag vulnerabilities such as stale authorization evaluations and the Zanzibar 'New Enemy' security flaw.
globs: src/**/*.{ts,tsx}, lib/**/*.{ts,tsx}, services/**/*.{ts,tsx}, server/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-zanzibar-consistency-token-evaluation"
---

# OpenFGA Zanzibar Consistency Token (zed_token) Evaluation Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Executing authorization checks with default minimize-latency consistency immediately after tuple writes

## System Constraints
You are a Principal Security Architect enforcing Zanzibar consistency invariants across OpenFGA authorization pipelines. Mandate that every authorization check executed within write mutation flows, immediate follow-up reads, or distributed workflows explicitly specifies snapshot consistency tokens or HIGHER_CONSISTENCY preferences. Never permit default stale-tolerant read evaluation when replication lag can yield unauthorized access or false negative access blocks.

## Strict Guidelines
- Engineers MUST ALWAYS supply ConsistencyPreference.HIGHER_CONSISTENCY or a specific snapshot consistency token in client.check() following write mutations.
- Engineers MUST NOT rely on default client configuration (ConsistencyPreference.MINIMIZE_LATENCY) for checks evaluating permissions created or revoked in the current session or request lifecycle.
- Services MUST propagate consistency tokens across service boundaries via standardized HTTP response headers (e.g., 'X-FGA-Consistency-Token') for read-your-own-writes guarantees.
- Components NEVER assume OpenFGA read replicas are synchronously updated; authorization decisions following permission revocations MUST resolve at or ahead of the revocation token snapshot.
- Code SHOULD encapsulate client.write() and client.check() pairs into transactional authorization helper services that automatically bind and pass consistency context.

## Bad vs Good Implementations
### Unsynchronized Read-After-Write vs. Snapshot-Consistent Authorization Check

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omitting consistency options causes OpenFGA to hit potentially stale database replicas. In distributed deployments, replication delay produces non-deterministic authorization failures or fails to recognize revoking writes immediately preceding the check.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

export async function grantAndVerifyDocumentAccess(
  fgaClient: OpenFgaClient,
  userId: string,
  documentId: string
): Promise<boolean> {
  // Mutate permission tuple in Zanzibar store
  await fgaClient.write({
    writes: [{ user: `user:${userId}`, relation: 'viewer', object: `document:${documentId}` }],
  });

  // ANTI-PATTERN: Default check inherits ConsistencyPreference.MINIMIZE_LATENCY.
  // Stale read replicas may reject access or leak previous ACL boundaries (New Enemy problem).
  const { allowed } = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'viewer',
    object: `document:${documentId}`,
  });

  return allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: Using ConsistencyPreference.HIGHER_CONSISTENCY guarantees that the OpenFGA storage engine waits for replica synchronization or reads directly from leader/committed log snapshots, preventing read-after-write race conditions.
```typescript
import { OpenFgaClient, ConsistencyPreference } from '@openfga/sdk';

export interface AuthorizedMutationResult {
  allowed: boolean;
  fgaConsistencyToken?: string;
}

export async function grantAndVerifyDocumentAccess(
  fgaClient: OpenFgaClient,
  userId: string,
  documentId: string
): Promise<AuthorizedMutationResult> {
  // Mutate permission tuple and capture write result
  const writeResult = await fgaClient.write({
    writes: [{ user: `user:${userId}`, relation: 'viewer', object: `document:${documentId}` }],
  });

  // PRODUCTION INVARIANT: Explicitly enforce HIGHER_CONSISTENCY to force evaluation
  // at or past the write snapshot boundary, eliminating replica lag vulnerabilities.
  const { allowed } = await fgaClient.check(
    {
      user: `user:${userId}`,
      relation: 'viewer',
      object: `document:${documentId}`,
    },
    {
      consistency: ConsistencyPreference.HIGHER_CONSISTENCY,
    }
  );

  return {
    allowed: allowed ?? false,
    // Propagate snapshot state forward for downstream API or frontend requests
    fgaConsistencyToken: writeResult.writes?.[0]?.timestamp?.toString(),
  };
}
```

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 Zanzibar Consistency Token (zed_token) Evaluation Invariant

OpenFGA Zanzibar Consistency Token (zed_token) Evaluation Invariant defines an industrial-grade behavioral standard for security engineering. Enforces snapshot consistency token propagation or HIGHER_CONSISTENCY evaluation on all OpenFGA checks following state mutations. Eliminates read-after-write replication lag vulnerabilities such as stale authorization evaluations and the Zanzibar 'New Enemy' security flaw. 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: Executing authorization checks with default minimize-latency consistency immediately after tuple writes 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 DriftExecuting authorization checks with default minimize-latency consistency immediately after tuple writesCritical
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 supply ConsistencyPreference.HIGHER_CONSISTENCY or a specific snapshot consistency token in client.check() following write mutations.

Engineers MUST ALWAYS supply ConsistencyPreference.HIGHER_CONSISTENCY or a specific snapshot consistency token in client.check() following write 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.
2

Engineers MUST NOT rely on default client configuration (ConsistencyPreference.MINIMIZE_LATENCY) for checks evaluating permissions created or revoked in the current session or request lifecycle.

Engineers MUST NOT rely on default client configuration (ConsistencyPreference.MINIMIZE_LATENCY) for checks evaluating permissions created or revoked in the current session or request lifecycle.

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 propagate consistency tokens across service boundaries via standardized HTTP response headers (e.g., 'X-FGA-Consistency-Token') for read-your-own-writes guarantees.

Services MUST propagate consistency tokens across service boundaries via standardized HTTP response headers (e.g., 'X-FGA-Consistency-Token') for read-your-own-writes guarantees.

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

Components NEVER assume OpenFGA read replicas are synchronously updated

Components NEVER assume OpenFGA read replicas are synchronously updated; authorization decisions following permission revocations MUST resolve at or ahead of the revocation token snapshot.

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

Code SHOULD encapsulate client.write() and client.check() pairs into transactional authorization helper services that automatically bind and pass consistency context.

Code SHOULD encapsulate client.write() and client.check() pairs into transactional authorization helper services that automatically bind and pass consistency context.

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 Consistency Token (zed_token) Evaluation Invariant critical for AI coding assistants?

Enforces snapshot consistency token propagation or HIGHER_CONSISTENCY evaluation on all OpenFGA checks following state mutations. Eliminates read-after-write replication lag vulnerabilities such as stale authorization evaluations and the Zanzibar 'New Enemy' security flaw. 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 (Executing authorization checks with default minimize-latency consistency immediately after tuple writes) 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