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

OpenFGA Contextual Tuple Graph Recursion and Depth Limiter

Enforces strict structural validation, depth bounding, and cycle detection on ad-hoc contextual tuples passed to OpenFGA Check and ListObjects operations. Unbounded or cyclic contextual tuples allow malicious actors to induce catastrophic ReBAC graph expansion, thread starvation, and service-level denial of service via adversarial graph structures.

Prohibited Anti-Pattern: Unvalidated Contextual Tuple Injection Causing ReBAC Catastrophic Backtracking and CPU Starvation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Contextual Tuple Graph Recursion and Depth Limiter - Enforces strict structural validation, depth bounding, and cycle detection on ad-hoc contextual tuples passed to OpenFGA Check and ListObjects operations. Unbounded or cyclic contextual tuples allow malicious actors to induce catastrophic ReBAC graph expansion, thread starvation, and service-level denial of service via adversarial graph structures.
globs: src/auth/**/*.{ts,js,py,go}, src/middleware/**/*.{ts,js,py,go}, src/services/fga/**/*.{ts,js,py,go}, src/lib/fga/**/*.{ts,js,py,go}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuple-recursion-depth-limiter"
---

# OpenFGA Contextual Tuple Graph Recursion and Depth Limiter

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unvalidated Contextual Tuple Injection Causing ReBAC Catastrophic Backtracking and CPU Starvation

## System Constraints
You are a Principal Security Architect specializing in Fine-Grained Authorization (ReBAC) with OpenFGA. Mandate strict validation, graph cycle detection, and depth bounding on all client-provided contextual tuples prior to delegating evaluation to OpenFGA instances. Protect evaluation endpoints from catastrophic backtracking, recursive graph depth exhaustion, and thread starvation.

## Strict Guidelines
- Engineers MUST ALWAYS enforce a hard upper bound on the number of contextual tuples permitted in a single evaluation request (maximum 20 tuples unless explicitly documented and protected).
- Engineers MUST NOT pass raw, unvalidated client-supplied tuples directly into `fgaClient.check()` or `fgaClient.listObjects()` as `contextualTuples`.
- Code SHOULD validate contextual tuples as an acyclic directed graph (DAG) prior to FGA submission to preemptively fail closed on intentional recursion loops.
- Services MUST enforce strict, non-negotiable request timeouts (maximum 250ms for synchronous authorization calls) using contextual AbortControllers or deadlines.
- Components NEVER permit arbitrary relations or wildcards in user-supplied contextual tuples; tuple subjects, objects, and relations MUST conform to a strict, pre-compiled whitelist schema.

## Bad vs Good Implementations
### Adversarial Contextual Tuple Forwarding vs Graph-Bounded FGA Check

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly forwards unvalidated, unbounded client contextual tuples to OpenFGA. An adversary can pass a self-referential or deeply chained set of relations that forces exponential graph expansion, exhausting memory and CPU in the authorization worker pool.
```typescript
import { OpenFgaClient, type ClientCheckRequest } from '@openfga/sdk';

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

// ANTI-PATTERN: Forwards arbitrary user-controlled contextual tuples directly.
// Allows cyclic hierarchies (e.g. A in B, B in A) or deep nesting chains (1000 items)
// leading to server thread exhaustion and catastrophic FGA backtracking.
export async function evaluateAccess(
  user: string,
  relation: string,
  object: string,
  untrustedContextTuples: Array<{ user: string; relation: string; object: string }>
): Promise<boolean> {
  const response = await fgaClient.check({
    user,
    relation,
    object,
    contextualTuples: untrustedContextTuples,
  });
  return Boolean(response.allowed);
}
```

