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

OpenFGA 1.6 Cycle-Safe Contextual Tuple Traversal and Depth Bounding

Enforces strict bounded graph traversal and cycle prevention when evaluating OpenFGA 1.6 relationship checks with contextual tuples. Prevents recursive graph lookups, contextual tuple thrashing, and denial-of-service (DoS) latency spikes caused by circular graph hierarchies in high-concurrency ReBAC environments.

Prohibited Anti-Pattern: Injecting Unbounded or Cyclic Contextual Tuples into OpenFGA Check API Inducing Graph Explosion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA 1.6 Cycle-Safe Contextual Tuple Traversal and Depth Bounding - Enforces strict bounded graph traversal and cycle prevention when evaluating OpenFGA 1.6 relationship checks with contextual tuples. Prevents recursive graph lookups, contextual tuple thrashing, and denial-of-service (DoS) latency spikes caused by circular graph hierarchies in high-concurrency ReBAC environments.
globs: src/**/authz/**/*.ts, src/**/fga/**/*.ts, src/**/guards/**/*.ts, src/**/security/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-cycle-safe-contextual-traversal-guardrail"
---

# OpenFGA 1.6 Cycle-Safe Contextual Tuple Traversal and Depth Bounding

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Injecting Unbounded or Cyclic Contextual Tuples into OpenFGA Check API Inducing Graph Explosion

## System Constraints
You are a Principal Engineer enforcing OpenFGA 1.6 Contextual Tuple Traversal & Cycle-Safe Authorization. Mandate strict graph depth limits, explicit acyclic checks on contextual tuples, deterministic resolution timeouts, and total avoidance of circular ReBAC relation definitions that can cause catastrophic thread exhaustion or latency degradation.

## Strict Guidelines
- Engineers MUST ALWAYS validate that contextual tuples passed to `fgaClient.check()` or `fgaClient.batchCheck()` form a strict Directed Acyclic Graph (DAG) before invocation.
- Engineers MUST NOT inject unbounded or unvalidated dynamic contextual tuples originating from untrusted client payloads directly into OpenFGA authorization queries.
- Code MUST enforce a hard maximum limit on contextual tuples per check request (recommended maximum of 20 tuples) to prevent compute amplification.
- Services MUST configure explicit client-side timeouts (maximum 200ms) with `AbortSignal` for all contextual check operations to handle engine-level graph depth exhaustion gracefully.
- Components NEVER construct bidirectional delegation or circular containment relationships (e.g., `folder:A -> parent -> folder:B` and `folder:B -> parent -> folder:A`) via contextual tuples.

## Bad vs Good Implementations
### OpenFGA Contextual Tuple Graph Resolution Guard

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Contextual tuples are directly passed from input without cycle detection, length bounds, or query timeouts. An attacker or corrupted state can introduce a circular edge (A is parent of B, B is parent of A), forcing OpenFGA's sub-problem graph resolver into deep recursive traversal until internal depth limits abort, leading to latency exhaustion and denial of service.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

