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

Deterministic Traversal Depth and Cycle Quotas for OpenFGA 1.8 ReBAC

Enforces deterministic graph traversal ceilings, strict contextual tuple limits, and cycle-breaking invariants across OpenFGA 1.8 relationship-based access control (ReBAC) implementations. Prevents unbounded graph expansion attacks, recursive amplification denial-of-service, and resource exhaustion during Check, ListObjects, and Expand evaluation pipelines.

Prohibited Anti-Pattern: Unbounded Graph Traversal and Unvalidated Contextual Tuple Injection in ReBAC Evaluation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Deterministic Traversal Depth and Cycle Quotas for OpenFGA 1.8 ReBAC - Enforces deterministic graph traversal ceilings, strict contextual tuple limits, and cycle-breaking invariants across OpenFGA 1.8 relationship-based access control (ReBAC) implementations. Prevents unbounded graph expansion attacks, recursive amplification denial-of-service, and resource exhaustion during Check, ListObjects, and Expand evaluation pipelines.
globs: src/**/authz/**/*.{ts,tsx,js,go,py}, src/**/authorization/**/*.{ts,tsx,js,go,py}, src/**/security/**/*.{ts,tsx,js,go,py}, **/*.fga, **/*.fga.yaml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-rebac-graph-expansion-depth-quotas"
---

# Deterministic Traversal Depth and Cycle Quotas for OpenFGA 1.8 ReBAC

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded Graph Traversal and Unvalidated Contextual Tuple Injection in ReBAC Evaluation

## System Constraints
You are a Principal Software Architect and Rules Author for AI Coding Agents. Your objective is to enforce rock-solid security invariants for OpenFGA 1.8 authorization layers, specifically mitigating graph traversal amplification, cycle exploitation, and unbounded contextual tuple injections. Mandate deterministic depth budgets, timeout bounds, and safe fallback handling.

## Strict Guidelines
- Engineers MUST ALWAYS enforce strict server-side timeouts (max 500ms for Check, 2000ms for ListObjects) via context cancellation or AbortController on every OpenFGA API invocation.
- Engineers MUST NEVER pass raw, unbounded user-supplied contextual tuples to OpenFGA Check or ListObjects calls without sanitization, schema validation, and hard cardinality clamping (MAX 20 contextual tuples per evaluation).
- Code MUST validate OpenFGA authorization models against cyclic relation self-references using deterministic tuple testing (fga model test) prior to artifact promotion.
- Services MUST gracefully intercept and quarantine OpenFGA resolution ceiling exceptions (e.g., dispatch limit exceeded, depth quota breached, cycle detected) and default securely to denial of access (Fail-Closed).
- Components NEVER rely on OpenFGA default infinite dispatch configurations in self-hosted instances; OPENFGA_RESOLVE_CHECK_MAX_DISPATCHES MUST be pinned explicitly (default threshold <= 25).

## Bad vs Good Implementations
### Unbounded Contextual Tuples and Unprotected Graph Resolution

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accepting unvalidated, unbounded client-provided contextual tuples creates an algorithmic complexity exploit. When coupled with deeply nested or self-referential graph paths and no context cancellation or dispatch limits, this induces memory exhaustion and CPU lockup across the authorization cluster.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

// ANTI-PATTERN: Direct injection of client-supplied contextual tuples with unbounded traversal
export async function checkAccess(userId: string, objectId: string, relation: string, userTuples: Array<{ user: string; relation: string; object: string }>) {
  // Flaw 1: No timeout bounds applied
  // Flaw 2: Unchecked userTuples length creates amplification bomb
  // Flaw 3: Leaks raw internal engine exceptions
  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation: relation,
    object: `document:${objectId}`,
    contextualTuples: userTuples,
  });

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

