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

OpenFGA Causality Consistency Token & Strict Read-After-Write Guardrails

Enforces strict causal consistency and token propagation in OpenFGA authorization checks to prevent the New Enemy Problem. Guarantees that permission revocations and access updates are immediately respected across distributed read replicas without authorization bypasses caused by replication lag.

Prohibited Anti-Pattern: Stale Replica Evaluation via Default Consistency Checks After Relationship Mutation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Causality Consistency Token & Strict Read-After-Write Guardrails - Enforces strict causal consistency and token propagation in OpenFGA authorization checks to prevent the New Enemy Problem. Guarantees that permission revocations and access updates are immediately respected across distributed read replicas without authorization bypasses caused by replication lag.
globs: src/**/*.ts, src/**/*.service.ts, src/**/*.controller.ts, src/auth/**/*.ts, lib/security/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-causality-consistency-token-invariants"
---

# OpenFGA Causality Consistency Token & Strict Read-After-Write Guardrails

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Stale Replica Evaluation via Default Consistency Checks After Relationship Mutation

## System Constraints
You are a Principal Security Architect and Rules Author enforcing OpenFGA authorization invariants. Your mission is to prevent the 'New Enemy Problem' by mandating strict causal ordering in Relation-Based Access Control (ReBAC) evaluations. When generating or auditing OpenFGA integration code, you must enforce the extraction and propagation of consistency tokens from write mutations into subsequent check evaluations, mandate `ConsistencyPreference.HIGHER_CONSISTENCY` on post-mutation authorization boundaries, and reject any design that relies on stale replica reads during critical privilege shifts.

## Strict Guidelines
- Engineers MUST ALWAYS capture the consistency token or continuation token returned by OpenFGA write and delete tuple operations.
- Engineers MUST propagate consistency tokens across service boundaries via HTTP response headers (e.g., `x-fga-consistency-token`) or distributed tracing baggage whenever a privilege mutation occurs.
- Engineers MUST NOT issue authorization checks with default or `MINIMIZE_LATENCY` consistency preferences immediately following a role, relation, or membership mutation in the same causal session.
- Services MUST explicitly specify `consistency: ConsistencyPreference.HIGHER_CONSISTENCY` in `fgaClient.check()` or `fgaClient.batchCheck()` calls when evaluating access for high-integrity resources or immediately following revocation events.
- Components NEVER assume read-your-writes consistency when omitting consistency tokens from OpenFGA SDK check requests across distributed clusters.

## Bad vs Good Implementations
### Mitigating the New Enemy Problem via HIGHER_CONSISTENCY and Token Forwarding

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The mutation fails to capture the OpenFGA consistency token, and the subsequent check evaluation uses default consistency (MINIMIZE_LATENCY). In a distributed environment with read replicas, replication lag allows the revoked user to bypass authorization and view sensitive data right after revocation.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

export class AccessManager {
  constructor(private readonly fgaClient: OpenFgaClient) {}

  async revokeUserAccess(documentId: string, userId: string): Promise<void> {
    // Mutates access control relation
    await this.fgaClient.write({
      deletes: [{
        user: `user:${userId}`,
        relation: 'editor',
        object: `document:${documentId}`
      }]
    });
    // ANTI-PATTERN: Returns void without capturing write token
  }

  async canViewDocument(documentId: string, userId: string): Promise<boolean> {
    // ANTI-PATTERN: Default check relies on MINIMIZE_LATENCY.
    // Subject to replication lag ('New Enemy Problem'), potentially granting
    // read access to a revoked user on stale read-replicas.
    const response = await this.fgaClient.check({
      user: `user:${userId}`,
      relation: 'viewer',
      object: `document:${documentId}`
    });
    return !!response.allowed;
  }
}
```

#### Production Standard (Correct)
> **Standard**: Captures and propagates the consistency token produced during the tuple write. Enforces ConsistencyPreference.HIGHER_CONSISTENCY on authorization evaluations to prevent stale replica reads and eliminate the New Enemy Problem.
```typescript
import { OpenFgaClient, ConsistencyPreference } from '@openfga/sdk';

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

export class AccessManager {
  constructor(private readonly fgaClient: OpenFgaClient) {}

  async revokeUserAccess(documentId: string, userId: string): Promise<RevokeResult> {
    const response = await this.fgaClient.write({
      deletes: [{
        user: `user:${userId}`,
        relation: 'editor',
        object: `document:${documentId}`
      }]
    });

    // PRODUCTION FIX: Return causal consistency token for cross-service propagation
    return {
      success: true,
      consistencyToken: response.continuation_token ?? undefined
    };
  }

  async canViewDocument(
    documentId: string,
    userId: string,
    causalToken?: string
  ): Promise<boolean> {
    // PRODUCTION FIX: Enforce HIGHER_CONSISTENCY or supply the explicit causal token
    const response = await this.fgaClient.check(
      {
        user: `user:${userId}`,
        relation: 'viewer',
        object: `document:${documentId}`,
        consistency: ConsistencyPreference.HIGHER_CONSISTENCY
      },
      causalToken ? { consistencyToken: causalToken } : undefined
    );

    return !!response.allowed;
  }
}
```

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 Causality Consistency Token & Strict Read-After-Write Guardrails

OpenFGA Causality Consistency Token & Strict Read-After-Write Guardrails defines an industrial-grade behavioral standard for security engineering. Enforces strict causal consistency and token propagation in OpenFGA authorization checks to prevent the New Enemy Problem. Guarantees that permission revocations and access updates are immediately respected across distributed read replicas without authorization bypasses caused by 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: Stale Replica Evaluation via Default Consistency Checks After Relationship Mutation 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 DriftStale Replica Evaluation via Default Consistency Checks After Relationship MutationCritical
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 or continuation token returned by OpenFGA write and delete tuple operations.

Engineers MUST ALWAYS capture the consistency token or continuation token returned by OpenFGA write and 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 consistency tokens across service boundaries via HTTP response headers (e.g., `x-fga-consistency-token`) or distributed tracing baggage whenever a privilege mutation occurs.

Engineers MUST propagate consistency tokens across service boundaries via HTTP response headers (e.g., `x-fga-consistency-token`) or distributed tracing baggage whenever a privilege mutation occurs.

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

Engineers MUST NOT issue authorization checks with default or `MINIMIZE_LATENCY` consistency preferences immediately following a role, relation, or membership mutation in the same causal session.

Engineers MUST NOT issue authorization checks with default or `MINIMIZE_LATENCY` consistency preferences immediately following a role, relation, or membership mutation in the same causal session.

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 explicitly specify `consistency

Services MUST explicitly specify `consistency: ConsistencyPreference.HIGHER_CONSISTENCY` in `fgaClient.check()` or `fgaClient.batchCheck()` calls when evaluating access for high-integrity resources or immediately following revocation events.

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 assume read-your-writes consistency when omitting consistency tokens from OpenFGA SDK check requests across distributed clusters.

Components NEVER assume read-your-writes consistency when omitting consistency tokens from OpenFGA SDK check requests across distributed clusters.

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 Causality Consistency Token & Strict Read-After-Write Guardrails critical for AI coding assistants?

Enforces strict causal consistency and token propagation in OpenFGA authorization checks to prevent the New Enemy Problem. Guarantees that permission revocations and access updates are immediately respected across distributed read replicas without authorization bypasses caused by 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 (Stale Replica Evaluation via Default Consistency Checks After Relationship Mutation) 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