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

OpenFGA Graph Traversal Max-Depth and Cycle-Breaking Guardrail

Enforces strict recursion depth constraints, pre-commit cycle detection, and bounded latency barriers during OpenFGA relationship tuple resolution. Prevents algorithmic denial-of-service (DoS) and thread exhaustion caused by cyclic or deeply nested relationship graphs during authorization checks.

Prohibited Anti-Pattern: Unbounded Recursive Tuple Commit Leading to Cycle-Induced Resolution Hangs

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Graph Traversal Max-Depth and Cycle-Breaking Guardrail - Enforces strict recursion depth constraints, pre-commit cycle detection, and bounded latency barriers during OpenFGA relationship tuple resolution. Prevents algorithmic denial-of-service (DoS) and thread exhaustion caused by cyclic or deeply nested relationship graphs during authorization checks.
globs: src/auth/**/*.{ts,js,py,go}, src/services/authorization/**/*.{ts,js,py,go}, src/fga/**/*.{ts,js,py,go}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-hierarchical-graph-max-depth-guardrail"
---

# OpenFGA Graph Traversal Max-Depth and Cycle-Breaking Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded Recursive Tuple Commit Leading to Cycle-Induced Resolution Hangs

## System Constraints
You are a Principal Engineer and Security Architect enforcing deterministic graph traversal limits and cycle mitigation in OpenFGA relationship-based access control (ReBAC). You must strictly reject unbounded recursive definitions, mandate cycle pre-checks before committing hierarchy tuples, and enforce query execution deadlines with resolution node caps.

## Strict Guidelines
- Engineers MUST ALWAYS enforce pre-commit cycle detection using depth-first search (DFS) or directed acyclic graph (DAG) topological validation before persisting parent-child, group-membership, or folder-inheritance tuples to OpenFGA.
- Engineers MUST NOT allow OpenFGA check, expand, or list-objects operations to execute without a hard bounded timeout (e.g., maximum 200ms) enforced via an AbortController or context deadline.
- Services MUST configure OpenFGA server-level query resolution caps (e.g., `resolve_node_limit` ≤ 25, `resolve_node_breadth_limit` ≤ 100) or specify contextual limits per evaluation request.
- Code SHOULD enforce client-side or domain-level hierarchy depth ceilings (max depth ≤ 15) when building hierarchical or recursive relationship trees.
- Components NEVER execute raw OpenFGA `check` calls in high-throughput critical paths without handling circular reference errors or depth-exhaustion exceptions gracefully.

## Bad vs Good Implementations
### Unbounded Hierarchy Tuple Insertion and Unconstrained Check

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The code blindly inserts transitive relationship edges without verifying whether the new edge introduces a cycle into the folder hierarchy. Furthermore, the check evaluation executes without an AbortController timeout, leaving the application vulnerable to latency degradation and thread exhaustion under adversarial graph structures.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

// ANTI-PATTERN: Directly inserts hierarchical relationship without cycle validation.
// If folder:B is already an ancestor of folder:A, this creates an infinite loop or graph explosion.
export async function assignParentFolder(childFolderId: string, parentFolderId: string): Promise<void> {
  await fgaClient.write({
    writes: [
      {
        user: `folder:${parentFolderId}`,
        relation: 'parent',
        object: `folder:${childFolderId}`,
      },
    ],
  });
}

// ANTI-PATTERN: Query executed with no client timeout or error handling for resolution caps.
export async function canAccessFolder(userId: string, folderId: string): Promise<boolean> {
  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'viewer',
    object: `folder:${folderId}`,
  });
  return !!response.allowed;
}
```

#### Production Standard (Correct)
> **Standard**: The improved code prevents cyclic dependency chains before persistence using depth-bounded validation, applies a non-negotiable 250ms AbortController timeout to authorization checks, and fails closed when resolution node limits or timeouts are encountered.
```typescript
import { OpenFgaClient, FgaApiResolutionNodeLimitExceededError } 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 = 250;

/**
 * Validates that adding an edge parent -> child does not introduce a cycle
 * and does not exceed the maximum allowed depth.
 */