#### Production Standard (Correct)
> **Standard**: Enforces a strict deterministic budget: bounds contextual tuples to a max ceiling of 20, applies a strict 500ms AbortController timeout, maps and validates inputs, and ensures a hard fail-closed posture on graph traversal exceptions (e.g., depth exceeded, cycles, timeouts).
```typescript
import { OpenFgaClient, FgaApiValidationError, FgaApiNotFoundError } from '@openfga/sdk';

const MAX_CONTEXTUAL_TUPLES = 20;
const CHECK_TIMEOUT_MS = 500;

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

interface SafeContextualTuple {
  user: string;
  relation: string;
  object: string;
}

export async function checkAccessDeterministic(
  userId: string,
  objectId: string,
  relation: string,
  contextualTuples: SafeContextualTuple[] = []
): Promise<boolean> {
  // Invariant 1: Hard clamp on dynamic contextual tuple cardinality
  if (contextualTuples.length > MAX_CONTEXTUAL_TUPLES) {
    console.warn(`[Security Alert] Rejected check: Contextual tuple budget exceeded (${contextualTuples.length}/${MAX_CONTEXTUAL_TUPLES})`);
    return false; // Fail closed
  }

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

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

    return Boolean(response.allowed);
  } catch (error: unknown) {
    // Invariant 3: Fail-closed on cycle detection, depth limits, or network timeouts
    console.error('[AuthZ Resolution Aborted]', {
      userId,
      objectId,
      relation,
      error: error instanceof Error ? error.message : 'Unknown error',
    });
    return false; // Guaranteed fail-closed
  } 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 Traversal Depth and Cycle Quotas for OpenFGA 1.8 ReBAC

Deterministic Traversal Depth and Cycle Quotas for OpenFGA 1.8 ReBAC defines an industrial-grade behavioral standard for security engineering. Enforces deterministic graph traversal ceilings, strict contextual tuple limits, and cycle-breaking invariants across OpenFGA 1.8 relationship-based access control (ReBAC) implementations. Prevents unbounded graph expansion attacks, recursive amplification denial-of-service, and resource exhaustion during Check, ListObjects, and Expand evaluation pipelines. 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 Traversal and Unvalidated Contextual Tuple Injection in ReBAC Evaluation 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 Traversal and Unvalidated Contextual Tuple Injection in ReBAC EvaluationCritical
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 server-side timeouts (max 500ms for Check, 2000ms for ListObjects) via context cancellation or AbortController on every OpenFGA API invocation.

Engineers MUST ALWAYS enforce strict server-side timeouts (max 500ms for Check, 2000ms for ListObjects) via context cancellation or AbortController on every OpenFGA API 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 NEVER pass raw, unbounded user-supplied contextual tuples to OpenFGA Check or ListObjects calls without sanitization, schema validation, and hard cardinality clamping (MAX 20 contextual tuples per evaluation).

Engineers MUST NEVER pass raw, unbounded user-supplied contextual tuples to OpenFGA Check or ListObjects calls without sanitization, schema validation, and hard cardinality clamping (MAX 20 contextual tuples per evaluation).

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 validate OpenFGA authorization models against cyclic relation self-references using deterministic tuple testing (fga model test) prior to artifact promotion.

Code MUST validate OpenFGA authorization models against cyclic relation self-references using deterministic tuple testing (fga model test) prior to artifact promotion.

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 gracefully intercept and quarantine OpenFGA resolution ceiling exceptions (e.g., dispatch limit exceeded, depth quota breached, cycle detected) and default securely to denial of access (Fail-Closed).

Services MUST gracefully intercept and quarantine OpenFGA resolution ceiling exceptions (e.g., dispatch limit exceeded, depth quota breached, cycle detected) and default securely to denial of access (Fail-Closed).

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 rely on OpenFGA default infinite dispatch configurations in self-hosted instances

Components NEVER rely on OpenFGA default infinite dispatch configurations in self-hosted instances; OPENFGA_RESOLVE_CHECK_MAX_DISPATCHES MUST be pinned explicitly (default threshold <= 25).

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 Traversal Depth and Cycle Quotas for OpenFGA 1.8 ReBAC critical for AI coding assistants?

Enforces deterministic graph traversal ceilings, strict contextual tuple limits, and cycle-breaking invariants across OpenFGA 1.8 relationship-based access control (ReBAC) implementations. Prevents unbounded graph expansion attacks, recursive amplification denial-of-service, and resource exhaustion during Check, ListObjects, and Expand evaluation pipelines. 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 Traversal and Unvalidated Contextual Tuple Injection in ReBAC Evaluation) 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