export async function authorizeAccess(userId: string, docId: string, clientContextTuples: Array<{ user: string; relation: string; object: string }>) {
  // VULNERABLE: Direct injection of unbounded, unvalidated contextual tuples
  // Potential for cyclic graph traversal (e.g., group A -> group B -> group A)
  // causing catastrophic latency degradation and engine thread pool starvation.
  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'can_view',
    object: `document:${docId}`,
    contextualTuples: clientContextTuples,
  });

  return response.allowed;
}
```

#### Production Standard (Correct)
> **Standard**: Implements pre-evaluation DAG cycle validation, bounds contextual tuple cardinality to a safe maximum, and wraps the OpenFGA call with an explicit 200ms timeout via AbortController, neutralizing infinite expansion and thread starvation attacks.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

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

function assertAcyclicContext(tuples: FgaTupleKey[]): void {
  const adjacency = new Map<string, Set<string>>();
  for (const { user, object } of tuples) {
    if (user === object) {
      throw new Error(`Self-referential contextual tuple detected: ${user}`);
    }
    if (!adjacency.has(user)) adjacency.set(user, new Set());
    adjacency.get(user)!.add(object);
  }

  const visited = new Set<string>();
  const recursionStack = new Set<string>();

  function hasCycle(node: string): boolean {
    visited.add(node);
    recursionStack.add(node);
    const neighbors = adjacency.get(node) || new Set();
    for (const neighbor of neighbors) {
      if (!visited.has(neighbor) && hasCycle(neighbor)) return true;
      if (recursionStack.has(neighbor)) return true;
    }
    recursionStack.delete(node);
    return false;
  }

  for (const node of adjacency.keys()) {
    if (!visited.has(node) && hasCycle(node)) {
      throw new Error(`Cycle detected in contextual tuples involving node: ${node}`);
    }
  }
}

export async function authorizeAccess(
  userId: string,
  docId: string,
  rawContextTuples: FgaTupleKey[]
): Promise<boolean> {
  if (rawContextTuples.length > MAX_CONTEXTUAL_TUPLES) {
    throw new Error(`Contextual tuples count exceeds hard ceiling of ${MAX_CONTEXTUAL_TUPLES}`);
  }

  assertAcyclicContext(rawContextTuples);

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

  try {
    const response = await fgaClient.check(
      {
        user: `user:${userId}`,
        relation: 'can_view',
        object: `document:${docId}`,
        contextualTuples: rawContextTuples,
      },
      { signal: controller.signal }
    );
    return Boolean(response.allowed);
  } catch (error: any) {
    if (error.name === 'AbortError') {
      throw new Error('Authorization evaluation timed out due to graph complexity');
    }
    throw error;
  } 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 1.6 Cycle-Safe Contextual Tuple Traversal and Depth Bounding

OpenFGA 1.6 Cycle-Safe Contextual Tuple Traversal and Depth Bounding defines an industrial-grade behavioral standard for security engineering. Enforces strict bounded graph traversal and cycle prevention when evaluating OpenFGA 1.6 relationship checks with contextual tuples. Prevents recursive graph lookups, contextual tuple thrashing, and denial-of-service (DoS) latency spikes caused by circular graph hierarchies in high-concurrency ReBAC environments. 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: Injecting Unbounded or Cyclic Contextual Tuples into OpenFGA Check API Inducing Graph Explosion 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 DriftInjecting Unbounded or Cyclic Contextual Tuples into OpenFGA Check API Inducing Graph ExplosionCritical
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 validate that contextual tuples passed to `fgaClient.check()` or `fgaClient.batchCheck()` form a strict Directed Acyclic Graph (DAG) before invocation.

Engineers MUST ALWAYS validate that contextual tuples passed to `fgaClient.check()` or `fgaClient.batchCheck()` form a strict Directed Acyclic Graph (DAG) before 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 inject unbounded or unvalidated dynamic contextual tuples originating from untrusted client payloads directly into OpenFGA authorization queries.

Engineers MUST NOT inject unbounded or unvalidated dynamic contextual tuples originating from untrusted client payloads directly into OpenFGA authorization queries.

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 enforce a hard maximum limit on contextual tuples per check request (recommended maximum of 20 tuples) to prevent compute amplification.

Code MUST enforce a hard maximum limit on contextual tuples per check request (recommended maximum of 20 tuples) to prevent compute amplification.

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 explicit client-side timeouts (maximum 200ms) with `AbortSignal` for all contextual check operations to handle engine-level graph depth exhaustion gracefully.

Services MUST configure explicit client-side timeouts (maximum 200ms) with `AbortSignal` for all contextual check operations to handle engine-level graph depth exhaustion gracefully.

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 construct bidirectional delegation or circular containment relationships (e.g., `folder

Components NEVER construct bidirectional delegation or circular containment relationships (e.g., `folder:A -> parent -> folder:B` and `folder:B -> parent -> folder:A`) via 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is OpenFGA 1.6 Cycle-Safe Contextual Tuple Traversal and Depth Bounding critical for AI coding assistants?

Enforces strict bounded graph traversal and cycle prevention when evaluating OpenFGA 1.6 relationship checks with contextual tuples. Prevents recursive graph lookups, contextual tuple thrashing, and denial-of-service (DoS) latency spikes caused by circular graph hierarchies in high-concurrency ReBAC environments. 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 (Injecting Unbounded or Cyclic Contextual Tuples into OpenFGA Check API Inducing Graph Explosion) 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