This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: openfga-recursive-tuple-evaluation-budget-guardrail

OpenFGA Recursive Tuple Evaluation Budget & Traversal Depth Invariant

Deeply nested authorization graphs and cyclic relation tuples can trigger unbounded recursive tree traversals during OpenFGA evaluation, precipitating CPU starvation and cascading denial-of-service vulnerabilities. Systems must strictly enforce relationship traversal depth ceilings, resolve-node evaluation limits, and bounded contextual tuple arrays across both server runtime configurations and client SDK call sites.

Prohibited Anti-Pattern: Unbounded ReBAC Graph Traversal Without Node Budget Limits or Timeout Controls

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Recursive Tuple Evaluation Budget & Traversal Depth Invariant - Deeply nested authorization graphs and cyclic relation tuples can trigger unbounded recursive tree traversals during OpenFGA evaluation, precipitating CPU starvation and cascading denial-of-service vulnerabilities. Systems must strictly enforce relationship traversal depth ceilings, resolve-node evaluation limits, and bounded contextual tuple arrays across both server runtime configurations and client SDK call sites.
globs: src/auth/**/*.{ts,tsx,js,jsx}, src/services/**/*.{ts,tsx,js,jsx}, src/lib/openfga/**/*.{ts,tsx,js,jsx}, infra/**/*.tf, docker-compose*.yml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-recursive-tuple-evaluation-budget-guardrail"
---

# OpenFGA Recursive Tuple Evaluation Budget & Traversal Depth Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded ReBAC Graph Traversal Without Node Budget Limits or Timeout Controls

## System Constraints
You are a Principal Software Architect and Rules Author enforcing the OpenFGA 1.6 Recursive Tuple Evaluation Budget Invariant. Your mandate is to eliminate denial-of-service vulnerabilities in fine-grained authorization graphs by strictly enforcing relationship traversal budgets, resolve-node caps, and explicit timeout bounds across all OpenFGA client interactions and server runtime environments.

## Strict Guidelines
- Engineers MUST ALWAYS configure an explicit execution timeout (AbortController signal with <= 500ms deadline) on every OpenFGA check, expand, and list-objects invocation.
- Engineers MUST NOT supply unbounded or unvalidated contextual tuples arrays to OpenFGA check queries; contextual tuples MUST be limited to a defensive maximum (e.g., <= 20 tuples).
- Services MUST configure OpenFGA server runtimes with explicit node resolution budgets (`OPENFGA_RESOLVE_NODE_LIMIT` <= 25) and max concurrent read constraints (`OPENFGA_MAX_CONCURRENT_READS_FOR_CHECK` <= 30) to prevent unbounded subgraph expansion.
- Code SHOULD catch and handle authorization budget exhaustion errors (e.g., HTTP 400 / internal error code `cannot_allow_request_traversal_limit_reached`) by failing closed with explicit audit logging instead of failing open or uncaught 500 bubbles.
- Components NEVER issue recursive relation checks over cyclic organizational hierarchies without providing depth-limiting contextual conditions or structural loop-prevention guards.

## Bad vs Good Implementations
### Unbounded OpenFGA Check vs Budget-Constrained Resilient Check

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad example executes without an AbortSignal timeout, passes an unbounded array of contextual tuples, and does not handle evaluation budget or traversal depth errors. A malicious or cyclic relation graph can exhaust server-side resolution budgets, hanging worker threads and consuming excessive OpenFGA cluster memory.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

// ANTI-PATTERN: Indefinite execution budget, unbounded contextual tuples,
// and no traversal limit handling allow recursive graphs to trigger ReBAC DoS.
export async function authorizeUser(
  userId: string,
  relation: string,
  documentId: string,
  dynamicContextTuples: Array<{ user: string; relation: string; object: string }>
): Promise<boolean> {
  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation,
    object: `document:${documentId}`,
    contextualTuples: dynamicContextTuples, // Unvalidated dynamic length
  });

  return response.allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: The good implementation enforces a strict 350ms AbortSignal deadline, guards against memory exhaustion by capping contextual tuples to 20, gracefully catches traversal limit errors from OpenFGA, and strictly fails closed to preserve system security and availability.
