This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: openfga-graph-cycle-depth-limit-invariant

OpenFGA 1.6+ Tuple-To-Userset Graph Cycle and Depth Limit Invariant

Deeply nested ReBAC relationship evaluations over tuple-to-userset (TTU) chains must enforce strict acyclic invariants and deterministic graph traversal boundaries. Failure to validate DAG properties at tuple ingestion and unconstrained recursive evaluations lead to CPU exhaustion, authorization timeouts, and Denial-of-Service (DoS) in critical path authorization checks. Systems must enforce proactive cycle prevention at mutation time and explicit bounded depth guardrails during evaluation.

Prohibited Anti-Pattern: Unvalidated Cyclic TTU Relationship Ingestion Causing Authorization Engine Starvation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA 1.6+ Tuple-To-Userset Graph Cycle and Depth Limit Invariant - Deeply nested ReBAC relationship evaluations over tuple-to-userset (TTU) chains must enforce strict acyclic invariants and deterministic graph traversal boundaries. Failure to validate DAG properties at tuple ingestion and unconstrained recursive evaluations lead to CPU exhaustion, authorization timeouts, and Denial-of-Service (DoS) in critical path authorization checks. Systems must enforce proactive cycle prevention at mutation time and explicit bounded depth guardrails during evaluation.
globs: src/**/authz/**/*.{ts,js,go,py}, src/**/permissions/**/*.{ts,js,go,py}, src/**/services/auth*/**/*.{ts,js,go,py}, **/model.fga, **/fga.mod
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-graph-cycle-depth-limit-invariant"
---

# OpenFGA 1.6+ Tuple-To-Userset Graph Cycle and Depth Limit Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unvalidated Cyclic TTU Relationship Ingestion Causing Authorization Engine Starvation

## System Constraints
You are a Principal Software Architect enforcing OpenFGA 1.6+ Tuple-To-Userset Graph Cycle & Depth Limit Invariants. You must ensure that all ReBAC models, relation tuple ingestion pipelines, and authorization client checks enforce strictly bounded recursion depths and eliminate cyclic relationship paths. Reject any tuple ingestion that writes hierarchical relations without pre-flight cycle validation, and forbid unbounded contextual check queries.

## Strict Guidelines
- Engineers MUST ALWAYS validate DAG (Directed Acyclic Graph) invariants before persisting transitive or self-referential relationship tuples (e.g., parent-child hierarchies or group nesting).
- Engineers MUST NOT rely exclusively on OpenFGA engine-level depth limits as a substitute for application-level acyclic validation on tuple mutations.
- Code MUST configure explicit timeout contexts and bounded depth parameters when dispatching OpenFGA Check and Expand calls.
- Services MUST reject contextual tuples that introduce circular references between target objects and contextual parents during dynamic evaluation.
- Components NEVER allow dynamic user-defined tuple creation without transactional ancestry verification to prevent malicious authorization graph poisoning.

## Bad vs Good Implementations
### Tuple Mutation Cycle Validation and Context-Bounded Authorization Check

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad example writes hierarchical parent-child relationship tuples directly into OpenFGA without verifying whether the new edge forms a cycle. If folder A is assigned folder B as parent, while folder B already has folder A in its ancestry, this forms a cycle. Transitive tuple-to-userset (TTU) checks will traverse recursively until OpenFGA internal limits kill the request, inducing latency spikes and potential denial of service.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

const fgaClient = new OpenFgaClient({ apiUrl: process.env.FGA_API_URL! });

// ANTI-PATTERN: Direct tuple insertion allows circular dependencies (e.g., folder:A -> folder:B -> folder:A)
// Additionally, authorization checks use unbound execution without deadlines or cycle guards.
export async function assignParentFolder(folderId: string, parentFolderId: string) {
  await fgaClient.write({
    writes: [{
      user: `folder:${parentFolderId}`,
      relation: 'parent',
      object: `folder:${folderId}`,
    }],
  });
}

export async function canAccessFolder(userId: string, folderId: string): Promise<boolean> {
  // Unbounded check call vulnerable to downstream recursion exhaustion
  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'viewer',
    object: `folder:${folderId}`,
  });
  return response.allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: The good example verifies that the new relationship edge does not introduce a directed cycle prior to writing the tuple to the store. It asserts non-reflexivity (`folderId !== parentFolderId`) and executes an explicit ancestor pre-check with deterministic network timeouts. Checks enforce strict client-side abort signals to guarantee predictable p99 authorization response times.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

const fgaClient = new OpenFgaClient({
  apiUrl: process.env.FGA_API_URL!,
  storeId: process.env.FGA_STORE_ID!,
});

