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

OpenFGA Contextual Tuple Graph Traversal & Cycle Guardrail

Enforces pre-flight Directed Acyclic Graph (DAG) cycle detection, strict contextual tuple cardinality limits, and deterministic traversal timeouts for OpenFGA ReBAC evaluation. Prevents catastrophic recursive graph explosion, CPU exhaustion, and multi-tenant denial of service during dynamic contextual permission checks.

Prohibited Anti-Pattern: Unbounded or Cyclical Contextual Tuples Injected Directly into OpenFGA Check API

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Contextual Tuple Graph Traversal & Cycle Guardrail - Enforces pre-flight Directed Acyclic Graph (DAG) cycle detection, strict contextual tuple cardinality limits, and deterministic traversal timeouts for OpenFGA ReBAC evaluation. Prevents catastrophic recursive graph explosion, CPU exhaustion, and multi-tenant denial of service during dynamic contextual permission checks.
globs: src/**/auth/**/*.ts, src/**/fga/**/*.ts, src/**/permissions/**/*.ts, src/**/guards/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuple-traversal-cycle-guardrail"
---

# OpenFGA Contextual Tuple Graph Traversal & Cycle Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded or Cyclical Contextual Tuples Injected Directly into OpenFGA Check API

## System Constraints
You are a Principal Security Architect enforcing zero-trust OpenFGA authorization invariants. You must prevent recursive graph traversal denial of service and bounded sub-millisecond evaluation failures by enforcing DAG cycle validation, strict contextual tuple cardinality caps (max 20 tuples), and non-negotiable request timeouts on all OpenFGA dynamic check requests.

## Strict Guidelines
- Engineers MUST ALWAYS run in-memory DAG cycle detection on dynamic contextual tuples prior to invoking OpenFGA client check methods.
- Engineers MUST NOT pass unsanitized, user-supplied parent-child hierarchies or delegation chains as contextual tuples without schema validation.
- Services MUST bound contextual tuple cardinality to a hard maximum (e.g., <= 20 tuples) per authorization check to prevent combinatorial traversal explosion.
- Services MUST enforce strict, sub-millisecond or low-millisecond timeouts (maximum 100ms) with AbortController on all remote OpenFGA check evaluations.
- Components NEVER fall back to fail-open authorization if contextual tuple validation, graph traversal, or the OpenFGA client call times out or throws an error.

## Bad vs Good Implementations
### Contextual Tuple Graph Cycle Guardrail & Timeout Enforcement

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Contextual tuples are passed directly from caller input without cardinality bounding, graph cycle validation, or execution timeouts. If a caller inputs a cyclic hierarchy (e.g., A is parent of B, B is parent of A), the OpenFGA query engine performs recursive graph traversals leading to latency spikes, resource exhaustion, or hanging requests without fail-safe bounds.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

