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

OpenFGA Contextual Tuple Traversal Depth and Cycle Bound Guardrail

Fences recursive graph evaluation in OpenFGA authorization checks by enforcing bounded contextual tuple cardinalities, strictly prohibiting circular group nesting, and preventing unbounded relation transitive walks. Uncontrolled contextual tuples injected at evaluation time trigger exponential sub-graph expansions, unconstrained database fan-out, and high-cardinality authorization-induced latency degradation.

Prohibited Anti-Pattern: Injecting Dynamic Ephemeral Contextual Tuples Without Invariant Depth Bounds or Cycle Validation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Contextual Tuple Traversal Depth and Cycle Bound Guardrail - Fences recursive graph evaluation in OpenFGA authorization checks by enforcing bounded contextual tuple cardinalities, strictly prohibiting circular group nesting, and preventing unbounded relation transitive walks. Uncontrolled contextual tuples injected at evaluation time trigger exponential sub-graph expansions, unconstrained database fan-out, and high-cardinality authorization-induced latency degradation.
globs: src/**/authz/**/*.{ts,js}, src/**/services/**/*.{ts,js}, src/**/guards/**/*.{ts,js}, src/**/policies/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuple-traversal-guardrail"
---

# OpenFGA Contextual Tuple Traversal Depth and Cycle Bound Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Injecting Dynamic Ephemeral Contextual Tuples Without Invariant Depth Bounds or Cycle Validation

## System Constraints
You are a Principal Engineer enforcing production invariants on OpenFGA Relationship-Based Access Control (ReBAC). You must eliminate unchecked contextual tuple injection, enforce strict limits on contextual tuple array sizes, eliminate cyclic user/group edges prior to evaluation, and enforce deterministic timeouts and maximum resolution depth on all Check, ListObjects, and Expand operations.

## Strict Guidelines
- Engineers MUST ALWAYS sanitize and bound contextual tuple arrays to a strict maximum (e.g., <= 100 tuples) before invoking OpenFGA Client SDK methods.
- Engineers MUST NOT construct self-referential or cyclic transitive relation paths (e.g., group:A member of group:B member of group:A) inside contextual tuples.
- Code MUST validate contextual tuple graph acyclicity using an in-memory Tarjan/Kahn topological sort or visited-set cycle detector before passing them to the OpenFGA evaluation engine.
- Services MUST enforce an explicit AbortSignal deadline (e.g., max 150ms) on all OpenFGA `check` and `batchCheck` API calls to fail closed under high-depth expansion.
- Components NEVER execute raw `listObjects` queries with contextual tuples containing transitive wildcard definitions or unbounded inherited relation closures without pagination and depth assertions.

## Bad vs Good Implementations
### Unbounded Contextual Tuples with Cyclic Vulnerability vs Directed Acyclic Graph (DAG) Bounded Check

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Untrusted contextual tuples are passed directly to OpenFGA without size bounds, cycle checks, or timeouts. A cyclic relation graph or hundreds of recursive group-nesting tuples causes OpenFGA to perform an unbounded BFS/DFS traversal, triggering cascading timeout failures across the authorization layer.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

