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

OpenFGA Consistency Token Propagation and Read-After-Write Pinning

Enforces strict propagation and validation of OpenFGA consistency tokens across distributed microservice boundaries. Eliminates Zanzibar 'New Enemy' stale-cache authorization races by mandating that write responses return a token or monotonic timestamp and downstream authorization checks evaluate against at least that snapshot state. Mitigates authorization bypasses where revoked permissions remain active during replication lag.

Prohibited Anti-Pattern: Unpinned OpenFGA Check Executions Causing Stale Read Privilege Escalation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Consistency Token Propagation and Read-After-Write Pinning - Enforces strict propagation and validation of OpenFGA consistency tokens across distributed microservice boundaries. Eliminates Zanzibar 'New Enemy' stale-cache authorization races by mandating that write responses return a token or monotonic timestamp and downstream authorization checks evaluate against at least that snapshot state. Mitigates authorization bypasses where revoked permissions remain active during replication lag.
globs: src/services/**/*.{ts,js}, src/middleware/**/*.{ts,js}, src/controllers/**/*.{ts,js}, src/auth/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-consistency-token-pinning-guardrail"
---

# OpenFGA Consistency Token Propagation and Read-After-Write Pinning

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unpinned OpenFGA Check Executions Causing Stale Read Privilege Escalation

## System Constraints
You are a Principal Security Architect enforcing Zanzibar-style authorization consistency standards with OpenFGA. Every permission mutation (write/delete tuples) must capture the resulting consistency token and propagate it through HTTP/gRPC tracing context headers (e.g., 'x-openfga-consistency-token'). In subsequent authorization checks (OpenFGA 'check' or 'batchCheck'), clients MUST pin consistency to HIGHER_CONSISTENCY or explicitly inject the captured consistency token via check request options or contextual tuples. Any unpinned check following an authorization mutation within the same distributed transaction lifecycle is a critical security violation.

## Strict Guidelines
- Services MUST ALWAYS capture the consistency token returned by OpenFGA Write/Delete API calls and return it to the caller via an HTTP response header or envelope field.
- Engineers MUST NEVER execute OpenFGA `client.check()` using `ConsistencyPreference.UNSPECIFIED` or `MINIMIZE_LATENCY` immediately following a tuple mutation or when handling requests carrying an inbound consistency token.
- Distributed microservices MUST extract incoming OpenFGA consistency tokens from upstream headers (e.g., `x-openfga-token`) and inject them into all downstream check queries within the execution context.
- Code MUST pass `consistency: ConsistencyPreference.HIGHER_CONSISTENCY` or provide explicit contextual snapshot constraints whenever verifying freshly revoked or modified resource permissions.
- Services MUST reject or warn on incoming read requests that lack a consistency token when operating on recently modified sensitive entities.

## Bad vs Good Implementations
### Unpinned Check After Revocation (Vulnerable to Replication Lag) vs. Consistency-Pinned Evaluation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The code deletes a permission tuple but ignores the transaction receipt and performs a check with default (stale/eventually consistent) consistency preferences. On multi-replica or globally distributed OpenFGA deployments, the check query can hit an out-of-sync node and confirm access that was just revoked.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

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

  // DANGEROUS: Default check may hit a replica OpenFGA node that hasn't replicated the deletion
  // Stale read returns { allowed: true } allowing unauthorized access!
  const { allowed } = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'viewer',
    object: `document:${docId}`
  });

  return allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: Production invariant compliant implementation ensuring memory safety, deterministic execution, and zero runtime hallucination.
```typescript
import { OpenFgaClient, ConsistencyPreference } from '@openfga/sdk';

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

export interface AuthzWriteResult {
  allowed: boolean;
  consistencyToken?: string;
}

export async function revokeAndVerifyAccess(userId: string, docId: string): Promise<AuthzWriteResult> {
  // Production standard: Write and capture the consistency token or transactional snapshot
  const writeResponse = await fgaClient.write({
    deletes: [{
      user: `user:${userId}`,
      relation: 'viewer',
      object: `document:${docId}`
    }]
  });

  // Extract token or fallback to HIGHER_CONSISTENCY guarantee to defeat stale read race
  const consistencyToken = writeResponse.writes?.[0]?.timestamp ?? undefined;

  // Pin check consistency explicitly to eliminate read-after-write privilege leak
  const { allowed } = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'viewer',
    object: `document:${docId}`,
    consistency: ConsistencyPreference.HIGHER_CONSISTENCY
  });

  return {
    allowed: allowed ?? false,
    consistencyToken
  };
}
```

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA Consistency Token Propagation and Read-After-Write Pinning

OpenFGA Consistency Token Propagation and Read-After-Write Pinning defines an industrial-grade behavioral standard for security engineering. Enforces strict propagation and validation of OpenFGA consistency tokens across distributed microservice boundaries. Eliminates Zanzibar 'New Enemy' stale-cache authorization races by mandating that write responses return a token or monotonic timestamp and downstream authorization checks evaluate against at least that snapshot state. Mitigates authorization bypasses where revoked permissions remain active during replication lag. 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: Unpinned OpenFGA Check Executions Causing Stale Read Privilege Escalation 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 DriftUnpinned OpenFGA Check Executions Causing Stale Read Privilege EscalationCritical
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

Services MUST ALWAYS capture the consistency token returned by OpenFGA Write/Delete API calls and return it to the caller via an HTTP response header or envelope field.

Services MUST ALWAYS capture the consistency token returned by OpenFGA Write/Delete API calls and return it to the caller via an HTTP response header or envelope field.

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 NEVER execute OpenFGA `client.check()` using `ConsistencyPreference.UNSPECIFIED` or `MINIMIZE_LATENCY` immediately following a tuple mutation or when handling requests carrying an inbound consistency token.

Engineers MUST NEVER execute OpenFGA `client.check()` using `ConsistencyPreference.UNSPECIFIED` or `MINIMIZE_LATENCY` immediately following a tuple mutation or when handling requests carrying an inbound 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.
3

Distributed microservices MUST extract incoming OpenFGA consistency tokens from upstream headers (e.g., `x-openfga-token`) and inject them into all downstream check queries within the execution context.

Distributed microservices MUST extract incoming OpenFGA consistency tokens from upstream headers (e.g., `x-openfga-token`) and inject them into all downstream check queries within the execution 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.
4

Code MUST pass `consistency

Code MUST pass `consistency: ConsistencyPreference.HIGHER_CONSISTENCY` or provide explicit contextual snapshot constraints whenever verifying freshly revoked or modified resource permissions.

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

Services MUST reject or warn on incoming read requests that lack a consistency token when operating on recently modified sensitive entities.

Services MUST reject or warn on incoming read requests that lack a consistency token when operating on recently modified sensitive entities.

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 Consistency Token Propagation and Read-After-Write Pinning critical for AI coding assistants?

Enforces strict propagation and validation of OpenFGA consistency tokens across distributed microservice boundaries. Eliminates Zanzibar 'New Enemy' stale-cache authorization races by mandating that write responses return a token or monotonic timestamp and downstream authorization checks evaluate against at least that snapshot state. Mitigates authorization bypasses where revoked permissions remain active during replication lag. 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 (Unpinned OpenFGA Check Executions Causing Stale Read Privilege Escalation) 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