async function assertAcyclicWithBoundedDepth(
  childId: string,
  newParentId: string,
  currentDepth = 0
): Promise<void> {
  if (childId === newParentId) {
    throw new Error('Cycle detected: Self-referential hierarchy edge is forbidden.');
  }
  if (currentDepth > MAX_HIERARCHY_DEPTH) {
    throw new Error(`Graph hierarchy depth limit (${MAX_HIERARCHY_DEPTH}) exceeded.`);
  }

  // Check if childId is already an ancestor of newParentId
  const isAncestor = await fgaClient.check({
    user: `folder:${childId}`,
    relation: 'parent',
    object: `folder:${newParentId}`,
  });

  if (isAncestor.allowed) {
    throw new Error(`Cycle detected: folder:${childId} is already an ancestor of folder:${newParentId}.`);
  }
}

export async function assignParentFolder(childFolderId: string, parentFolderId: string): Promise<void> {
  await assertAcyclicWithBoundedDepth(childFolderId, parentFolderId);

  await fgaClient.write({
    writes: [
      {
        user: `folder:${parentFolderId}`,
        relation: 'parent',
        object: `folder:${childFolderId}`,
      },
    ],
  });
}

export async function canAccessFolder(userId: string, folderId: string): Promise<boolean> {
  const controller = new AbortController();
  const timeoutId = 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;
  } catch (error: unknown) {
    if (error instanceof FgaApiResolutionNodeLimitExceededError) {
      console.error(`Authorization resolution limit exceeded for folder:${folderId}`, error);
      return false; // Fail closed
    }
    if (error instanceof Error && error.name === 'AbortError') {
      console.error(`Authorization query timed out after ${CHECK_TIMEOUT_MS}ms for folder:${folderId}`);
      return false; // Fail closed
    }
    throw error;
  } finally {
    clearTimeout(timeoutId);
  }
}
```

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 Graph Traversal Max-Depth and Cycle-Breaking Guardrail

OpenFGA Graph Traversal Max-Depth and Cycle-Breaking Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces strict recursion depth constraints, pre-commit cycle detection, and bounded latency barriers during OpenFGA relationship tuple resolution. Prevents algorithmic denial-of-service (DoS) and thread exhaustion caused by cyclic or deeply nested relationship graphs during authorization checks. 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: Unbounded Recursive Tuple Commit Leading to Cycle-Induced Resolution Hangs 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 DriftUnbounded Recursive Tuple Commit Leading to Cycle-Induced Resolution HangsCritical
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 enforce pre-commit cycle detection using depth-first search (DFS) or directed acyclic graph (DAG) topological validation before persisting parent-child, group-membership, or folder-inheritance tuples to OpenFGA.

Engineers MUST ALWAYS enforce pre-commit cycle detection using depth-first search (DFS) or directed acyclic graph (DAG) topological validation before persisting parent-child, group-membership, or folder-inheritance 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.
2

Engineers MUST NOT allow OpenFGA check, expand, or list-objects operations to execute without a hard bounded timeout (e.g., maximum 200ms) enforced via an AbortController or context deadline.

Engineers MUST NOT allow OpenFGA check, expand, or list-objects operations to execute without a hard bounded timeout (e.g., maximum 200ms) enforced via an AbortController or context deadline.

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 configure OpenFGA server-level query resolution caps (e.g., `resolve_node_limit` ≤ 25, `resolve_node_breadth_limit` ≤ 100) or specify contextual limits per evaluation request.

Services MUST configure OpenFGA server-level query resolution caps (e.g., `resolve_node_limit` ≤ 25, `resolve_node_breadth_limit` ≤ 100) or specify contextual limits per evaluation request.

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

Code SHOULD enforce client-side or domain-level hierarchy depth ceilings (max depth ≤ 15) when building hierarchical or recursive relationship trees.

Code SHOULD enforce client-side or domain-level hierarchy depth ceilings (max depth ≤ 15) when building hierarchical or recursive relationship trees.

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 execute raw OpenFGA `check` calls in high-throughput critical paths without handling circular reference errors or depth-exhaustion exceptions gracefully.

Components NEVER execute raw OpenFGA `check` calls in high-throughput critical paths without handling circular reference errors or depth-exhaustion exceptions gracefully.

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 Graph Traversal Max-Depth and Cycle-Breaking Guardrail critical for AI coding assistants?

Enforces strict recursion depth constraints, pre-commit cycle detection, and bounded latency barriers during OpenFGA relationship tuple resolution. Prevents algorithmic denial-of-service (DoS) and thread exhaustion caused by cyclic or deeply nested relationship graphs during authorization checks. 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 (Unbounded Recursive Tuple Commit Leading to Cycle-Induced Resolution Hangs) 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