This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: openfga-contextual-tuples-transaction-isolation-standard

OpenFGA Contextual Tuples Transaction Isolation & TOCTOU Eradication Standard

Mandates that ephemeral contextual tuples provided to OpenFGA authorization checks are strictly derived from and bound to transactional database snapshots (or locked rows). This eradicates Time-of-Check to Time-of-Use (TOCTOU) authorization vulnerabilities where parent reassignment, tenancy migration, or ownership transfer occurs concurrently between check evaluation and database mutation.

Prohibited Anti-Pattern: Evaluating Ephemeral Contextual Tuples from Unlocked or Pre-Transaction Cache Prior to Mutation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Contextual Tuples Transaction Isolation & TOCTOU Eradication Standard - Mandates that ephemeral contextual tuples provided to OpenFGA authorization checks are strictly derived from and bound to transactional database snapshots (or locked rows). This eradicates Time-of-Check to Time-of-Use (TOCTOU) authorization vulnerabilities where parent reassignment, tenancy migration, or ownership transfer occurs concurrently between check evaluation and database mutation.
globs: src/**/*.service.ts, src/**/*.repository.ts, src/auth/**/*.ts, src/modules/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuples-transaction-isolation-standard"
---

# OpenFGA Contextual Tuples Transaction Isolation & TOCTOU Eradication Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Evaluating Ephemeral Contextual Tuples from Unlocked or Pre-Transaction Cache Prior to Mutation

## System Constraints
You are a Principal Security Architect enforcing the OpenFGA Contextual Tuples Transaction Isolation Standard. Contextual tuples inject ephemeral relationship state into OpenFGA evaluations; if this state diverges from the underlying transactional datastore during or immediately after the check, authorization guarantees collapse. You must mandate that any contextual tuple reflecting volatile application state (e.g., dynamic parent containers, tenant assignments, temporary delegation tokens) is evaluated within an active database transaction isolation boundary or verified via strict optimistic concurrency control (OCC) versioning prior to commit.

## Strict Guidelines
- Engineers MUST ALWAYS fetch the state used to construct contextual tuples within an active transactional read snapshot or with pessimistic locks (`SELECT ... FOR UPDATE` or `REPEATABLE READ`) when an authorized mutation follows.
- Engineers MUST NOT evaluate OpenFGA checks using cached or client-provided contextual tuples without re-verifying those tuples against the transactional store inside the mutating transaction.
- Code MUST rollback the surrounding database transaction immediately if an OpenFGA contextual tuple check evaluates to `allowed: false`.
- Services MUST verify version stamps or lock counters on all entities represented in contextual tuples when using Optimistic Concurrency Control (OCC) to guarantee the entity state did not mutate between authorization and write execution.
- Components NEVER issue non-transactional database updates based on authorization checks executed prior to acquiring record locks for dynamic hierarchical relations (e.g., moving a document across workspace boundaries).

## Bad vs Good Implementations
### Eradicating TOCTOU in Contextual Hierarchical Re-parenting

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The folder metadata used to construct the contextual tuple was fetched without transactional isolation or a row lock. A concurrent request could alter the folder's workspace or security boundary after `fga.check()` completes but before `db.document.update()` executes, allowing unauthorized document movement.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { db } from '../database';

