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

OpenFGA Conditional Relationship Tuple & Transaction Isolation Standard

Enforces atomic batch mutations and deterministic conditional evaluation for OpenFGA authorization tuples. Prevents transient privilege escalation, authorization bypass, and Time-of-Check to Time-of-Use (TOCTOU) exploits caused by eventual consistency lag and non-atomic state synchronization between primary persistence layers and the Fine-Grained Authorization engine.

Prohibited Anti-Pattern: Non-Atomic Sequential Tuple Writes and Unbounded Ephemeral State Injection Inducing Authorization Desynchronization

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Conditional Relationship Tuple & Transaction Isolation Standard - Enforces atomic batch mutations and deterministic conditional evaluation for OpenFGA authorization tuples. Prevents transient privilege escalation, authorization bypass, and Time-of-Check to Time-of-Use (TOCTOU) exploits caused by eventual consistency lag and non-atomic state synchronization between primary persistence layers and the Fine-Grained Authorization engine.
globs: src/auth/**/*.{ts,tsx}, src/services/auth/**/*.{ts,tsx}, src/lib/fga/**/*.{ts,tsx}, src/middleware/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-conditional-tuple-transaction-isolation-standard"
---

# OpenFGA Conditional Relationship Tuple & Transaction Isolation Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Non-Atomic Sequential Tuple Writes and Unbounded Ephemeral State Injection Inducing Authorization Desynchronization

## System Constraints
You are a Principal Security Architect enforcing the OpenFGA Conditional Relationship Tuple & Transaction Isolation Standard. You must reject any OpenFGA mutation implementation that executes sequential or non-atomic write/delete operations across separate network requests. Mandate that all role migrations and contextual access modifications use OpenFGA's atomic write-and-delete payload batching. Ensure all dynamic authorization factors (e.g., temporal constraints, IP subnet boundaries, resource claim limits) are evaluated through compiled Common Expression Language (CEL) conditions or ephemeral contextual tuples at Check time, rather than volatile persistent tuples.

## Strict Guidelines
- Engineers MUST ALWAYS execute tuple modifications and role revocations within a single atomic OpenFGA Client write call containing both `writes` and `deletes` arrays.
- Engineers MUST NOT execute sequential `client.write()` calls to rotate or replace permissions, as this creates transient privilege gaps or accidental escalation windows.
- Services MUST synchronize database state transitions and OpenFGA tuple mutations using an Idempotent Transactional Outbox pattern or two-phase reconciliation with compensating rollbacks.
- Engineers MUST evaluate highly volatile, request-bound contexts (e.g., current timestamp, client IP, device trust score) via OpenFGA Conditional Tuples or contextual tuples directly inside the `check` call rather than writing transient persistent tuples.
- All OpenFGA CEL conditions MUST specify strictly typed, validated schemas and MUST NOT depend on non-deterministic external calls or ambient system clocks within the condition body.
- Contextual tuples provided to `client.check()` MUST NOT conflict with persisted authority tuples; they MUST augment query evaluation strictly for the lifespan of the active execution context.

## Bad vs Good Implementations
### Atomic Role Swap and Conditional Access vs Non-Atomic Sequential Calls

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Executing writes and deletes as separate API operations creates a distributed race condition and non-atomic isolation failure. If the second request fails or experiences latency, both users hold owner privileges, or unauthorized concurrent operations can succeed during the desynchronization window.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

export async function transferOwnership(
  fgaClient: OpenFgaClient,
  organizationId: string,
  previousOwnerId: string,
  newOwnerId: string
): Promise<void> {
  // VULNERABLE: Non-atomic sequential writes induce a transient state where both users
  // hold ownership simultaneously or, upon failure of the second call, zero owners exist.
  await fgaClient.write({
    writes: [
      {
        user: `user:${newOwnerId}`,
        relation: 'owner',
        object: `organization:${organizationId}`
      }
    ]
  });

  // If network fails here, both users remain owner (Privilege Duplication)
  await fgaClient.write({
    deletes: [
      {
        user: `user:${previousOwnerId}`,
        relation: 'owner',
        object: `organization:${organizationId}`
      }
    ]
  });
}
```

#### Production Standard (Correct)
> **Standard**: Bundling the write and delete operations into a single `client.write()` payload guarantees serializable atomicity inside OpenFGA. Either both operations succeed or both fail, preventing split-brain privilege assignment. Conditional attributes further restrict access validity based on verified context.
```typescript
import { OpenFgaClient, ClientWriteRequest } from '@openfga/sdk';

