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

OpenFGA Contextual Tuple Graph Traversal Depth and Cycle Guardrail

Enforces pre-flight cycle detection, strict cardinality caps, and traversal depth limits on contextual tuples injected during runtime OpenFGA relationship-based access control (ReBAC) evaluations. Prevents Denial of Service (DoS) and algorithmic complexity exhaustion caused by deeply nested or cyclical graph expansions in check and list-objects queries. Mandates client-side structural validation before passing dynamic authorization contexts to the OpenFGA storage engine.

Prohibited Anti-Pattern: Unbounded Contextual Tuple Injection Causing ReBAC Graph Recursion Exhaustion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Contextual Tuple Graph Traversal Depth and Cycle Guardrail - Enforces pre-flight cycle detection, strict cardinality caps, and traversal depth limits on contextual tuples injected during runtime OpenFGA relationship-based access control (ReBAC) evaluations. Prevents Denial of Service (DoS) and algorithmic complexity exhaustion caused by deeply nested or cyclical graph expansions in check and list-objects queries. Mandates client-side structural validation before passing dynamic authorization contexts to the OpenFGA storage engine.
globs: src/auth/**/*.{ts,tsx}, src/security/**/*.{ts,tsx}, src/lib/fga/**/*.{ts,tsx}, src/services/authz/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuple-depth-guardrail"
---

# OpenFGA Contextual Tuple Graph Traversal Depth and Cycle Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded Contextual Tuple Injection Causing ReBAC Graph Recursion Exhaustion

## System Constraints
You are a Principal Security Architect enforcing resilient ReBAC implementations with OpenFGA. You must mandate strict depth controls, cycle detection, and input bounds on contextual tuples injected into authorization evaluation calls. ReBAC engines resolve relationships recursively; passing unvalidated, cyclical, or excessively deep contextual tuples directly from client inputs or dynamic session payloads exposes the authorization cluster to stack overflows, high latency spikes, and algorithmic complexity DoS attacks.

## Strict Guidelines
- Engineers MUST ALWAYS run pre-flight cycle detection using Tarjan's or Kahn's algorithm on contextual tuple graphs before sending evaluations to OpenFGA.
- Engineers MUST NOT forward raw, unvalidated client-provided hierarchies or contextual tuples directly into OpenFGA `check`, `batchCheck`, or `listObjects` APIs.
- Code SHOULD enforce strict limits on total contextual tuple count (MAX_CONTEXTUAL_TUPLES <= 20) and contextual chain depth (MAX_GRAPH_DEPTH <= 4).
- Services MUST configure OpenFGA clients with deterministic execution timeouts and per-request abort signals to prevent runaway recursive resolutions.
- Components NEVER allow self-referential or transitive reflexive contextual tuples where an entity is asserted as its own ancestor or direct relation.

## Bad vs Good Implementations
### Insecure Unbounded Contextual Tuples vs. Guarded Directed Acyclic Graph (DAG) Traversal

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Contextual tuples are passed directly from caller inputs without validation. Cyclical or deeply nested chains cause graph explosion in OpenFGA's recursive resolution algorithm, triggering ReBAC denial of service and unbounded latency.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

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