export async function moveDocument(
  fga: OpenFgaClient,
  userId: string,
  docId: string,
  targetFolderId: string
): Promise<void> {
  // ANTI-PATTERN: Reading parent folder without a lock or transaction snapshot.
  const folder = await db.folder.findUnique({ where: { id: targetFolderId } });
  if (!folder) throw new Error('Folder not found');

  // Checking authorization with an unpinned, ephemeral contextual tuple
  const { allowed } = await fga.check({
    user: `user:${userId}`,
    relation: 'can_create_document',
    object: `folder:${folder.id}`,
    contextualTuples: [
      // Stale contextual state: folder's parent workspace could change concurrently
      { user: `user:${userId}`, relation: 'editor', object: `workspace:${folder.workspaceId}` }
    ]
  });

  if (!allowed) throw new Error('Unauthorized');

  // TOCTOU Window: Target folder may have been re-parented to an unauthorized workspace here
  await db.document.update({
    where: { id: docId },
    data: { folderId: targetFolderId }
  });
}
```

#### Production Standard (Correct)
> **Standard**: The target folder row is locked inside a transactional boundary (`FOR UPDATE`), ensuring its parent hierarchy cannot be modified concurrently. The contextual tuple is derived directly from the locked row, eradicating any TOCTOU window between authorization validation and the target mutation.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { prisma } from '../database';

export async function moveDocument(
  fga: OpenFgaClient,
  userId: string,
  docId: string,
  targetFolderId: string
): Promise<void> {
  // Enforce transactional isolation: pessimistic lock prevents TOCTOU mutation
  await prisma.$transaction(async (tx) => {
    // 1. Lock the target folder row to freeze its hierarchy for the duration of the tx
    const [lockedFolder] = await tx.$queryRaw<Array<{ id: string; workspace_id: string; version: number }>>`
      SELECT id, workspace_id, version FROM "Folder"
      WHERE id = ${targetFolderId}
      FOR UPDATE
    `;

    if (!lockedFolder) throw new Error('Folder not found');

    // 2. Evaluate authorization using validated, locked snapshot state
    const { allowed } = await fga.check({
      user: `user:${userId}`,
      relation: 'can_create_document',
      object: `folder:${lockedFolder.id}`,
      contextualTuples: [
        {
          user: `user:${userId}`,
          relation: 'editor',
          object: `workspace:${lockedFolder.workspace_id}`
        }
      ]
    });

    if (!allowed) {
      throw new Error('Forbidden: Insufficient permissions for destination workspace');
    }

    // 3. Apply mutation inside the locked transaction; snapshot guarantees validity
    await tx.document.update({
      where: { id: docId },
      data: {
        folderId: lockedFolder.id,
        version: { increment: 1 }
      }
    });
  });
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA Contextual Tuples Transaction Isolation & TOCTOU Eradication Standard

OpenFGA Contextual Tuples Transaction Isolation & TOCTOU Eradication Standard defines an industrial-grade behavioral standard for backend engineering. Mandates that ephemeral contextual tuples provided to OpenFGA authorization checks are strictly derived from and bound to transactional database snapshots (or locked rows). This eradicates Time-of-Check to Time-of-Use (TOCTOU) authorization vulnerabilities where parent reassignment, tenancy migration, or ownership transfer occurs concurrently between check evaluation and database 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: Evaluating Ephemeral Contextual Tuples from Unlocked or Pre-Transaction Cache Prior to 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 DriftEvaluating Ephemeral Contextual Tuples from Unlocked or Pre-Transaction Cache Prior to 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 fetch the state used to construct contextual tuples within an active transactional read snapshot or with pessimistic locks (`SELECT ... FOR UPDATE` or `REPEATABLE READ`) when an authorized mutation follows.

Engineers MUST ALWAYS fetch the state used to construct contextual tuples within an active transactional read snapshot or with pessimistic locks (`SELECT ... FOR UPDATE` or `REPEATABLE READ`) when an authorized mutation follows.

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 evaluate OpenFGA checks using cached or client-provided contextual tuples without re-verifying those tuples against the transactional store inside the mutating transaction.

Engineers MUST NOT evaluate OpenFGA checks using cached or client-provided contextual tuples without re-verifying those tuples against the transactional store inside the mutating transaction.

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 MUST rollback the surrounding database transaction immediately if an OpenFGA contextual tuple check evaluates to `allowed

Code MUST rollback the surrounding database transaction immediately if an OpenFGA contextual tuple check evaluates to `allowed: false`.

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 verify version stamps or lock counters on all entities represented in contextual tuples when using Optimistic Concurrency Control (OCC) to guarantee the entity state did not mutate between authorization and write execution.

Services MUST verify version stamps or lock counters on all entities represented in contextual tuples when using Optimistic Concurrency Control (OCC) to guarantee the entity state did not mutate between authorization and write execution.

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 issue non-transactional database updates based on authorization checks executed prior to acquiring record locks for dynamic hierarchical relations (e.g., moving a document across workspace boundaries).

Components NEVER issue non-transactional database updates based on authorization checks executed prior to acquiring record locks for dynamic hierarchical relations (e.g., moving a document across workspace boundaries).

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 Contextual Tuples Transaction Isolation & TOCTOU Eradication Standard critical for AI coding assistants?

Mandates that ephemeral contextual tuples provided to OpenFGA authorization checks are strictly derived from and bound to transactional database snapshots (or locked rows). This eradicates Time-of-Check to Time-of-Use (TOCTOU) authorization vulnerabilities where parent reassignment, tenancy migration, or ownership transfer occurs concurrently between check evaluation and database 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 (Evaluating Ephemeral Contextual Tuples from Unlocked or Pre-Transaction Cache Prior to 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