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

OpenFGA ReBAC Recursive Cycle Clamping and Transitive Graph Depth Standard

Prevents catastrophic denial-of-service vulnerabilities caused by unbounded transitive graph traversals, circular group nestings, and unchecked contextual tuple expansions in OpenFGA Relationship-Based Access Control (ReBAC). Mandates cycle-detection pre-validation on tuple writes, strict execution budgets with deadline clamping on authorization checks, and fail-closed traversal boundary policies.

Prohibited Anti-Pattern: Unbounded ReBAC Graph Traversal and Cyclic Relation Expansion Causing Service Starvation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA ReBAC Recursive Cycle Clamping and Transitive Graph Depth Standard - Prevents catastrophic denial-of-service vulnerabilities caused by unbounded transitive graph traversals, circular group nestings, and unchecked contextual tuple expansions in OpenFGA Relationship-Based Access Control (ReBAC). Mandates cycle-detection pre-validation on tuple writes, strict execution budgets with deadline clamping on authorization checks, and fail-closed traversal boundary policies.
globs: src/auth/**/*.{ts,tsx}, src/services/auth/**/*.{ts,tsx}, src/lib/fga/**/*.{ts,tsx}, src/security/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-rebac-depth-clamping-cycle-guardrail"
---

# OpenFGA ReBAC Recursive Cycle Clamping and Transitive Graph Depth Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded ReBAC Graph Traversal and Cyclic Relation Expansion Causing Service Starvation

## System Constraints
You are a Principal Software Architect enforcing enterprise OpenFGA ReBAC stability standards. You must strictly prevent unbounded recursive traversals, circular nested memberships, and memory/CPU exhaustion across fine-grained authorization checks. Mandate DAG (Directed Acyclic Graph) validation on tuple ingestion, strict client-side evaluation deadline clamping, bounded contextual tuple budgets, and deterministic fail-closed execution on resolution limits.

## Strict Guidelines
- Engineers MUST ALWAYS enforce strict per-request deadline timeouts (maximum 250ms for synchronous check calls) using AbortSignal on all OpenFGA client evaluation invocations.
- Engineers MUST NEVER permit unvalidated self-referential or cyclic relationship tuple insertions (e.g., group:A#member@group:B, group:B#member@group:A) into the authorization tuple store.
- Services MUST implement Directed Acyclic Graph (DAG) cycle validation prior to committing transitive relationship tuples (parent/child, group membership, folder hierarchy).
- Code MUST explicitly clamp contextual_tuples arrays to a deterministic maximum boundary (e.g., max 25 contextual tuples per evaluation) to prevent unbounded evaluation tree expansion.
- Engineers MUST ALWAYS handle OpenFGA depth exhaustion and cycle-detected errors by failing closed (returning access denied) and emitting critical security telemetry, never by silently retrying.
- Components NEVER execute raw unbounded batch authorization checks without concurrency throttling and collective timeout budgets.

## Bad vs Good Implementations
### Safe ReBAC Evaluation with Clamped Depth, Budgeted Context, and DAG Cycle-Checked Writes

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad example creates two severe denial-of-service attack vectors: (1) It allows writing cyclic group memberships (e.g., A contains B, B contains A) without pre-validation, creating circular graph loops. (2) It executes check() without execution timeouts (AbortSignal) and accepts unbounded contextual tuples, allowing an attacker to submit crafted deep nested structures that lock OpenFGA evaluation threads and exhaust CPU.
```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 tuples without cycle detection
export async function addGroupMember(parentGroupId: string, childGroupId: string): Promise<void> {
  await fgaClient.write({
    writes: [{
      user: `group:${childGroupId}#member`,
      relation: 'member',
      object: `group:${parentGroupId}`,
    }],
  });
}

// ANTI-PATTERN: Unbounded check without timeouts, depth budgets, or cycle fail-closed handling
export async function checkAccess(userId: string, objectId: string, relation: string, userContextTuples: any[]): Promise<boolean> {
  // Missing AbortSignal, unbounded contextual_tuples can trigger evaluation DoS
  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation,
    object: `document:${objectId}`,
    contextualTuples: userContextTuples, // Arbitrary size allows memory ballooning
  });
  return response.allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: The good example implements strict depth and cycle clamping: (1) `validateNoCycle` proactively verifies the relationship DAG before committing tuples, preventing circular graph deadlocks. (2) Contextual tuples are clamped to an explicit safety ceiling (`MAX_CONTEXTUAL_TUPLES = 20`). (3) Authorization checks enforce a hard 250ms deadline via `AbortSignal`. (4) All evaluation errors and timeouts fail closed, returning `false` rather than leaking access or cascading system latency.