const MAX_HIERARCHY_DEPTH = 15;
const CHECK_TIMEOUT_MS = 800;

// PRODUCTION FIX: Pre-flight transitive reachability check to prevent cycles in TTU hierarchies
export async function assignParentFolder(folderId: string, parentFolderId: string): Promise<void> {
  if (folderId === parentFolderId) {
    throw new Error('Self-referential relation cycle detected: folder cannot be its own parent.');
  }

  // Check if target folderId is already an ancestor of parentFolderId (transitive cycle pre-validation)
  const cycleCheck = await fgaClient.check({
    user: `folder:${folderId}`,
    relation: 'parent_transitive',
    object: `folder:${parentFolderId}`,
  }, {
    requestTimeout: CHECK_TIMEOUT_MS,
  });

  if (cycleCheck.allowed) {
    throw new Error(`Cycle detected: folder:${folderId} is already an ancestor of folder:${parentFolderId}`);
  }

  // Write tuple only after DAG invariant is verified
  await fgaClient.write({
    writes: [{
      user: `folder:${parentFolderId}`,
      relation: 'parent',
      object: `folder:${folderId}`,
    }],
  }, {
    requestTimeout: CHECK_TIMEOUT_MS,
  });
}

export async function canAccessFolder(userId: string, folderId: string): Promise<boolean> {
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), CHECK_TIMEOUT_MS);

  try {
    const response = await fgaClient.check({
      user: `user:${userId}`,
      relation: 'viewer',
      object: `folder:${folderId}`,
    }, {
      signal: controller.signal,
    });
    return response.allowed ?? false;
  } finally {
    clearTimeout(timeout);
  }
}
```

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 1.6+ Tuple-To-Userset Graph Cycle and Depth Limit Invariant

OpenFGA 1.6+ Tuple-To-Userset Graph Cycle and Depth Limit Invariant defines an industrial-grade behavioral standard for security engineering. Deeply nested ReBAC relationship evaluations over tuple-to-userset (TTU) chains must enforce strict acyclic invariants and deterministic graph traversal boundaries. Failure to validate DAG properties at tuple ingestion and unconstrained recursive evaluations lead to CPU exhaustion, authorization timeouts, and Denial-of-Service (DoS) in critical path authorization checks. Systems must enforce proactive cycle prevention at mutation time and explicit bounded depth guardrails during evaluation. 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: Unvalidated Cyclic TTU Relationship Ingestion Causing Authorization Engine Starvation 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 DriftUnvalidated Cyclic TTU Relationship Ingestion Causing Authorization Engine StarvationCritical
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 validate DAG (Directed Acyclic Graph) invariants before persisting transitive or self-referential relationship tuples (e.g., parent-child hierarchies or group nesting).

Engineers MUST ALWAYS validate DAG (Directed Acyclic Graph) invariants before persisting transitive or self-referential relationship tuples (e.g., parent-child hierarchies or group nesting).

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 rely exclusively on OpenFGA engine-level depth limits as a substitute for application-level acyclic validation on tuple mutations.

Engineers MUST NOT rely exclusively on OpenFGA engine-level depth limits as a substitute for application-level acyclic validation on tuple mutations.

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 configure explicit timeout contexts and bounded depth parameters when dispatching OpenFGA Check and Expand calls.

Code MUST configure explicit timeout contexts and bounded depth parameters when dispatching OpenFGA Check and Expand calls.

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 reject contextual tuples that introduce circular references between target objects and contextual parents during dynamic evaluation.

Services MUST reject contextual tuples that introduce circular references between target objects and contextual parents during dynamic evaluation.

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 allow dynamic user-defined tuple creation without transactional ancestry verification to prevent malicious authorization graph poisoning.

Components NEVER allow dynamic user-defined tuple creation without transactional ancestry verification to prevent malicious authorization graph poisoning.

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 1.6+ Tuple-To-Userset Graph Cycle and Depth Limit Invariant critical for AI coding assistants?

Deeply nested ReBAC relationship evaluations over tuple-to-userset (TTU) chains must enforce strict acyclic invariants and deterministic graph traversal boundaries. Failure to validate DAG properties at tuple ingestion and unconstrained recursive evaluations lead to CPU exhaustion, authorization timeouts, and Denial-of-Service (DoS) in critical path authorization checks. Systems must enforce proactive cycle prevention at mutation time and explicit bounded depth guardrails during evaluation. 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 (Unvalidated Cyclic TTU Relationship Ingestion Causing Authorization Engine Starvation) 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