export interface OwnershipTransferContext {
  organizationId: string;
  previousOwnerId: string;
  newOwnerId: string;
  allowedIpSubnet: string;
  sessionTimestamp: string;
}

export async function transferOwnershipAtomic(
  fgaClient: OpenFgaClient,
  context: OwnershipTransferContext
): Promise<void> {
  // SECURE: Atomic write and delete executed in a single transaction payload.
  // Leverages a CEL condition for contextual validation to prevent TOCTOU exploitation.
  const payload: ClientWriteRequest = {
    writes: [
      {
        user: `user:${context.newOwnerId}`,
        relation: 'owner',
        object: `organization:${context.organizationId}`,
        condition: {
          name: 'ip_and_temporal_guard',
          context: {
            client_ip: context.allowedIpSubnet,
            grant_timestamp: context.sessionTimestamp
          }
        }
      }
    ],
    deletes: [
      {
        user: `user:${context.previousOwnerId}`,
        relation: 'owner',
        object: `organization:${context.organizationId}`
      }
    ]
  };

  // OpenFGA guarantees atomic commit of both operations within the storage engine
  await fgaClient.write(payload, {
    transaction: {
      disableOrderBy: false
    }
  });
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA Conditional Relationship Tuple & Transaction Isolation Standard

OpenFGA Conditional Relationship Tuple & Transaction Isolation Standard defines an industrial-grade behavioral standard for security engineering. Enforces atomic batch mutations and deterministic conditional evaluation for OpenFGA authorization tuples. Prevents transient privilege escalation, authorization bypass, and Time-of-Check to Time-of-Use (TOCTOU) exploits caused by eventual consistency lag and non-atomic state synchronization between primary persistence layers and the Fine-Grained Authorization engine. 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: Non-Atomic Sequential Tuple Writes and Unbounded Ephemeral State Injection Inducing Authorization Desynchronization 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 DriftNon-Atomic Sequential Tuple Writes and Unbounded Ephemeral State Injection Inducing Authorization DesynchronizationCritical
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 execute tuple modifications and role revocations within a single atomic OpenFGA Client write call containing both `writes` and `deletes` arrays.

Engineers MUST ALWAYS execute tuple modifications and role revocations within a single atomic OpenFGA Client write call containing both `writes` and `deletes` arrays.

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 sequential `client.write()` calls to rotate or replace permissions, as this creates transient privilege gaps or accidental escalation windows.

Engineers MUST NOT execute sequential `client.write()` calls to rotate or replace permissions, as this creates transient privilege gaps or accidental escalation windows.

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

Services MUST synchronize database state transitions and OpenFGA tuple mutations using an Idempotent Transactional Outbox pattern or two-phase reconciliation with compensating rollbacks.

Services MUST synchronize database state transitions and OpenFGA tuple mutations using an Idempotent Transactional Outbox pattern or two-phase reconciliation with compensating rollbacks.

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

Engineers MUST evaluate highly volatile, request-bound contexts (e.g., current timestamp, client IP, device trust score) via OpenFGA Conditional Tuples or contextual tuples directly inside the `check` call rather than writing transient persistent tuples.

Engineers MUST evaluate highly volatile, request-bound contexts (e.g., current timestamp, client IP, device trust score) via OpenFGA Conditional Tuples or contextual tuples directly inside the `check` call rather than writing transient persistent tuples.

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

All OpenFGA CEL conditions MUST specify strictly typed, validated schemas and MUST NOT depend on non-deterministic external calls or ambient system clocks within the condition body.

All OpenFGA CEL conditions MUST specify strictly typed, validated schemas and MUST NOT depend on non-deterministic external calls or ambient system clocks within the condition body.

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.
6

Contextual tuples provided to `client.check()` MUST NOT conflict with persisted authority tuples

Contextual tuples provided to `client.check()` MUST NOT conflict with persisted authority tuples; they MUST augment query evaluation strictly for the lifespan of the active 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is OpenFGA Conditional Relationship Tuple & Transaction Isolation Standard critical for AI coding assistants?

Enforces atomic batch mutations and deterministic conditional evaluation for OpenFGA authorization tuples. Prevents transient privilege escalation, authorization bypass, and Time-of-Check to Time-of-Use (TOCTOU) exploits caused by eventual consistency lag and non-atomic state synchronization between primary persistence layers and the Fine-Grained Authorization engine. 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 (Non-Atomic Sequential Tuple Writes and Unbounded Ephemeral State Injection Inducing Authorization Desynchronization) 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