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

OpenFGA Graph Traversal Depth and Cyclic Relationship Defense Guardrail

Enforces deterministic graph evaluation limits, cycle prevention invariants, and context-bound authorization checks within OpenFGA ReBAC implementations. Eliminates denial-of-service via nested relationship loops and prevents privilege escalation caused by unbounded transitive resolutions in multi-tenant architectures. Mandates explicit graph depth constraints, tuple write DAG validation, and fail-closed fallback mechanisms.

Prohibited Anti-Pattern: Unbounded Self-Referential Hierarchy Traversal and Missing DAG Validation Causing Authorization DoS and Resolution Bypass

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Graph Traversal Depth and Cyclic Relationship Defense Guardrail - Enforces deterministic graph evaluation limits, cycle prevention invariants, and context-bound authorization checks within OpenFGA ReBAC implementations. Eliminates denial-of-service via nested relationship loops and prevents privilege escalation caused by unbounded transitive resolutions in multi-tenant architectures. Mandates explicit graph depth constraints, tuple write DAG validation, and fail-closed fallback mechanisms.
globs: src/**/*.{ts,js}, model/**/*.fga, **/*.openfga.json, lib/auth/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-rebac-depth-cycle-guardrail"
---

# OpenFGA Graph Traversal Depth and Cyclic Relationship Defense Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded Self-Referential Hierarchy Traversal and Missing DAG Validation Causing Authorization DoS and Resolution Bypass

## System Constraints
You are a Principal Security Architect enforcing the OpenFGA ReBAC Graph Depth & Cycle-Safe Authorization Guardrail. You must ensure all authorization models, relationship tuple mutations, and query checks implement strict cycle-prevention logic, tenant boundary isolation, bounded depth configurations, and fail-closed error handling.

## Strict Guidelines
- Engineers MUST ALWAYS enforce strict Directed Acyclic Graph (DAG) invariants prior to persisting any relation tuple to the OpenFGA store.
- Engineers MUST NOT permit self-referencing transitive relationships (e.g., folder inside itself or cyclic group-in-group nesting) without pre-write cycle detection.
- Services MUST configure explicit OpenFGA client timeouts and strict contextual depth parameters on every `check` and `expand` request.
- Code MUST fail-closed (`allowed: false`) upon receiving `ResolutionDepthExceeded`, client timeout, or upstream evaluation error.
- Components NEVER construct cross-tenant relationship tuples without explicit tenant partitioning keys in both `object` and `user` fields.

## Bad vs Good Implementations
### Cycle-Vulnerable Tuple Mutation and Unbounded Check vs DAG-Validated Fail-Closed Authorization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Writing relationship tuples without pre-validating directed acyclic properties allows users to construct cyclic parent chains (A -> B -> A). Subsequent check requests cause OpenFGA evaluation depth exhaustion or request timeouts. Furthermore, the check function lacks tenant namespace isolation and does not gracefully catch or fail-closed against traversal limit exceptions.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

// ANTI-PATTERN: Blindly writing nested parent-child tuples without DAG validation,
// followed by an unconstrained, unbounded evaluation check that lacks fail-closed handling.
export async function addFolderParent(tenantId: string, folderId: string, parentFolderId: string) {
  await fgaClient.write({
    writes: [
      {
        user: `folder:${parentFolderId}`,
        relation: 'parent',
        object: `folder:${folderId}`,
      },
    ],
  });
}

export async function checkFolderAccess(userId: string, folderId: string, relation: string): Promise<boolean> {
  // Vulnerable to cyclic graph traversal timeouts; returns unhandled exception or hangs
  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation,
    object: `folder:${folderId}`,
  });
  return !!response.allowed;
}
```

#### Production Standard (Correct)
> **Standard**: Enforces pre-write cycle detection to protect OpenFGA from cyclic graph loops, prepends tenant partition keys to prevent cross-tenant traversal bypasses, bounds evaluation execution with an explicit client-side timeout, and strictly fails closed (`return false`) whenever graph depth issues or timeouts occur.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

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

const MAX_CHECK_TIMEOUT_MS = 1500;

async function wouldCreateCycle(tenantId: string, childId: string, targetParentId: string): Promise<boolean> {
  if (childId === targetParentId) return true;
  const response = await fgaClient.check({
    user: `tenant:${tenantId}#folder:${childId}`,
    relation: 'ancestor',
    object: `tenant:${tenantId}#folder:${targetParentId}`,
  });
  return response.allowed === true;
}

export async function addFolderParent(tenantId: string, folderId: string, parentFolderId: string): Promise<void> {
  const hasCycle = await wouldCreateCycle(tenantId, folderId, parentFolderId);
  if (hasCycle) {
    throw new Error(`CycleDetected: Assigning parent '${parentFolderId}' to '${folderId}' introduces a cyclic loop.`);
  }

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

export async function checkFolderAccess(tenantId: string, userId: string, folderId: string, relation: string): Promise<boolean> {
  const checkPayload: ClientCheckRequest = {
    user: `tenant:${tenantId}#user:${userId}`,
    relation,
    object: `tenant:${tenantId}#folder:${folderId}`,
  };

  try {
    const timeoutPromise = new Promise<never>((_, reject) =>
      setTimeout(() => reject(new Error('OpenFgaCheckTimeout')), MAX_CHECK_TIMEOUT_MS)
    );

    const checkPromise = fgaClient.check(checkPayload);
    const result = await Promise.race([checkPromise, timeoutPromise]);
    
    return result.allowed === true;
  } catch (error) {
    // Fail-closed invariant: depth exhaustion, network partitions, and timeouts MUST resolve to false
    console.error('Authorization check aborted or depth limit exceeded. Failing closed.', { error, checkPayload });
    return 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: OpenFGA Graph Traversal Depth and Cyclic Relationship Defense Guardrail

OpenFGA Graph Traversal Depth and Cyclic Relationship Defense Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces deterministic graph evaluation limits, cycle prevention invariants, and context-bound authorization checks within OpenFGA ReBAC implementations. Eliminates denial-of-service via nested relationship loops and prevents privilege escalation caused by unbounded transitive resolutions in multi-tenant architectures. Mandates explicit graph depth constraints, tuple write DAG validation, and fail-closed fallback mechanisms. 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 Self-Referential Hierarchy Traversal and Missing DAG Validation Causing Authorization DoS and Resolution Bypass 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 Self-Referential Hierarchy Traversal and Missing DAG Validation Causing Authorization DoS and Resolution BypassCritical
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 strict Directed Acyclic Graph (DAG) invariants prior to persisting any relation tuple to the OpenFGA store.

Engineers MUST ALWAYS enforce strict Directed Acyclic Graph (DAG) invariants prior to persisting any relation tuple to the OpenFGA store.

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 permit self-referencing transitive relationships (e.g., folder inside itself or cyclic group-in-group nesting) without pre-write cycle detection.

Engineers MUST NOT permit self-referencing transitive relationships (e.g., folder inside itself or cyclic group-in-group nesting) without pre-write cycle detection.

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 explicit OpenFGA client timeouts and strict contextual depth parameters on every `check` and `expand` request.

Services MUST configure explicit OpenFGA client timeouts and strict contextual depth parameters on every `check` and `expand` 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 MUST fail-closed (`allowed

Code MUST fail-closed (`allowed: false`) upon receiving `ResolutionDepthExceeded`, client timeout, or upstream evaluation error.

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 construct cross-tenant relationship tuples without explicit tenant partitioning keys in both `object` and `user` fields.

Components NEVER construct cross-tenant relationship tuples without explicit tenant partitioning keys in both `object` and `user` fields.

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 Depth and Cyclic Relationship Defense Guardrail critical for AI coding assistants?

Enforces deterministic graph evaluation limits, cycle prevention invariants, and context-bound authorization checks within OpenFGA ReBAC implementations. Eliminates denial-of-service via nested relationship loops and prevents privilege escalation caused by unbounded transitive resolutions in multi-tenant architectures. Mandates explicit graph depth constraints, tuple write DAG validation, and fail-closed fallback mechanisms. 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 Self-Referential Hierarchy Traversal and Missing DAG Validation Causing Authorization DoS and Resolution Bypass) 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