This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: openfga-recursion-hop-limit-boundary-guardrail

OpenFGA Relationship Tuple Recursion and Hop-Limit Boundary Guardrail

Enforces strict pre-write cycle detection, depth-bounding heuristics, and fail-closed resolution boundaries on fine-grained authorization graphs. Transitive relation expansions (e.g., nested groups, parent-child hierarchies) without bounded hop limits expose the authorization engine to algorithmic complexity attacks, memory exhaustion, and denial-of-service during Check and Expand API resolutions.

Prohibited Anti-Pattern: Unbounded Graph Traversals and Cyclic Tuple Ingestion Triggering Authorization Engine DoS

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Relationship Tuple Recursion and Hop-Limit Boundary Guardrail - Enforces strict pre-write cycle detection, depth-bounding heuristics, and fail-closed resolution boundaries on fine-grained authorization graphs. Transitive relation expansions (e.g., nested groups, parent-child hierarchies) without bounded hop limits expose the authorization engine to algorithmic complexity attacks, memory exhaustion, and denial-of-service during Check and Expand API resolutions.
globs: src/auth/**/*.{ts,js,py,go}, src/services/**/*.{ts,js,py,go}, models/**/*.fga, **/*fga*.{json,yaml,yml}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-recursion-hop-limit-boundary-guardrail"
---

# OpenFGA Relationship Tuple Recursion and Hop-Limit Boundary Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded Graph Traversals and Cyclic Tuple Ingestion Triggering Authorization Engine DoS

## System Constraints
You are a Principal Engineer enforcing OpenFGA Relationship Tuple Recursion & Hop-Limit Boundary Guardrail. Mandate pre-commit cycle detection, explicit hop-depth limits on hierarchical writes, and strict fail-closed handling on resolution boundary limits.

## Strict Guidelines
- Engineers MUST ALWAYS validate potential cycles (e.g., via targeted cycle-detection traversal or depth validation) prior to committing transitive or hierarchical relationship tuples to OpenFGA.
- Engineers MUST NOT write relationship tuples that form a self-referential or mutually referential transitive path (e.g., parent:folder:A -> parent:folder:B -> parent:folder:A).
- Code MUST set an explicit application-layer hop limit (maximum recursion depth, e.g., max 15 hops) on hierarchical ingestion to avoid triggering OpenFGA max-resolution-depth errors (e.g., FGA error code 2004 / resolution_depth_exceeded).
- Services MUST implement fail-closed error handling when OpenFGA client returns cycle detection or depth boundary violations during Check, Expand, or ListObjects operations.
- Components NEVER assume OpenFGA server-side depth caps are sufficient protection against tenant-level resource exhaustion; defense-in-depth pre-checks are mandatory.

## Bad vs Good Implementations
### Hierarchical Tuple Ingestion with Pre-Write Cycle & Depth Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly persisting parent-child relationships into OpenFGA without graph validation permits cyclic edges and unconstrained graph depth. When OpenFGA resolves permissions transitively, it incurs severe latency, triggers max depth limits, or crashes authorization resolution paths across all tenants sharing the store.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

export async function addFolderParent(
  fgaClient: OpenFgaClient,
  childFolderId: string,
  parentFolderId: string
): Promise<void> {
  // VULNERABILITY: Blindly writing nested hierarchy allows cyclic
  // references (A -> B -> A) or excessive graph depth, causing
  // OpenFGA Check operations to spin and fail with DoS/resolution limits.
  await fgaClient.write({
    writes: [{
      user: `folder:${parentFolderId}`,
      relation: 'parent',
      object: `folder:${childFolderId}`
    }]
  });
}
```

#### Production Standard (Correct)
> **Standard**: Implements an explicit pre-write cycle validation check, validates current tree depth against a hard boundary (MAX_HIERARCHY_DEPTH = 15), rejects trivial self-references, and traps depth-exceeded errors with strict fail-closed error handling to prevent graph DoS.
```typescript
import { OpenFgaClient, FgaApiResolutionDepthExceededError } from '@openfga/sdk';

const MAX_HIERARCHY_DEPTH = 15;

export async function addFolderParent(
  fgaClient: OpenFgaClient,
  childFolderId: string,
  parentFolderId: string
): Promise<void> {
  if (childFolderId === parentFolderId) {
    throw new Error('Self-referential parent assignment detected; operation aborted.');
  }

  // 1. Compile-time / Pre-write cycle check: verify that parentFolderId is not already a descendant of childFolderId
  const isDescendant = await fgaClient.check({
    user: `folder:${parentFolderId}`,
    relation: 'parent',
    object: `folder:${childFolderId}`,
    contextualTuples: []
  });

  if (isDescendant.allowed) {
    throw new Error(`Cycle detected: folder:${parentFolderId} is already a descendant of folder:${childFolderId}`);
  }

  // 2. Transitive depth bound validation: verify hierarchy does not exceed safety limits
  const expandResult = await fgaClient.expand({
    relation: 'parent',
    object: `folder:${parentFolderId}`
  });

  const calculateDepth = (tree: any, currentDepth = 0): number => {
    if (!tree?.nodes || tree.nodes.length === 0) return currentDepth;
    if (currentDepth >= MAX_HIERARCHY_DEPTH) return currentDepth;
    return Math.max(...tree.nodes.map((node: any) => calculateDepth(node, currentDepth + 1)));
  };

  if (calculateDepth(expandResult.tree) >= MAX_HIERARCHY_DEPTH) {
    throw new Error(`Hierarchy exceeds maximum permitted traversal depth of ${MAX_HIERARCHY_DEPTH}`);
  }

  // 3. Commit tuple with fail-closed error boundaries
  try {
    await fgaClient.write({
      writes: [{
        user: `folder:${parentFolderId}`,
        relation: 'parent',
        object: `folder:${childFolderId}`
      }]
    });
  } catch (error) {
    if (error instanceof FgaApiResolutionDepthExceededError) {
      throw new Error('Authorization boundary exceeded: graph depth limit breached during write.');
    }
    throw error;
  }
}
```

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 Relationship Tuple Recursion and Hop-Limit Boundary Guardrail

OpenFGA Relationship Tuple Recursion and Hop-Limit Boundary Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces strict pre-write cycle detection, depth-bounding heuristics, and fail-closed resolution boundaries on fine-grained authorization graphs. Transitive relation expansions (e.g., nested groups, parent-child hierarchies) without bounded hop limits expose the authorization engine to algorithmic complexity attacks, memory exhaustion, and denial-of-service during Check and Expand API resolutions. 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 Graph Traversals and Cyclic Tuple Ingestion Triggering Authorization Engine DoS 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 Graph Traversals and Cyclic Tuple Ingestion Triggering Authorization Engine DoSCritical
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 potential cycles (e.g., via targeted cycle-detection traversal or depth validation) prior to committing transitive or hierarchical relationship tuples to OpenFGA.

Engineers MUST ALWAYS validate potential cycles (e.g., via targeted cycle-detection traversal or depth validation) prior to committing transitive or hierarchical 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.
2

Engineers MUST NOT write relationship tuples that form a self-referential or mutually referential transitive path (e.g., parent

Engineers MUST NOT write relationship tuples that form a self-referential or mutually referential transitive path (e.g., parent:folder:A -> parent:folder:B -> parent:folder:A).

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 set an explicit application-layer hop limit (maximum recursion depth, e.g., max 15 hops) on hierarchical ingestion to avoid triggering OpenFGA max-resolution-depth errors (e.g., FGA error code 2004 / resolution_depth_exceeded).

Code MUST set an explicit application-layer hop limit (maximum recursion depth, e.g., max 15 hops) on hierarchical ingestion to avoid triggering OpenFGA max-resolution-depth errors (e.g., FGA error code 2004 / resolution_depth_exceeded).

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 implement fail-closed error handling when OpenFGA client returns cycle detection or depth boundary violations during Check, Expand, or ListObjects operations.

Services MUST implement fail-closed error handling when OpenFGA client returns cycle detection or depth boundary violations during Check, Expand, or ListObjects operations.

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 OpenFGA server-side depth caps are sufficient protection against tenant-level resource exhaustion

Components NEVER assume OpenFGA server-side depth caps are sufficient protection against tenant-level resource exhaustion; defense-in-depth pre-checks are mandatory.

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 Relationship Tuple Recursion and Hop-Limit Boundary Guardrail critical for AI coding assistants?

Enforces strict pre-write cycle detection, depth-bounding heuristics, and fail-closed resolution boundaries on fine-grained authorization graphs. Transitive relation expansions (e.g., nested groups, parent-child hierarchies) without bounded hop limits expose the authorization engine to algorithmic complexity attacks, memory exhaustion, and denial-of-service during Check and Expand API resolutions. 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 Graph Traversals and Cyclic Tuple Ingestion Triggering Authorization Engine DoS) 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