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

OpenFGA Atomic Conditional Tuple Mutation and Consistency Standard

Enforces atomic batch execution and strict consistency preferences for OpenFGA relationship tuple mutations involving conditional grants. Eliminates privilege escalation windows, lockouts, and authorization leaks during high-concurrency ReBAC lifecycle transitions across distributed decision points.

Prohibited Anti-Pattern: Sequential Non-Atomic Tuple Operations Causing Transient Privilege Leaks and Stale Grant Windows

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Atomic Conditional Tuple Mutation and Consistency Standard - Enforces atomic batch execution and strict consistency preferences for OpenFGA relationship tuple mutations involving conditional grants. Eliminates privilege escalation windows, lockouts, and authorization leaks during high-concurrency ReBAC lifecycle transitions across distributed decision points.
globs: src/**/authz/**/*.{ts,js}, src/**/fga/**/*.{ts,js}, src/**/services/**/*.{ts,js}, src/**/policy/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-conditional-tuple-mutation-atomicity"
---

# OpenFGA Atomic Conditional Tuple Mutation and Consistency Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Sequential Non-Atomic Tuple Operations Causing Transient Privilege Leaks and Stale Grant Windows

## System Constraints
You are a Principal Security Architect enforcing the OpenFGA Conditional Relationship Tuple Mutation Atomicity Standard. You must mandate atomic write/delete batches, explicit schema-validated condition contexts, and strong read consistency preferences to eliminate privilege leakage windows and race conditions during ReBAC state transitions.

## Strict Guidelines
- Engineers MUST ALWAYS execute relationship tuple lifecycle mutations (such as role promotions, revocations, and condition modifications) within a single atomic batch call (`client.write({ writes, deletes })`).
- Engineers MUST NOT execute split sequential API invocations (e.g., separate `deleteTuples` followed by `writeTuples`) that create transient unauthorized windows or orphan states on network partition.
- Code SHOULD enforce `ConsistencyPreference.HIGHER_CONSISTENCY` on read and check evaluations executed immediately following tuple mutations to prevent stale authorization decisions caused by storage replica lag.
- Services MUST validate all conditional expression context keys and data types using strict schemas (e.g., Zod) prior to dispatching conditional relationship tuples to OpenFGA.
- Components NEVER assume intermediate permissions are revoked or granted until the atomic batch mutation is durable and acknowledged by the OpenFGA storage engine.

## Bad vs Good Implementations
### Atomic Conditional Tuple Swap with Consistency Guarantee vs Sequential Write/Delete

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Sequential calls to `deleteTuples` and `writeTuples` lack atomicity. A network failure between calls leaves the user partially migrated, and concurrent authorization checks during execution expose a window of either privilege escalation or availability loss. Condition context is passed without validation.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

export async function transitionUserRole(
  fga: OpenFgaClient,
  userId: string,
  oldRole: string,
  newRole: string,
  orgId: string,
  ipConstraint: string
): Promise<void> {
  // VULNERABILITY: Non-atomic sequential mutation.
  // If delete succeeds but write fails, user is left in an inconsistent locked-out state.
  // If write happens first, user temporarily possesses overlapping privilege elevation.
  await fga.deleteTuples([
    { user: `user:${userId}`, relation: oldRole, object: `organization:${orgId}` }
  ]);

  // Unvalidated dynamic condition context without schema assertions
  await fga.writeTuples([
    {
      user: `user:${userId}`,
      relation: newRole,
      object: `organization:${orgId}`,
      condition: {
        name: 'ip_address_match',
        context: { client_ip: ipConstraint }
      }
    }
  ]);
}
```

#### Production Standard (Correct)
> **Standard**: Combines `writes` and `deletes` into a single atomic transactional request (`fga.write`), ensuring all-or-nothing mutation semantics. Context payloads are validated before network dispatch, and follow-up checks mandate `ConsistencyPreference.HIGHER_CONSISTENCY` to avoid replica lag anomalies.
```typescript
import { OpenFgaClient, ConsistencyPreference, ClientWriteRequest } from '@openfga/sdk';
import { z } from 'zod';

const IpConditionContextSchema = z.object({
  client_ip: z.string().ip({ version: 'v4' })
});

