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

Atomic Evaluation of Contextual Tuples in OpenFGA Boundaries

Enforces strict isolation and atomicity for ephemeral authorization states by mandating that request-scoped context attributes are passed solely via contextual tuples within a single Check or ListObjects evaluation cycle. Prevents split-brain authorization anomalies, race conditions, and persistent relationship contamination caused by writing temporary tuples to the OpenFGA datastore.

Prohibited Anti-Pattern: Persisting Ephemeral Tuples or Splitting Contextual Checks Across Multiple Roundtrips

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Atomic Evaluation of Contextual Tuples in OpenFGA Boundaries - Enforces strict isolation and atomicity for ephemeral authorization states by mandating that request-scoped context attributes are passed solely via contextual tuples within a single Check or ListObjects evaluation cycle. Prevents split-brain authorization anomalies, race conditions, and persistent relationship contamination caused by writing temporary tuples to the OpenFGA datastore.
globs: src/**/auth/**/*.{ts,js,py,go}, src/**/authz/**/*.{ts,js,py,go}, src/**/permissions/**/*.{ts,js,py,go}, src/**/middleware/**/*.{ts,js,py,go}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuple-transaction-boundary"
---

# Atomic Evaluation of Contextual Tuples in OpenFGA Boundaries

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Persisting Ephemeral Tuples or Splitting Contextual Checks Across Multiple Roundtrips

## System Constraints
You are a Principal Security Architect enforcing transactional authorization boundaries in OpenFGA. You must ensure that dynamic, request-scoped facts (e.g., dynamic tenancy, IP location, device posture, time-based delegation) are never persisted into the relationship graph store and are never decoupled from the core authorization check. You must mandate atomic evaluation using contextual tuples directly within the Check payload.

## Strict Guidelines
- Engineers MUST ALWAYS supply ephemeral or request-scoped relations via the `contextualTuples` field in a single `fgaClient.check()` or `fgaClient.listObjects()` call.
- Engineers MUST NOT write ephemeral or temporary authorization tuples into the persistent OpenFGA relationship store via `writeTuples` followed by asynchronous cleanup.
- Services MUST NOT execute multi-phase authorization where static graph relationships and dynamic context checks are performed as disconnected application queries.
- Engineers MUST validate the format, boundary, and origin of all runtime assertions before mapping them into contextual tuples to prevent injection of forged relation paths.
- Authorization middleware MUST treat contextual tuples as strictly ephemeral: their lifecycle MUST terminate concurrently with the completion of the individual OpenFGA evaluation call.

## Bad vs Good Implementations
### Contextual Tuple Invariant Enforcement in OpenFGA Check

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Persisting request-scoped state using write() introduces write amplification, datastore pollution on process crashes, and severe race conditions between concurrent requests for the same user.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

export async function authorizeDocumentAccess(
  fgaClient: OpenFgaClient,
  userId: string,
  documentId: string,
  departmentId: string
): Promise<boolean> {
  // ANTI-PATTERN: Writing ephemeral state to persistent storage,
  // causing race conditions, split-brain state, and dangling tuples on crash.
  await fgaClient.write({
    writes: [{
      user: `user:${userId}`,
      relation: 'ephemeral_department_member',
      object: `department:${departmentId}`
    }]
  });

  const { allowed } = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'can_view',
    object: `document:${documentId}`
  });

  // Cleanup failure here causes permanent privilege escalation
  await fgaClient.write({
    deletes: [{
      user: `user:${userId}`,
      relation: 'ephemeral_department_member',
      object: `department:${departmentId}`
    }]
  });

  return allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: Contextual tuples are evaluated in-memory within OpenFGA alongside the persistent graph for the single transaction cycle, guaranteeing zero state leakage, zero dangling tuples, and zero race conditions.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

export async function authorizeDocumentAccess(
  fgaClient: OpenFgaClient,
  userId: string,
  documentId: string,
  departmentId: string
): Promise<boolean> {
  // PRODUCTION INVARIANT: Inject ephemeral context atomically into the check payload.
  // Contextual tuples exist only within the evaluation cycle of this single request.
  const checkPayload: ClientCheckRequest = {
    user: `user:${userId}`,
    relation: 'can_view',
    object: `document:${documentId}`,
    contextualTuples: [
      {
        user: `user:${userId}`,
        relation: 'ephemeral_department_member',
        object: `department:${departmentId}`
      }
    ]
  };

  const response = await fgaClient.check(checkPayload);
  return response.allowed ?? false;
}
```

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: Atomic Evaluation of Contextual Tuples in OpenFGA Boundaries

Atomic Evaluation of Contextual Tuples in OpenFGA Boundaries defines an industrial-grade behavioral standard for security engineering. Enforces strict isolation and atomicity for ephemeral authorization states by mandating that request-scoped context attributes are passed solely via contextual tuples within a single Check or ListObjects evaluation cycle. Prevents split-brain authorization anomalies, race conditions, and persistent relationship contamination caused by writing temporary tuples to the OpenFGA datastore. 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: Persisting Ephemeral Tuples or Splitting Contextual Checks Across Multiple Roundtrips 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 DriftPersisting Ephemeral Tuples or Splitting Contextual Checks Across Multiple RoundtripsCritical
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 supply ephemeral or request-scoped relations via the `contextualTuples` field in a single `fgaClient.check()` or `fgaClient.listObjects()` call.

Engineers MUST ALWAYS supply ephemeral or request-scoped relations via the `contextualTuples` field in a single `fgaClient.check()` or `fgaClient.listObjects()` call.

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 write ephemeral or temporary authorization tuples into the persistent OpenFGA relationship store via `writeTuples` followed by asynchronous cleanup.

Engineers MUST NOT write ephemeral or temporary authorization tuples into the persistent OpenFGA relationship store via `writeTuples` followed by asynchronous cleanup.

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 NOT execute multi-phase authorization where static graph relationships and dynamic context checks are performed as disconnected application queries.

Services MUST NOT execute multi-phase authorization where static graph relationships and dynamic context checks are performed as disconnected application queries.

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 validate the format, boundary, and origin of all runtime assertions before mapping them into contextual tuples to prevent injection of forged relation paths.

Engineers MUST validate the format, boundary, and origin of all runtime assertions before mapping them into contextual tuples to prevent injection of forged relation paths.

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

Authorization middleware MUST treat contextual tuples as strictly ephemeral

Authorization middleware MUST treat contextual tuples as strictly ephemeral: their lifecycle MUST terminate concurrently with the completion of the individual OpenFGA evaluation call.

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 Atomic Evaluation of Contextual Tuples in OpenFGA Boundaries critical for AI coding assistants?

Enforces strict isolation and atomicity for ephemeral authorization states by mandating that request-scoped context attributes are passed solely via contextual tuples within a single Check or ListObjects evaluation cycle. Prevents split-brain authorization anomalies, race conditions, and persistent relationship contamination caused by writing temporary tuples to the OpenFGA datastore. 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 (Persisting Ephemeral Tuples or Splitting Contextual Checks Across Multiple Roundtrips) 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

Atomic