#### Production Standard (Correct)
> **Standard**: Enforces a strict upper bound on contextual tuple count, validates allowed relations against an invariant allowlist, runs pre-flight cycle and depth limit verification, and enforces a deterministic 250ms timeout abort signal to neutralize DoS attack vectors.
```typescript
import { OpenFgaClient, type ClientCheckRequest } from '@openfga/sdk';

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

const MAX_CONTEXTUAL_TUPLES = 20;
const MAX_TRANSITIVE_DEPTH = 3;
const ALLOWED_RELATIONS = new Set(['parent', 'viewer', 'editor', 'member']);
const CHECK_TIMEOUT_MS = 250;

export interface ContextTuple {
  user: string;
  relation: string;
  object: string;
}

function validateContextualGraph(tuples: ContextTuple[]): void {
  if (tuples.length > MAX_CONTEXTUAL_TUPLES) {
    throw new Error(`Contextual tuple count exceeds maximum limit: ${MAX_CONTEXTUAL_TUPLES}`);
  }

  const adj = new Map<string, string[]>();
  for (const t of tuples) {
    if (!ALLOWED_RELATIONS.has(t.relation)) {
      throw new Error(`Disallowed relation in contextual tuple: ${t.relation}`);
    }
    const neighbors = adj.get(t.user) ?? [];
    neighbors.push(t.object);
    adj.set(t.user, neighbors);
  }

  // Detect cycles and depth using DFS
  const visited = new Set<string>();
  const inStack = new Set<string>();

  function dfs(node: string, depth: number): void {
    if (depth > MAX_TRANSITIVE_DEPTH) {
      throw new Error(`Contextual graph depth exceeds maximum limit of ${MAX_TRANSITIVE_DEPTH}`);
    }
    visited.add(node);
    inStack.add(node);

    for (const neighbor of adj.get(node) ?? []) {
      if (inStack.has(neighbor)) {
        throw new Error(`Cycle detected in contextual tuples: ${node} -> ${neighbor}`);
      }
      if (!visited.has(neighbor)) {
        dfs(neighbor, depth + 1);
      }
    }
    inStack.delete(node);
  }

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

export async function evaluateAccess(
  user: string,
  relation: string,
  object: string,
  rawTuples: ContextTuple[]
): Promise<boolean> {
  validateContextualGraph(rawTuples);

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

  try {
    const response = await fgaClient.check(
      {
        user,
        relation,
        object,
        contextualTuples: rawTuples,
      },
      { signal: controller.signal }
    );
    return Boolean(response.allowed);
  } finally {
    clearTimeout(timeout);
  }
}
```

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 Contextual Tuple Graph Recursion and Depth Limiter

OpenFGA Contextual Tuple Graph Recursion and Depth Limiter defines an industrial-grade behavioral standard for security engineering. Enforces strict structural validation, depth bounding, and cycle detection on ad-hoc contextual tuples passed to OpenFGA Check and ListObjects operations. Unbounded or cyclic contextual tuples allow malicious actors to induce catastrophic ReBAC graph expansion, thread starvation, and service-level denial of service via adversarial graph structures. 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: Unvalidated Contextual Tuple Injection Causing ReBAC Catastrophic Backtracking and CPU 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 DriftUnvalidated Contextual Tuple Injection Causing ReBAC Catastrophic Backtracking and CPU 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 a hard upper bound on the number of contextual tuples permitted in a single evaluation request (maximum 20 tuples unless explicitly documented and protected).

Engineers MUST ALWAYS enforce a hard upper bound on the number of contextual tuples permitted in a single evaluation request (maximum 20 tuples unless explicitly documented and protected).

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 pass raw, unvalidated client-supplied tuples directly into `fgaClient.check()` or `fgaClient.listObjects()` as `contextualTuples`.

Engineers MUST NOT pass raw, unvalidated client-supplied tuples directly into `fgaClient.check()` or `fgaClient.listObjects()` as `contextualTuples`.

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 validate contextual tuples as an acyclic directed graph (DAG) prior to FGA submission to preemptively fail closed on intentional recursion loops.

Code SHOULD validate contextual tuples as an acyclic directed graph (DAG) prior to FGA submission to preemptively fail closed on intentional recursion loops.

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 enforce strict, non-negotiable request timeouts (maximum 250ms for synchronous authorization calls) using contextual AbortControllers or deadlines.

Services MUST enforce strict, non-negotiable request timeouts (maximum 250ms for synchronous authorization calls) using contextual AbortControllers or deadlines.

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 permit arbitrary relations or wildcards in user-supplied contextual tuples

Components NEVER permit arbitrary relations or wildcards in user-supplied contextual tuples; tuple subjects, objects, and relations MUST conform to a strict, pre-compiled whitelist schema.

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 Recursion and Depth Limiter critical for AI coding assistants?

Enforces strict structural validation, depth bounding, and cycle detection on ad-hoc contextual tuples passed to OpenFGA Check and ListObjects operations. Unbounded or cyclic contextual tuples allow malicious actors to induce catastrophic ReBAC graph expansion, thread starvation, and service-level denial of service via adversarial graph structures. 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 (Unvalidated Contextual Tuple Injection Causing ReBAC Catastrophic Backtracking and CPU 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