export async function transitionUserRole(
  fga: OpenFgaClient,
  userId: string,
  oldRole: string,
  newRole: string,
  orgId: string,
  ipConstraint: string
): Promise<void> {
  // 1. Strict schema validation of the dynamic condition payload
  const validatedContext = IpConditionContextSchema.parse({ client_ip: ipConstraint });

  // 2. Compose atomic write/delete batch into a single transactional boundary
  const mutationPayload: ClientWriteRequest = {
    writes: [
      {
        user: `user:${userId}`,
        relation: newRole,
        object: `organization:${orgId}`,
        condition: {
          name: 'ip_address_match',
          context: validatedContext
        }
      }
    ],
    deletes: [
      {
        user: `user:${userId}`,
        relation: oldRole,
        object: `organization:${orgId}`
      }
    ]
  };

  // 3. Execute atomic transaction (OpenFGA default transaction wrapper ensures all-or-nothing)
  await fga.write(mutationPayload);

  // 4. Validate state with explicit HIGHER_CONSISTENCY to bypass stale read replicas
  const verification = await fga.check({
    user: `user:${userId}`,
    relation: newRole,
    object: `organization:${orgId}`,
    context: validatedContext
  }, {
    consistency: ConsistencyPreference.HIGHER_CONSISTENCY
  });

  if (!verification.allowed) {
    throw new Error(`State verification failed post-atomic mutation for user:${userId}`);
  }
}
```

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 Atomic Conditional Tuple Mutation and Consistency Standard

OpenFGA Atomic Conditional Tuple Mutation and Consistency Standard defines an industrial-grade behavioral standard for security engineering. Enforces atomic batch execution and strict consistency preferences for OpenFGA relationship tuple mutations involving conditional grants. Eliminates privilege escalation windows, lockouts, and authorization leaks during high-concurrency ReBAC lifecycle transitions across distributed decision points. 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: Sequential Non-Atomic Tuple Operations Causing Transient Privilege Leaks and Stale Grant Windows 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 DriftSequential Non-Atomic Tuple Operations Causing Transient Privilege Leaks and Stale Grant WindowsCritical
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 relationship tuple lifecycle mutations (such as role promotions, revocations, and condition modifications) within a single atomic batch call (`client.write({ writes, deletes })`).

Engineers MUST ALWAYS execute relationship tuple lifecycle mutations (such as role promotions, revocations, and condition modifications) within a single atomic batch call (`client.write({ writes, deletes })`).

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 split sequential API invocations (e.g., separate `deleteTuples` followed by `writeTuples`) that create transient unauthorized windows or orphan states on network partition.

Engineers MUST NOT execute split sequential API invocations (e.g., separate `deleteTuples` followed by `writeTuples`) that create transient unauthorized windows or orphan states on network partition.

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 enforce `ConsistencyPreference.HIGHER_CONSISTENCY` on read and check evaluations executed immediately following tuple mutations to prevent stale authorization decisions caused by storage replica lag.

Code SHOULD enforce `ConsistencyPreference.HIGHER_CONSISTENCY` on read and check evaluations executed immediately following tuple mutations to prevent stale authorization decisions caused by storage replica lag.

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 all conditional expression context keys and data types using strict schemas (e.g., Zod) prior to dispatching conditional relationship tuples to OpenFGA.

Services MUST validate all conditional expression context keys and data types using strict schemas (e.g., Zod) prior to dispatching conditional relationship tuples to OpenFGA.

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 intermediate permissions are revoked or granted until the atomic batch mutation is durable and acknowledged by the OpenFGA storage engine.

Components NEVER assume intermediate permissions are revoked or granted until the atomic batch mutation is durable and acknowledged by the OpenFGA storage engine.

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 Atomic Conditional Tuple Mutation and Consistency Standard critical for AI coding assistants?

Enforces atomic batch execution and strict consistency preferences for OpenFGA relationship tuple mutations involving conditional grants. Eliminates privilege escalation windows, lockouts, and authorization leaks during high-concurrency ReBAC lifecycle transitions across distributed decision points. 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 (Sequential Non-Atomic Tuple Operations Causing Transient Privilege Leaks and Stale Grant Windows) 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