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

OpenFGA Transactional Check-Before-Write Monotonic Consistency Guardrail

Enforces atomic transactional binding between OpenFGA authorization checks and state mutations using monotonic generation fencing tokens. Eliminates Time-of-Check to Time-of-Use (TOCTOU) authorization race conditions caused by asynchronous tuple revocation during concurrent writes.

Prohibited Anti-Pattern: Stateless Non-Atomic Check-Then-Write TOCTOU Race Condition

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Transactional Check-Before-Write Monotonic Consistency Guardrail - Enforces atomic transactional binding between OpenFGA authorization checks and state mutations using monotonic generation fencing tokens. Eliminates Time-of-Check to Time-of-Use (TOCTOU) authorization race conditions caused by asynchronous tuple revocation during concurrent writes.
globs: src/**/*.ts, src/**/*.service.ts, src/**/*.repository.ts, src/**/*.controller.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-check-before-write-monotonic-consistency"
---

# OpenFGA Transactional Check-Before-Write Monotonic Consistency Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Stateless Non-Atomic Check-Then-Write TOCTOU Race Condition

## System Constraints
You are a Principal Software Architect enforcing zero-trust transactional authorization invariants. Naive check-then-write workflows introduce critical Authorization-Time-to-Execution (TOCTOU) vulnerabilities when access tuples are revoked concurrently. You must ensure that every OpenFGA check-before-write operation binds the authorization evaluation to an atomic monotonic generation token or optimistic concurrency control (OCC) revision within the underlying data store.

## Strict Guidelines
- Engineers MUST ALWAYS bind relation evaluation to an optimistic concurrency control (OCC) fence or monotonic generation counter on the target entity.
- Engineers MUST NOT perform naked OpenFGA `check()` calls outside a transactional fence or without passing contextual consistency state.
- Code SHOULD leverage contextual tuples or monotonic version predicates in the mutation query to invalidate writes if authorization context changed mid-flight.
- Services MUST ensure that mutations atomically verify that the monotonic token evaluated during authorization remains identical at the exact moment of persistence.
- Components NEVER execute raw unversioned mutations (`UPDATE ... WHERE id = :id`) following an asynchronous authorization check.

## Bad vs Good Implementations
### Naive Check-Then-Write vs. Monotonic Generation Fencing

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: A naked OpenFGA check followed by a detached mutation allows an attacker or concurrent admin action to revoke access after the check completes but before the database write commits, resulting in an unauthorized write.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { prisma } from '../lib/prisma';

export async function updateProtectedDocument(
  fga: OpenFgaClient,
  userId: string,
  docId: string,
  content: string
): Promise<void> {
  // VULNERABLE: Asynchronous check creates a TOCTOU race window.
  // If user permission is revoked while updateProtectedDocument is running,
  // the unauthorized write executes successfully.
  const { allowed } = await fga.check({
    user: `user:${userId}`,
    relation: 'editor',
    object: `document:${docId}`,
  });

  if (!allowed) {
    throw new Error('AccessDenied');
  }

  // Blind mutation without monotonic fencing or transactional verification
  await prisma.document.update({
    where: { id: docId },
    data: { content },
  });
}
```

#### Production Standard (Correct)
> **Standard**: Binds authorization evaluation to a monotonic generation token inside a transaction with optimistic concurrency control. Any concurrent permission revocation or concurrent write invalidates the predicate, guaranteeing strict authorization consistency.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { prisma } from '../lib/prisma';

export async function updateProtectedDocument(
  fga: OpenFgaClient,
  userId: string,
  docId: string,
  content: string
): Promise<void> {
  await prisma.$transaction(async (tx) => {
    // 1. Acquire current state with monotonic authorization generation token
    const document = await tx.document.findUniqueOrThrow({
      where: { id: docId },
      select: { id: true, authGeneration: true, version: true },
    });

    // 2. Perform check passing contextual tuple bound to the read monotonic generation
    const { allowed } = await fga.check({
      user: `user:${userId}`,
      relation: 'editor',
      object: `document:${docId}`,
      contextualTuples: [
        {
          user: `user:${userId}`,
          relation: 'evaluated_at_generation',
          object: `generation:${document.authGeneration}`,
        },
      ],
    });

    if (!allowed) {
      throw new Error('AccessDenied');
    }

    // 3. Atomically fence the write against the observed monotonic generation and OCC version
    const updateResult = await tx.document.updateMany({
      where: {
        id: docId,
        authGeneration: document.authGeneration,
        version: document.version,
      },
      data: {
        content,
        version: { increment: 1 },
      },
    });

    if (updateResult.count === 0) {
      throw new Error('ConcurrentAuthorizationMutationConflict');
    }
  });
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA Transactional Check-Before-Write Monotonic Consistency Guardrail

OpenFGA Transactional Check-Before-Write Monotonic Consistency Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces atomic transactional binding between OpenFGA authorization checks and state mutations using monotonic generation fencing tokens. Eliminates Time-of-Check to Time-of-Use (TOCTOU) authorization race conditions caused by asynchronous tuple revocation during concurrent writes. 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: Stateless Non-Atomic Check-Then-Write TOCTOU Race Condition 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 DriftStateless Non-Atomic Check-Then-Write TOCTOU Race ConditionCritical
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 bind relation evaluation to an optimistic concurrency control (OCC) fence or monotonic generation counter on the target entity.

Engineers MUST ALWAYS bind relation evaluation to an optimistic concurrency control (OCC) fence or monotonic generation counter on the target entity.

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 perform naked OpenFGA `check()` calls outside a transactional fence or without passing contextual consistency state.

Engineers MUST NOT perform naked OpenFGA `check()` calls outside a transactional fence or without passing contextual consistency 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.
3

Code SHOULD leverage contextual tuples or monotonic version predicates in the mutation query to invalidate writes if authorization context changed mid-flight.

Code SHOULD leverage contextual tuples or monotonic version predicates in the mutation query to invalidate writes if authorization context changed mid-flight.

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 ensure that mutations atomically verify that the monotonic token evaluated during authorization remains identical at the exact moment of persistence.

Services MUST ensure that mutations atomically verify that the monotonic token evaluated during authorization remains identical at the exact moment of persistence.

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 execute raw unversioned mutations (`UPDATE ... WHERE id =

Components NEVER execute raw unversioned mutations (`UPDATE ... WHERE id = :id`) following an asynchronous authorization check.

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 Transactional Check-Before-Write Monotonic Consistency Guardrail critical for AI coding assistants?

Enforces atomic transactional binding between OpenFGA authorization checks and state mutations using monotonic generation fencing tokens. Eliminates Time-of-Check to Time-of-Use (TOCTOU) authorization race conditions caused by asynchronous tuple revocation during concurrent writes. 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 (Stateless Non-Atomic Check-Then-Write TOCTOU Race Condition) 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