// ANTI-PATTERN: Direct injection of unbounded, unvalidated contextual tuples
export async function checkAccess(userId: string, relation: string, docId: string, parentChains: Array<{ parent: string; child: string }>) {
  // Dangerous: Arbitrary number of contextual tuples directly mapped without cycle detection
  const contextualTuples = parentChains.map((p) => ({
    user: `document:${p.parent}`,
    relation: 'parent',
    object: `document:${p.child}`,
  }));

  // Unbounded execution time; a cyclic relationship (A -> B -> A) causes graph traversal explosion or timeouts
  const { allowed } = await fgaClient.check({
    user: `user:${userId}`,
    relation,
    object: `document:${docId}`,
    contextualTuples,
  });

  return allowed;
}
```

#### Production Standard (Correct)
> **Standard**: Enforces a strict upper bound of 20 contextual tuples, verifies DAG topology through cycle detection via DFS before invoking OpenFGA, bounds the network check to 50ms with an AbortController, and strictly fails closed on errors or timeouts.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

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

const MAX_CONTEXTUAL_TUPLES = 20;
const EVALUATION_TIMEOUT_MS = 50;

interface Edge {
  parent: string;
  child: string;
}

function assertNoCycles(edges: Edge[]): void {
  const adj = new Map<string, string[]>();
  for (const { parent, child } of edges) {
    if (!adj.has(parent)) adj.set(parent, []);
    adj.get(parent)!.push(child);
  }

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

  function dfs(node: string): boolean {
    visited.add(node);
    inStack.add(node);
    for (const neighbor of adj.get(node) || []) {
      if (!visited.has(neighbor) && dfs(neighbor)) return true;
      if (inStack.has(neighbor)) return true;
    }
    inStack.delete(node);
    return false;
  }

  for (const node of adj.keys()) {
    if (!visited.has(node) && dfs(node)) {
      throw new Error(`Cycle detected in contextual hierarchy at node: ${node}`);
    }
  }
}

export async function checkAccess(
  userId: string,
  relation: string,
  docId: string,
  parentChains: Edge[]
): Promise<boolean> {
  // Invariant 1: Enforce hard cardinality cap
  if (parentChains.length > MAX_CONTEXTUAL_TUPLES) {
    throw new Error(`Contextual tuple limit exceeded: ${parentChains.length} > ${MAX_CONTEXTUAL_TUPLES}`);
  }

  // Invariant 2: Directed Acyclic Graph validation before dispatch
  assertNoCycles(parentChains);

  const contextualTuples = parentChains.map((p) => ({
    user: `document:${p.parent}`,
    relation: 'parent',
    object: `document:${p.child}`,
  }));

  // Invariant 3: Deterministic bounded timeout with fail-closed semantics
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), EVALUATION_TIMEOUT_MS);

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

    const response = await fgaClient.check(payload, {
      signal: controller.signal,
    });

    return response.allowed ?? false;
  } catch (error) {
    // Invariant 4: Fail-closed on traversal timeout or graph resolution error
    return false;
  } finally {
    clearTimeout(timeout);
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA Contextual Tuple Graph Traversal & Cycle Guardrail

OpenFGA Contextual Tuple Graph Traversal & Cycle Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces pre-flight Directed Acyclic Graph (DAG) cycle detection, strict contextual tuple cardinality limits, and deterministic traversal timeouts for OpenFGA ReBAC evaluation. Prevents catastrophic recursive graph explosion, CPU exhaustion, and multi-tenant denial of service during dynamic contextual permission checks. 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 or Cyclical Contextual Tuples Injected Directly into OpenFGA Check API 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 or Cyclical Contextual Tuples Injected Directly into OpenFGA Check APICritical
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 in-memory DAG cycle detection on dynamic contextual tuples prior to invoking OpenFGA client check methods.

Engineers MUST ALWAYS run in-memory DAG cycle detection on dynamic contextual tuples prior to invoking OpenFGA client check 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 pass unsanitized, user-supplied parent-child hierarchies or delegation chains as contextual tuples without schema validation.

Engineers MUST NOT pass unsanitized, user-supplied parent-child hierarchies or delegation chains as contextual tuples without schema validation.

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

Services MUST bound contextual tuple cardinality to a hard maximum (e.g., <= 20 tuples) per authorization check to prevent combinatorial traversal explosion.

Services MUST bound contextual tuple cardinality to a hard maximum (e.g., <= 20 tuples) per authorization check to prevent combinatorial traversal explosion.

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, sub-millisecond or low-millisecond timeouts (maximum 100ms) with AbortController on all remote OpenFGA check evaluations.

Services MUST enforce strict, sub-millisecond or low-millisecond timeouts (maximum 100ms) with AbortController on all remote OpenFGA check evaluations.

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 fall back to fail-open authorization if contextual tuple validation, graph traversal, or the OpenFGA client call times out or throws an error.

Components NEVER fall back to fail-open authorization if contextual tuple validation, graph traversal, or the OpenFGA client call times out or throws an error.

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 & Cycle Guardrail critical for AI coding assistants?

Enforces pre-flight Directed Acyclic Graph (DAG) cycle detection, strict contextual tuple cardinality limits, and deterministic traversal timeouts for OpenFGA ReBAC evaluation. Prevents catastrophic recursive graph explosion, CPU exhaustion, and multi-tenant denial of service during dynamic contextual permission checks. 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 or Cyclical Contextual Tuples Injected Directly into OpenFGA Check API) 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