This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: openfga-cyclic-transitive-graph-evaluation-boundary

Deterministic Recursion and Cycle Boundary Enforcement for OpenFGA ReBAC Graphs

Enforces strict recursion depth limits, graph cycle detection, and compute budgets during relationship-based access control (ReBAC) graph resolution in OpenFGA. Prevents compute exhaustion and denial-of-service attacks caused by cyclic tuple insertions or deeply nested transitive relationship expansions.

Prohibited Anti-Pattern: Unbounded Recursive Tuple Traversal and Unchecked Cyclic Relationship Expansions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Deterministic Recursion and Cycle Boundary Enforcement for OpenFGA ReBAC Graphs - Enforces strict recursion depth limits, graph cycle detection, and compute budgets during relationship-based access control (ReBAC) graph resolution in OpenFGA. Prevents compute exhaustion and denial-of-service attacks caused by cyclic tuple insertions or deeply nested transitive relationship expansions.
globs: src/auth/**/*.{ts,js}, src/services/fga/**/*.{ts,js}, src/lib/permissions/**/*.{ts,js}, src/middleware/auth/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-cyclic-transitive-graph-evaluation-boundary"
---

# Deterministic Recursion and Cycle Boundary Enforcement for OpenFGA ReBAC Graphs

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded Recursive Tuple Traversal and Unchecked Cyclic Relationship Expansions

## System Constraints
You are a Principal Security Architect enforcing ReBAC graph invariants on OpenFGA integrations. You must ensure that all relationship evaluations, transitive multi-hop queries, contextual tuple injections, and tuple mutation pipelines employ deterministic recursion limits, cycle detection, and hard request boundaries to prevent algorithmic complexity and exhaustion attacks.

## Strict Guidelines
- Engineers MUST ALWAYS enforce strict cycle detection and a maximum path depth (MAX_HOP_LIMIT <= 15) when pre-evaluating or writing transitive contextual tuples.
- Engineers MUST NOT expose raw, unbounded `expand` or `list-objects` API calls to untrusted client inputs without deterministic pagination and depth boundaries.
- Tuple ingestion pipelines MUST validate that newly inserted hierarchical relationships (e.g., parent/child or nested group membership) do not introduce direct or transitive directed cycles before persisting to OpenFGA.
- OpenFGA client requests MUST ALWAYS configure deterministic request deadlines and timeout boundaries (e.g., maximum 500ms for Check, 2000ms for ListObjects).
- Services MUST reject contextual tuple sets containing circular edge definitions before passing them to the OpenFGA evaluation engine.

## Bad vs Good Implementations
### Unbounded Tuple Ingestion and Contextual Traversal vs. Guarded Cycle-Safe Evaluation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The code fails to validate directed acyclic graph (DAG) constraints prior to writing nested group relationships, allowing malicious or accidental circular dependencies. In addition, dynamic contextual tuples are supplied directly to evaluation without cycle detection or hop-count boundary verification, opening the system to algorithmic compute exhaustion (ReBaC Denial-of-Service).
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

// VULNERABLE: Direct tuple insertion without cycle detection allows
// an attacker to create: group:A -> member -> group:B -> member -> group:A
export async function addGroupMember(parentGroupId: string, childGroupId: string) {
  await fgaClient.write({
    writes: [{
      user: `group:${childGroupId}`,
      relation: 'member',
      object: `group:${parentGroupId}`,
    }],
  });
}

// VULNERABLE: Unbounded recursive contextual expansion can trigger infinite loops
// or exhaustion of OpenFGA resolution memory when evaluation graphs loop.
export async function evaluateTransitiveAccess(userId: string, objectId: string, dynamicEdges: Array<{ from: string; to: string }>) {
  const contextualTuples = dynamicEdges.map(edge => ({
    user: edge.from,
    relation: 'parent',
    object: edge.to,
  }));
  
  return await fgaClient.check({
    user: `user:${userId}`,
    relation: 'can_view',
    object: objectId,
    contextualTuples,
  });
}
```

#### Production Standard (Correct)
> **Standard**: The defensive implementation enforces DAG validation via BFS cycle detection before relationship mutation, caps maximum graph traversal depth to prevent recursive expansion attacks, and enforces strict client-side timeout boundaries (500ms abort controller) for OpenFGA check evaluations.
```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_GRAPH_HOPS = 10;
const CHECK_TIMEOUT_MS = 500;

interface Edge {
  from: string;
  to: string;
}