```typescript
import { OpenFgaClient, FgaError } from '@openfga/sdk';

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

const MAX_CHECK_TIMEOUT_MS = 250;
const MAX_CONTEXTUAL_TUPLES = 20;

export interface RelationshipNode {
  id: string;
  parents: string[];
}

// Pre-write cycle detection ensuring transitive DAG invariant
export async function validateNoCycle(
  targetGroupId: string,
  ancestorGroupId: string,
  fetchAncestors: (id: string) => Promise<string[]>
): Promise<void> {
  const visited = new Set<string>();
  const queue: string[] = [ancestorGroupId];

  while (queue.length > 0) {
    const current = queue.shift()!;
    if (current === targetGroupId) {
      throw new Error(`Cycle detected: Adding ${ancestorGroupId} to ${targetGroupId} creates a recursive loop.`);
    }
    if (!visited.has(current)) {
      visited.add(current);
      const parents = await fetchAncestors(current);
      queue.push(...parents);
    }
  }
}

export async function writeGroupMemberSafe(
  parentGroupId: string,
  childGroupId: string,
  fetchAncestors: (id: string) => Promise<string[]>
): Promise<void> {
  if (parentGroupId === childGroupId) {
    throw new Error('Self-referential membership is prohibited.');
  }

  // Enforce DAG invariant before persistence
  await validateNoCycle(childGroupId, parentGroupId, fetchAncestors);

  await fgaClient.write({
    writes: [{
      user: `group:${childGroupId}#member`,
      relation: 'member',
      object: `group:${parentGroupId}`,
    }],
  });
}

export async function checkAccessSafe(
  userId: string,
  objectId: string,
  relation: string,
  contextualTuples: Array<{ user: string; relation: string; object: string }> = []
): Promise<boolean> {
  // Clamp contextual tuple cardinality to eliminate memory exhaustion vectors
  if (contextualTuples.length > MAX_CONTEXTUAL_TUPLES) {
    throw new Error(`Contextual tuple limit exceeded: maximum allowed is ${MAX_CONTEXTUAL_TUPLES}`);
  }

  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), MAX_CHECK_TIMEOUT_MS);

  try {
    const response = await fgaClient.check(
      {
        user: `user:${userId}`,
        relation,
        object: `document:${objectId}`,
        contextualTuples,
      },
      {
        signal: controller.signal,
      }
    );
    return Boolean(response.allowed);
  } catch (error: unknown) {
    // Fail closed on timeouts, cycle errors, or resolution limits
    if (error instanceof Error && error.name === 'AbortError') {
      console.error(`FGA check timed out after ${MAX_CHECK_TIMEOUT_MS}ms. Failing closed.`, {
        userId,
        objectId,
        relation,
      });
      return false;
    }

    if (error instanceof FgaError) {
      console.error('FGA evaluation error encountered. Clamping graph traversal to denied.', error);
      return false;
    }

    throw error;
  } finally {
    clearTimeout(timeoutId);
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA ReBAC Recursive Cycle Clamping and Transitive Graph Depth Standard

OpenFGA ReBAC Recursive Cycle Clamping and Transitive Graph Depth Standard defines an industrial-grade behavioral standard for backend engineering. Prevents catastrophic denial-of-service vulnerabilities caused by unbounded transitive graph traversals, circular group nestings, and unchecked contextual tuple expansions in OpenFGA Relationship-Based Access Control (ReBAC). Mandates cycle-detection pre-validation on tuple writes, strict execution budgets with deadline clamping on authorization checks, and fail-closed traversal boundary policies. 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 ReBAC Graph Traversal and Cyclic Relation Expansion Causing Service 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 DriftUnbounded ReBAC Graph Traversal and Cyclic Relation Expansion Causing Service 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 enforce strict per-request deadline timeouts (maximum 250ms for synchronous check calls) using AbortSignal on all OpenFGA client evaluation invocations.

Engineers MUST ALWAYS enforce strict per-request deadline timeouts (maximum 250ms for synchronous check calls) using AbortSignal on all OpenFGA client evaluation invocations.

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 NEVER permit unvalidated self-referential or cyclic relationship tuple insertions (e.g., group

Engineers MUST NEVER permit unvalidated self-referential or cyclic relationship tuple insertions (e.g., group:A#member@group:B, group:B#member@group:A) into the authorization tuple 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.
3

Services MUST implement Directed Acyclic Graph (DAG) cycle validation prior to committing transitive relationship tuples (parent/child, group membership, folder hierarchy).

Services MUST implement Directed Acyclic Graph (DAG) cycle validation prior to committing transitive relationship tuples (parent/child, group membership, folder hierarchy).

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 explicitly clamp contextual_tuples arrays to a deterministic maximum boundary (e.g., max 25 contextual tuples per evaluation) to prevent unbounded evaluation tree expansion.

Code MUST explicitly clamp contextual_tuples arrays to a deterministic maximum boundary (e.g., max 25 contextual tuples per evaluation) to prevent unbounded evaluation tree expansion.

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

Engineers MUST ALWAYS handle OpenFGA depth exhaustion and cycle-detected errors by failing closed (returning access denied) and emitting critical security telemetry, never by silently retrying.

Engineers MUST ALWAYS handle OpenFGA depth exhaustion and cycle-detected errors by failing closed (returning access denied) and emitting critical security telemetry, never by silently retrying.

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.
6

Components NEVER execute raw unbounded batch authorization checks without concurrency throttling and collective timeout budgets.

Components NEVER execute raw unbounded batch authorization checks without concurrency throttling and collective timeout budgets.

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 ReBAC Recursive Cycle Clamping and Transitive Graph Depth Standard critical for AI coding assistants?

Prevents catastrophic denial-of-service vulnerabilities caused by unbounded transitive graph traversals, circular group nestings, and unchecked contextual tuple expansions in OpenFGA Relationship-Based Access Control (ReBAC). Mandates cycle-detection pre-validation on tuple writes, strict execution budgets with deadline clamping on authorization checks, and fail-closed traversal boundary policies. 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 ReBAC Graph Traversal and Cyclic Relation Expansion Causing Service 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