// Anti-pattern: Forwarding client-supplied contextual tuples directly into OpenFGA Check.
// Allows cyclic dependencies (e.g., group:1 -> group:2 -> group:1) and cardinality explosion
// causing server thread exhaustion and authorization latency timeouts.
export async function authorizeUserResourceAccess(
  userId: string,
  relation: string,
  resourceId: string,
  untrustedContextualTuples: Array<{ user: string; relation: string; object: string }>
) {
  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation,
    object: `document:${resourceId}`,
    contextualTuples: untrustedContextualTuples,
  });

  return response.allowed;
}
```

#### Production Standard (Correct)
> **Standard**: Enforces strict limits on contextual tuple array size (MAX_CONTEXTUAL_TUPLES), pre-validates against cyclic dependency graphs via depth-first cycle detection, executes with a strict 150ms AbortSignal deadline, and consistently fails closed upon authorization timeouts or graph validation errors.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

const MAX_CONTEXTUAL_TUPLES = 50;
const AUTHZ_TIMEOUT_MS = 150;

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

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

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

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

  for (const node of adjList.keys()) {
    if (!visited.has(node) && hasCycle(node)) {
      throw new Error(`Cyclic relation detected in contextual tuples at node: ${node}`);
    }
  }
}

export async function authorizeUserResourceAccess(
  fgaClient: OpenFgaClient,
  userId: string,
  relation: string,
  resourceId: string,
  rawContextualTuples: TupleKey[]
): Promise<boolean> {
  if (rawContextualTuples.length > MAX_CONTEXTUAL_TUPLES) {
    throw new Error(`Contextual tuple cardinality limit exceeded: ${rawContextualTuples.length} > ${MAX_CONTEXTUAL_TUPLES}`);
  }

  assertAcyclicContextualGraph(rawContextualTuples);

  const checkPayload: ClientCheckRequest = {
    user: `user:${userId}`,
    relation,
    object: `document:${resourceId}`,
    contextualTuples: rawContextualTuples,
  };

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

  try {
    const response = await fgaClient.check(checkPayload, {
      signal: controller.signal,
    });
    return Boolean(response.allowed);
  } catch (err: unknown) {
    // Fail closed on evaluation timeout, cycle abort, or backend transport errors
    return false;
  } finally {
    clearTimeout(timeoutId);
  }
}
```

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 Traversal Depth and Cycle Bound Guardrail

OpenFGA Contextual Tuple Traversal Depth and Cycle Bound Guardrail defines an industrial-grade behavioral standard for backend engineering. Fences recursive graph evaluation in OpenFGA authorization checks by enforcing bounded contextual tuple cardinalities, strictly prohibiting circular group nesting, and preventing unbounded relation transitive walks. Uncontrolled contextual tuples injected at evaluation time trigger exponential sub-graph expansions, unconstrained database fan-out, and high-cardinality authorization-induced latency degradation. 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 Dynamic Ephemeral Contextual Tuples Without Invariant Depth Bounds or Cycle Validation 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 Dynamic Ephemeral Contextual Tuples Without Invariant Depth Bounds or Cycle ValidationCritical
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 sanitize and bound contextual tuple arrays to a strict maximum (e.g., <= 100 tuples) before invoking OpenFGA Client SDK methods.

Engineers MUST ALWAYS sanitize and bound contextual tuple arrays to a strict maximum (e.g., <= 100 tuples) before invoking OpenFGA Client SDK methods.

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 construct self-referential or cyclic transitive relation paths (e.g., group

Engineers MUST NOT construct self-referential or cyclic transitive relation paths (e.g., group:A member of group:B member of group:A) inside 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.
3

Code MUST validate contextual tuple graph acyclicity using an in-memory Tarjan/Kahn topological sort or visited-set cycle detector before passing them to the OpenFGA evaluation engine.

Code MUST validate contextual tuple graph acyclicity using an in-memory Tarjan/Kahn topological sort or visited-set cycle detector before passing them to the OpenFGA evaluation engine.

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 an explicit AbortSignal deadline (e.g., max 150ms) on all OpenFGA `check` and `batchCheck` API calls to fail closed under high-depth expansion.

Services MUST enforce an explicit AbortSignal deadline (e.g., max 150ms) on all OpenFGA `check` and `batchCheck` API calls to fail closed under high-depth 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.
5

Components NEVER execute raw `listObjects` queries with contextual tuples containing transitive wildcard definitions or unbounded inherited relation closures without pagination and depth assertions.

Components NEVER execute raw `listObjects` queries with contextual tuples containing transitive wildcard definitions or unbounded inherited relation closures without pagination and depth assertions.

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

Fences recursive graph evaluation in OpenFGA authorization checks by enforcing bounded contextual tuple cardinalities, strictly prohibiting circular group nesting, and preventing unbounded relation transitive walks. Uncontrolled contextual tuples injected at evaluation time trigger exponential sub-graph expansions, unconstrained database fan-out, and high-cardinality authorization-induced latency degradation. 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 Dynamic Ephemeral Contextual Tuples Without Invariant Depth Bounds or Cycle Validation) 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