```typescript
import { OpenFgaClient, FgaApiValidationError, FgaApiRateLimitExceededError } from '@openfga/sdk';

const MAX_CONTEXTUAL_TUPLES = 20;
const CHECK_TIMEOUT_MS = 350;

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

export async function authorizeUser(
  userId: string,
  relation: string,
  documentId: string,
  dynamicContextTuples: Array<{ user: string; relation: string; object: string }> = []
): Promise<boolean> {
  // Invariant 1: Enforce strict contextual tuple boundaries
  if (dynamicContextTuples.length > MAX_CONTEXTUAL_TUPLES) {
    throw new Error(`Contextual tuple budget exceeded: received ${dynamicContextTuples.length}, max ${MAX_CONTEXTUAL_TUPLES}`);
  }

  // Invariant 2: Explicit timeout budget via AbortController
  const controller = new AbortController();
  const timeoutHandle = setTimeout(() => controller.abort(), CHECK_TIMEOUT_MS);

  try {
    const response = await fgaClient.check(
      {
        user: `user:${userId}`,
        relation,
        object: `document:${documentId}`,
        contextualTuples: dynamicContextTuples,
      },
      { signal: controller.signal }
    );

    return response.allowed ?? false;
  } catch (error: unknown) {
    if (error instanceof Error && error.name === 'AbortError') {
      console.error('Authorization check exceeded evaluation time budget', { userId, documentId, relation });
      return false; // Fail closed
    }

    if (error instanceof FgaApiValidationError || error instanceof FgaApiRateLimitExceededError) {
      console.error('OpenFGA evaluation budget or validation violation', { error, userId, documentId });
      return false; // Fail closed
    }

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

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 Recursive Tuple Evaluation Budget & Traversal Depth Invariant

OpenFGA Recursive Tuple Evaluation Budget & Traversal Depth Invariant defines an industrial-grade behavioral standard for security engineering. Deeply nested authorization graphs and cyclic relation tuples can trigger unbounded recursive tree traversals during OpenFGA evaluation, precipitating CPU starvation and cascading denial-of-service vulnerabilities. Systems must strictly enforce relationship traversal depth ceilings, resolve-node evaluation limits, and bounded contextual tuple arrays across both server runtime configurations and client SDK call sites. 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 Without Node Budget Limits or Timeout Controls 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 Without Node Budget Limits or Timeout ControlsCritical
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 configure an explicit execution timeout (AbortController signal with <= 500ms deadline) on every OpenFGA check, expand, and list-objects invocation.

Engineers MUST ALWAYS configure an explicit execution timeout (AbortController signal with <= 500ms deadline) on every OpenFGA check, expand, and list-objects invocation.

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 supply unbounded or unvalidated contextual tuples arrays to OpenFGA check queries

Engineers MUST NOT supply unbounded or unvalidated contextual tuples arrays to OpenFGA check queries; contextual tuples MUST be limited to a defensive maximum (e.g., <= 20 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.
3

Services MUST configure OpenFGA server runtimes with explicit node resolution budgets (`OPENFGA_RESOLVE_NODE_LIMIT` <= 25) and max concurrent read constraints (`OPENFGA_MAX_CONCURRENT_READS_FOR_CHECK` <= 30) to prevent unbounded subgraph expansion.

Services MUST configure OpenFGA server runtimes with explicit node resolution budgets (`OPENFGA_RESOLVE_NODE_LIMIT` <= 25) and max concurrent read constraints (`OPENFGA_MAX_CONCURRENT_READS_FOR_CHECK` <= 30) to prevent unbounded subgraph 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.
4

Code SHOULD catch and handle authorization budget exhaustion errors (e.g., HTTP 400 / internal error code `cannot_allow_request_traversal_limit_reached`) by failing closed with explicit audit logging instead of failing open or uncaught 500 bubbles.

Code SHOULD catch and handle authorization budget exhaustion errors (e.g., HTTP 400 / internal error code `cannot_allow_request_traversal_limit_reached`) by failing closed with explicit audit logging instead of failing open or uncaught 500 bubbles.

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 issue recursive relation checks over cyclic organizational hierarchies without providing depth-limiting contextual conditions or structural loop-prevention guards.

Components NEVER issue recursive relation checks over cyclic organizational hierarchies without providing depth-limiting contextual conditions or structural loop-prevention guards.

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 Recursive Tuple Evaluation Budget & Traversal Depth Invariant critical for AI coding assistants?

Deeply nested authorization graphs and cyclic relation tuples can trigger unbounded recursive tree traversals during OpenFGA evaluation, precipitating CPU starvation and cascading denial-of-service vulnerabilities. Systems must strictly enforce relationship traversal depth ceilings, resolve-node evaluation limits, and bounded contextual tuple arrays across both server runtime configurations and client SDK call sites. 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 Without Node Budget Limits or Timeout Controls) 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