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

OpenFGA Consistent Snapshot Token Enforcement for Zanzibar 'New Enemy' Mitigation

Enforces cryptographically verifiable snapshot read tokens across distributed boundaries to mitigate the Zanzibar 'New Enemy' authorization race condition. Guarantees that ReBAC authorization evaluations against OpenFGA execute at a snapshot timestamp at least as fresh as the mutating transaction, preventing stale permission grants on newly modified or restricted resources.

Prohibited Anti-Pattern: Executing authorization checks with default eventual consistency snapshots after state or relation mutations.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Consistent Snapshot Token Enforcement for Zanzibar 'New Enemy' Mitigation - Enforces cryptographically verifiable snapshot read tokens across distributed boundaries to mitigate the Zanzibar 'New Enemy' authorization race condition. Guarantees that ReBAC authorization evaluations against OpenFGA execute at a snapshot timestamp at least as fresh as the mutating transaction, preventing stale permission grants on newly modified or restricted resources.
globs: src/**/authz/**/*.{ts,js}, src/**/services/**/*.{ts,js}, src/**/middleware/**/*.{ts,js}, src/**/controllers/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-rebac-snapshot-token-guardrail"
---

# OpenFGA Consistent Snapshot Token Enforcement for Zanzibar 'New Enemy' Mitigation

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Executing authorization checks with default eventual consistency snapshots after state or relation mutations.

## System Constraints
You are a Principal Security Architect enforcing Zanzibar ReBAC invariants. In distributed systems, permission revocation followed by sensitive data exposure is vulnerable to the 'New Enemy' race condition when reads evaluate against stale authorization snapshots. You must mandate that every authorization check either enforces strict snapshot freshness via client-propagated consistency tokens or binds explicitly to the write-transaction snapshot token generated by prior mutations.

## Strict Guidelines
- Engineers MUST ALWAYS propagate monotonic snapshot consistency tokens (e.g., OpenFGA consistency tokens or zedtokens) through gRPC/HTTP request metadata across all distributed service hops.
- Engineers MUST NOT execute OpenFGA `check` or `expand` calls using default or eventually-consistent snapshot read levels in request flows following data mutation or ACL revocation.
- Services MUST supply `consistency: ConsistencyPreference.HIGHER_CONSISTENCY` or bind explicit snapshot tokens (`consistency_token`) returned from previous tuple writes whenever evaluating access to resources mutated within the causal dependency window.
- Components NEVER accept untrusted, unverified client-supplied snapshot tokens without validating signature integrity or ensuring the monotonic sequence number falls within bounded cluster skew limits.
- Code SHOULD encapsulate authorization check invocations inside a centralized access control layer that automatically injects causal snapshot tokens extracted from execution context or distributed tracing headers.

## Bad vs Good Implementations
### Mitigating the 'New Enemy' Race Condition via Snapshot Token Propagation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Executing OpenFGA check queries without specifying consistency preferences or providing a causal snapshot token leaves the check vulnerable to replica lag. If access was revoked immediately prior to this call, the check evaluates against a stale snapshot, permitting unauthorized access to updated sensitive state.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

// VULNERABLE: Performs check with default eventual consistency.
// If an enemy was removed from an ACL right before this check,
// a replica lag in OpenFGA will return 'allowed: true', exposing newly written data.
export async function verifyDocumentAccess(
  userId: string,
  documentId: string
): Promise<boolean> {
  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'viewer',
    object: `document:${documentId}`,
  });

  return response.allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: By injecting `ConsistencyPreference.HIGHER_CONSISTENCY` and propagating causal `consistency_token` metadata derived from upstream write transactions, the authorization evaluation is guaranteed to reflect all mutations preceding the current operation.
```typescript
import { OpenFgaClient, ConsistencyPreference } from '@openfga/sdk';
import { RequestContext } from '../context/request-context';

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

export async function verifyDocumentAccess(
  userId: string,
  documentId: string,
  context: RequestContext
): Promise<boolean> {
  // SECURE: Enforce snapshot consistency using the transaction's causal token.
  // If a mutation just occurred, the consistency token guarantees evaluating
  // against a snapshot at least as fresh as that write, defeating the 'New Enemy' race.
  const consistencyToken = context.getConsistencyToken();

  const response = await fgaClient.check(
    {
      user: `user:${userId}`,
      relation: 'viewer',
      object: `document:${documentId}`,
      // Propagate explicit token or enforce higher consistency boundary
      ...(consistencyToken ? { consistency_token: consistencyToken } : {}),
    },
    {
      // Guarantee evaluation against a fresh snapshot replica
      consistency: ConsistencyPreference.HIGHER_CONSISTENCY,
    }
  );

  return response.allowed ?? false;
}
```

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 Consistent Snapshot Token Enforcement for Zanzibar 'New Enemy' Mitigation

OpenFGA Consistent Snapshot Token Enforcement for Zanzibar 'New Enemy' Mitigation defines an industrial-grade behavioral standard for security engineering. Enforces cryptographically verifiable snapshot read tokens across distributed boundaries to mitigate the Zanzibar 'New Enemy' authorization race condition. Guarantees that ReBAC authorization evaluations against OpenFGA execute at a snapshot timestamp at least as fresh as the mutating transaction, preventing stale permission grants on newly modified or restricted resources. 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 eventual consistency snapshots after state or relation mutations. 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 eventual consistency snapshots after state or relation mutations.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 propagate monotonic snapshot consistency tokens (e.g., OpenFGA consistency tokens or zedtokens) through gRPC/HTTP request metadata across all distributed service hops.

Engineers MUST ALWAYS propagate monotonic snapshot consistency tokens (e.g., OpenFGA consistency tokens or zedtokens) through gRPC/HTTP request metadata across all distributed service hops.

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 execute OpenFGA `check` or `expand` calls using default or eventually-consistent snapshot read levels in request flows following data mutation or ACL revocation.

Engineers MUST NOT execute OpenFGA `check` or `expand` calls using default or eventually-consistent snapshot read levels in request flows following data mutation or ACL 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.
3

Services MUST supply `consistency

Services MUST supply `consistency: ConsistencyPreference.HIGHER_CONSISTENCY` or bind explicit snapshot tokens (`consistency_token`) returned from previous tuple writes whenever evaluating access to resources mutated within the causal dependency window.

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 accept untrusted, unverified client-supplied snapshot tokens without validating signature integrity or ensuring the monotonic sequence number falls within bounded cluster skew limits.

Components NEVER accept untrusted, unverified client-supplied snapshot tokens without validating signature integrity or ensuring the monotonic sequence number falls within bounded cluster skew limits.

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 authorization check invocations inside a centralized access control layer that automatically injects causal snapshot tokens extracted from execution context or distributed tracing headers.

Code SHOULD encapsulate authorization check invocations inside a centralized access control layer that automatically injects causal snapshot tokens extracted from execution context or distributed tracing headers.

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 Consistent Snapshot Token Enforcement for Zanzibar 'New Enemy' Mitigation critical for AI coding assistants?

Enforces cryptographically verifiable snapshot read tokens across distributed boundaries to mitigate the Zanzibar 'New Enemy' authorization race condition. Guarantees that ReBAC authorization evaluations against OpenFGA execute at a snapshot timestamp at least as fresh as the mutating transaction, preventing stale permission grants on newly modified or restricted resources. 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 eventual consistency snapshots after state or relation mutations.) 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