// Guard: Validate DAG invariants before writing transitive relations
export async function validateNoCycle(
  candidateFrom: string,
  candidateTo: string,
  existingEdges: Edge[],
  maxHops: number = MAX_GRAPH_HOPS
): Promise<boolean> {
  const adjList = new Map<string, string[]>();
  for (const { from, to } of existingEdges) {
    const targets = adjList.get(from) ?? [];
    targets.push(to);
    adjList.set(from, targets);
  }

  // Check if candidateTo can reach candidateFrom (which would form a cycle)
  const visited = new Set<string>();
  const queue: Array<{ node: string; depth: number }> = [{ node: candidateTo, depth: 0 }];

  while (queue.length > 0) {
    const current = queue.shift()!;
    if (current.node === candidateFrom) {
      return false; // Cycle detected
    }
    if (current.depth >= maxHops) {
      throw new Error(`Graph evaluation boundary exceeded max hop limit of ${maxHops}`);
    }
    if (!visited.has(current.node)) {
      visited.add(current.node);
      for (const next of adjList.get(current.node) ?? []) {
        queue.push({ node: next, depth: current.depth + 1 });
      }
    }
  }
  return true;
}

export async function addGroupMemberSafely(
  parentGroupId: string,
  childGroupId: string,
  fetchExistingRelations: () => Promise<Edge[]>
) {
  const existing = await fetchExistingRelations();
  const isAcyclic = await validateNoCycle(`group:${parentGroupId}`, `group:${childGroupId}`, existing);
  
  if (!isAcyclic) {
    throw new Error('Cyclic group membership detected. ReBAC graph invariants strictly prohibit circular edges.');
  }

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

export async function evaluateTransitiveAccessSafely(
  userId: string,
  objectId: string,
  dynamicEdges: Edge[]
) {
  if (dynamicEdges.length > MAX_GRAPH_HOPS) {
    throw new Error(`Contextual edge count (${dynamicEdges.length}) exceeds safety limit (${MAX_GRAPH_HOPS}).`);
  }

  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), CHECK_TIMEOUT_MS);

  try {
    const request: ClientCheckRequest = {
      user: `user:${userId}`,
      relation: 'can_view',
      object: objectId,
      contextualTuples: dynamicEdges.map(edge => ({
        user: edge.from,
        relation: 'parent',
        object: edge.to,
      })),
    };

    return await fgaClient.check(request, { signal: controller.signal });
  } 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: Deterministic Recursion and Cycle Boundary Enforcement for OpenFGA ReBAC Graphs

Deterministic Recursion and Cycle Boundary Enforcement for OpenFGA ReBAC Graphs defines an industrial-grade behavioral standard for security engineering. Enforces strict recursion depth limits, graph cycle detection, and compute budgets during relationship-based access control (ReBAC) graph resolution in OpenFGA. Prevents compute exhaustion and denial-of-service attacks caused by cyclic tuple insertions or deeply nested transitive relationship expansions. 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 Traversal and Unchecked Cyclic Relationship Expansions 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 Traversal and Unchecked Cyclic Relationship ExpansionsCritical
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 cycle detection and a maximum path depth (MAX_HOP_LIMIT <= 15) when pre-evaluating or writing transitive contextual tuples.

Engineers MUST ALWAYS enforce strict cycle detection and a maximum path depth (MAX_HOP_LIMIT <= 15) when pre-evaluating or writing transitive contextual tuples.

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 expose raw, unbounded `expand` or `list-objects` API calls to untrusted client inputs without deterministic pagination and depth boundaries.

Engineers MUST NOT expose raw, unbounded `expand` or `list-objects` API calls to untrusted client inputs without deterministic pagination and depth boundaries.

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

Tuple ingestion pipelines MUST validate that newly inserted hierarchical relationships (e.g., parent/child or nested group membership) do not introduce direct or transitive directed cycles before persisting to OpenFGA.

Tuple ingestion pipelines MUST validate that newly inserted hierarchical relationships (e.g., parent/child or nested group membership) do not introduce direct or transitive directed cycles before persisting 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.
4

OpenFGA client requests MUST ALWAYS configure deterministic request deadlines and timeout boundaries (e.g., maximum 500ms for Check, 2000ms for ListObjects).

OpenFGA client requests MUST ALWAYS configure deterministic request deadlines and timeout boundaries (e.g., maximum 500ms for Check, 2000ms for ListObjects).

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

Services MUST reject contextual tuple sets containing circular edge definitions before passing them to the OpenFGA evaluation engine.

Services MUST reject contextual tuple sets containing circular edge definitions before passing them to the OpenFGA evaluation engine.

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 Deterministic Recursion and Cycle Boundary Enforcement for OpenFGA ReBAC Graphs critical for AI coding assistants?

Enforces strict recursion depth limits, graph cycle detection, and compute budgets during relationship-based access control (ReBAC) graph resolution in OpenFGA. Prevents compute exhaustion and denial-of-service attacks caused by cyclic tuple insertions or deeply nested transitive relationship expansions. 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 Traversal and Unchecked Cyclic Relationship Expansions) 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

Deterministic