// VULNERABLE: Direct passthrough of arbitrary contextual tuples from user request.
// Deeply nested or cyclical relations (e.g. folder:a -> folder:b -> folder:a)
// cause goroutine exhaustion and CPU spikes in the OpenFGA engine.
export async function checkAccessInsecure(
  userId: string,
  relation: string,
  objectId: string,
  contextualTuples: Array<{ user: string; relation: string; object: string }>
) {
  const payload: ClientCheckRequest = {
    user: `user:${userId}`,
    relation,
    object: objectId,
    contextualTuples
  };

  const { allowed } = await fgaClient.check(payload);
  return allowed;
}
```

#### Production Standard (Correct)
> **Standard**: Strict pre-flight guards enforce a maximum tuple count, detect cyclic dependencies via depth-first search cycle detection, prevent reflexive self-loops, and place strict execution timeouts on the OpenFGA client query to ensure bounded traversal complexity.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

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

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

const MAX_CONTEXTUAL_TUPLES = 15;
const MAX_ALLOWED_DEPTH = 3;
const EVALUATION_TIMEOUT_MS = 250;

class CyclicalGraphError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'CyclicalGraphError';
  }
}

function validateContextualGraph(tuples: TupleKey[]): void {
  if (tuples.length > MAX_CONTEXTUAL_TUPLES) {
    throw new RangeError(`Exceeded maximum contextual tuple limit of ${MAX_CONTEXTUAL_TUPLES}`);
  }

  const adjList = new Map<string, string[]>();
  for (const { user, object } of tuples) {
    if (user === object) {
      throw new CyclicalGraphError(`Self-referential relation detected on ${object}`);
    }
    const neighbors = adjList.get(user) ?? [];
    neighbors.push(object);
    adjList.set(user, neighbors);
  }

  // Detect cycles and measure traversal depth using iterative DFS
  const visited = new Set<string>();
  const recursionStack = new Set<string>();

  function dfs(node: string, currentDepth: number): void {
    if (currentDepth > MAX_ALLOWED_DEPTH) {
      throw new RangeError(`Contextual hierarchy exceeds max depth of ${MAX_ALLOWED_DEPTH}`);
    }
    visited.add(node);
    recursionStack.add(node);

    const neighbors = adjList.get(node) ?? [];
    for (const neighbor of neighbors) {
      if (!visited.has(neighbor)) {
        dfs(neighbor, currentDepth + 1);
      } else if (recursionStack.has(neighbor)) {
        throw new CyclicalGraphError(`Cyclical dependency detected between ${node} and ${neighbor}`);
      }
    }
    recursionStack.delete(node);
  }

  for (const node of adjList.keys()) {
    if (!visited.has(node)) {
      dfs(node, 1);
    }
  }
}

export async function checkAccessGuarded(
  userId: string,
  relation: string,
  objectId: string,
  contextualTuples: TupleKey[]
): Promise<boolean> {
  validateContextualGraph(contextualTuples);

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

  try {
    const payload: ClientCheckRequest = {
      user: `user:${userId}`,
      relation,
      object: objectId,
      contextualTuples
    };

    const { allowed } = await fgaClient.check(payload, {
      signal: controller.signal
    });
    return Boolean(allowed);
  } finally {
    clearTimeout(timeoutId);
  }
}
```

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 Contextual Tuple Graph Traversal Depth and Cycle Guardrail

OpenFGA Contextual Tuple Graph Traversal Depth and Cycle Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces pre-flight cycle detection, strict cardinality caps, and traversal depth limits on contextual tuples injected during runtime OpenFGA relationship-based access control (ReBAC) evaluations. Prevents Denial of Service (DoS) and algorithmic complexity exhaustion caused by deeply nested or cyclical graph expansions in check and list-objects queries. Mandates client-side structural validation before passing dynamic authorization contexts to the OpenFGA storage engine. 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 Contextual Tuple Injection Causing ReBAC Graph Recursion Exhaustion 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 Contextual Tuple Injection Causing ReBAC Graph Recursion ExhaustionCritical
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 run pre-flight cycle detection using Tarjan's or Kahn's algorithm on contextual tuple graphs before sending evaluations to OpenFGA.

Engineers MUST ALWAYS run pre-flight cycle detection using Tarjan's or Kahn's algorithm on contextual tuple graphs before sending evaluations 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.
2

Engineers MUST NOT forward raw, unvalidated client-provided hierarchies or contextual tuples directly into OpenFGA `check`, `batchCheck`, or `listObjects` APIs.

Engineers MUST NOT forward raw, unvalidated client-provided hierarchies or contextual tuples directly into OpenFGA `check`, `batchCheck`, or `listObjects` APIs.

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 SHOULD enforce strict limits on total contextual tuple count (MAX_CONTEXTUAL_TUPLES <= 20) and contextual chain depth (MAX_GRAPH_DEPTH <= 4).

Code SHOULD enforce strict limits on total contextual tuple count (MAX_CONTEXTUAL_TUPLES <= 20) and contextual chain depth (MAX_GRAPH_DEPTH <= 4).

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 configure OpenFGA clients with deterministic execution timeouts and per-request abort signals to prevent runaway recursive resolutions.

Services MUST configure OpenFGA clients with deterministic execution timeouts and per-request abort signals to prevent runaway recursive resolutions.

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 allow self-referential or transitive reflexive contextual tuples where an entity is asserted as its own ancestor or direct relation.

Components NEVER allow self-referential or transitive reflexive contextual tuples where an entity is asserted as its own ancestor or direct relation.

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 Contextual Tuple Graph Traversal Depth and Cycle Guardrail critical for AI coding assistants?

Enforces pre-flight cycle detection, strict cardinality caps, and traversal depth limits on contextual tuples injected during runtime OpenFGA relationship-based access control (ReBAC) evaluations. Prevents Denial of Service (DoS) and algorithmic complexity exhaustion caused by deeply nested or cyclical graph expansions in check and list-objects queries. Mandates client-side structural validation before passing dynamic authorization contexts to the OpenFGA storage engine. 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 Contextual Tuple Injection Causing ReBAC Graph Recursion Exhaustion) 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