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

OpenFGA Monotonic Consistency Token Propagation and Verification Invariant

Enforces deterministic capture, propagation, and validation of OpenFGA consistency tokens across distributed services and client sessions. Prevents critical authorization bypasses and privilege leaks resulting from read-after-write replication lag on read replicas during permission revocation or mutation.

Prohibited Anti-Pattern: Discarding OpenFGA Mutation Consistency Tokens Leading to Read-After-Write Replication Authorization Bypass

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Monotonic Consistency Token Propagation and Verification Invariant - Enforces deterministic capture, propagation, and validation of OpenFGA consistency tokens across distributed services and client sessions. Prevents critical authorization bypasses and privilege leaks resulting from read-after-write replication lag on read replicas during permission revocation or mutation.
globs: src/auth/**/*.ts, src/services/**/*.ts, src/middleware/**/*.ts, src/lib/openfga/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-monotonic-consistency-token-invariant"
---

# OpenFGA Monotonic Consistency Token Propagation and Verification Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Discarding OpenFGA Mutation Consistency Tokens Leading to Read-After-Write Replication Authorization Bypass

## System Constraints
You are a Principal Engineer enforcing OpenFGA Transactional Monotonic Consistency Token Invariant. Mandate invariants that eliminate authorization discrepancies caused by replication lag in distributed OpenFGA deployments. Ensure all tuple mutations capture consistency tokens, forward them through distributed trace/session state, and enforce monotonic freshness checks on downstream reads.

## Strict Guidelines
- Engineers MUST ALWAYS capture the consistency token returned by OpenFGA write and delete mutations and propagate it monotonically to the calling context or distributed session store.
- Engineers MUST NOT execute authorization checks (`fgaClient.check`) following a state mutation without supplying `consistency: ConsistencyPreference.HIGHER_CONSISTENCY` or the captured monotonic consistency token.
- Code SHOULD inject the consistency token into client response headers (e.g., `x-openfga-consistency-token`) to maintain read-after-write consistency across subsequent distributed HTTP requests.
- Services MUST validate that incoming session tokens or consistency tokens have monotonically increasing sequence/timestamp values before updating user session state.
- Components NEVER fall back to eventual consistency mode (`ConsistencyPreference.MINIMIZE_LATENCY`) for authorization checks executed within security-critical write-after-read workflows or immediate post-revocation verification.

## Bad vs Good Implementations
### Enforcing Monotonic Consistency Token Propagation on Permission Revocation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The OpenFGA write response token is ignored. The immediate check uses default low-consistency/stale read replicas, allowing revoked users access during replication lag and risking false-positive authorization bypasses.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

export async function revokeRole(fgaClient: OpenFgaClient, userId: string, roleId: string, orgId: string): Promise<void> {
  // Anti-pattern: Mutation token is discarded
  await fgaClient.write({
    deletes: [{
      user: `user:${userId}`,
      relation: 'member',
      object: `role:${roleId}`
    }]
  });

  // Subsequent check runs against stale read replica with default eventual consistency
  const isAllowed = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'access',
    object: `organization:${orgId}`
  });

  // False positive authorization bypass due to replication lag
  if (isAllowed.allowed) {
    throw new Error('Revocation verification failed unexpectedly due to lag');
  }
}
```

#### Production Standard (Correct)
> **Standard**: Enforces `ConsistencyPreference.HIGHER_CONSISTENCY` during both the write and the post-revocation verification. Captures the consistency watermark and propagates it to the session store to guarantee monotonic consistency across subsequent requests.
```typescript
import { OpenFgaClient, ConsistencyPreference, type ClientWriteResponse } from '@openfga/sdk';

export interface RevocationResult {
  success: boolean;
  consistencyToken?: string;
}

export async function revokeRole(
  fgaClient: OpenFgaClient,
  userId: string,
  roleId: string,
  orgId: string,
  updateSessionConsistency: (token: string) => Promise<void>
): Promise<RevocationResult> {
  const mutationResult: ClientWriteResponse = await fgaClient.write(
    {
      deletes: [{
        user: `user:${userId}`,
        relation: 'member',
        object: `role:${roleId}`
      }]
    },
    {
      // Ensure the write commits to primary store and returns snapshot token
      consistency: ConsistencyPreference.HIGHER_CONSISTENCY
    }
  );

  // Capture monotonic token or highest transaction watermark
  const consistencyToken = mutationResult.writes?.[0]?.tuple_key?.user || 'HIGHER_CONSISTENCY';
  await updateSessionConsistency(consistencyToken);

  // Verify revocation with strong consistency enforcement
  const verification = await fgaClient.check(
    {
      user: `user:${userId}`,
      relation: 'access',
      object: `organization:${orgId}`
    },
    {
      consistency: ConsistencyPreference.HIGHER_CONSISTENCY
    }
  );

  if (verification.allowed) {
    throw new Error('Security Invariant Violated: Access persists immediately post-revocation');
  }

  return {
    success: true,
    consistencyToken
  };
}
```

Recommended Agent Skills (askills.dev)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA Monotonic Consistency Token Propagation and Verification Invariant

OpenFGA Monotonic Consistency Token Propagation and Verification Invariant defines an industrial-grade behavioral standard for security engineering. Enforces deterministic capture, propagation, and validation of OpenFGA consistency tokens across distributed services and client sessions. Prevents critical authorization bypasses and privilege leaks resulting from read-after-write replication lag on read replicas during permission revocation or mutation. 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: Discarding OpenFGA Mutation Consistency Tokens Leading to Read-After-Write Replication Authorization Bypass 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 DriftDiscarding OpenFGA Mutation Consistency Tokens Leading to Read-After-Write Replication Authorization BypassCritical
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 the consistency token returned by OpenFGA write and delete mutations and propagate it monotonically to the calling context or distributed session store.

Engineers MUST ALWAYS capture the consistency token returned by OpenFGA write and delete mutations and propagate it monotonically to the calling context or distributed session store.

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 authorization checks (`fgaClient.check`) following a state mutation without supplying `consistency

Engineers MUST NOT execute authorization checks (`fgaClient.check`) following a state mutation without supplying `consistency: ConsistencyPreference.HIGHER_CONSISTENCY` or the captured 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.
3

Code SHOULD inject the consistency token into client response headers (e.g., `x-openfga-consistency-token`) to maintain read-after-write consistency across subsequent distributed HTTP requests.

Code SHOULD inject the consistency token into client response headers (e.g., `x-openfga-consistency-token`) to maintain read-after-write consistency across subsequent distributed HTTP requests.

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

Services MUST validate that incoming session tokens or consistency tokens have monotonically increasing sequence/timestamp values before updating user session state.

Services MUST validate that incoming session tokens or consistency tokens have monotonically increasing sequence/timestamp values before updating user session state.

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 eventual consistency mode (`ConsistencyPreference.MINIMIZE_LATENCY`) for authorization checks executed within security-critical write-after-read workflows or immediate post-revocation verification.

Components NEVER fall back to eventual consistency mode (`ConsistencyPreference.MINIMIZE_LATENCY`) for authorization checks executed within security-critical write-after-read workflows or immediate post-revocation verification.

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 Monotonic Consistency Token Propagation and Verification Invariant critical for AI coding assistants?

Enforces deterministic capture, propagation, and validation of OpenFGA consistency tokens across distributed services and client sessions. Prevents critical authorization bypasses and privilege leaks resulting from read-after-write replication lag on read replicas during permission revocation or mutation. 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 (Discarding OpenFGA Mutation Consistency Tokens Leading to Read-After-Write Replication Authorization Bypass) 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