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

OpenFGA 1.6 Contextual Tuple Traversal Depth and Cycle Detection Invariant

Enforces strict pre-flight acyclicity validation, traversal depth bounding, and bounded context timeouts when submitting contextual tuples to OpenFGA 1.6 check APIs. Prevents denial-of-service, goroutine starvation, and catastrophic tail-latency degradation caused by circular references or deeply nested dynamic relation graphs in ReBAC authorization pipelines.

Prohibited Anti-Pattern: Unbounded Contextual Tuple Graph Injection Leading to ReBAC Cycle Exploitation and Algorithmic DoS

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA 1.6 Contextual Tuple Traversal Depth and Cycle Detection Invariant - Enforces strict pre-flight acyclicity validation, traversal depth bounding, and bounded context timeouts when submitting contextual tuples to OpenFGA 1.6 check APIs. Prevents denial-of-service, goroutine starvation, and catastrophic tail-latency degradation caused by circular references or deeply nested dynamic relation graphs in ReBAC authorization pipelines.
globs: src/auth/**/*.{ts,js}, src/services/auth/**/*.{ts,js}, src/middleware/**/*.{ts,js}, src/lib/fga/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuple-depth-cycle-guardrail"
---

# OpenFGA 1.6 Contextual Tuple Traversal Depth and Cycle Detection Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded Contextual Tuple Graph Injection Leading to ReBAC Cycle Exploitation and Algorithmic DoS

## System Constraints
You are a Principal Software Architect enforcing zero-trust authorization resilience standards under OpenFGA 1.6. You must prevent graph-traversal algorithmic denial-of-service conditions. When contextual tuples are utilized in ReBAC evaluation pipelines, you MUST mandate deterministic client-side DAG verification, strict contextual tuple quantity caps, explicit traversal depth limits, strict AbortSignal timeouts, and fail-closed error handling for cyclic graph states.

## Strict Guidelines
- Engineers MUST ALWAYS enforce a hard cap on dynamic contextual tuples (max 20 tuples per check invocation) before dispatching to the OpenFGA client.
- Engineers MUST ALWAYS run an in-memory directed cycle check (e.g., depth-first search or topological sort) on contextual tuples containing transitive relations prior to calling OpenFGA check or batchCheck APIs.
- Engineers MUST configure an explicit timeout using AbortController (strictly <= 200ms) for all OpenFGA authorization checks to prevent p99 tail-latency cascade across calling services.
- Services MUST fail closed (default deny: { allowed: false }) whenever OpenFGA returns resolve_node_limit errors, cycle detection warnings, or contextual traversal timeouts.
- Engineers MUST NOT allow unauthenticated or client-controlled arbitrary subject/relation/object tuples to be merged into contextual tuples without strict schema-level whitelist sanitization.
- Code SHOULD enforce a maximum contextual chain depth limit (<= 5 levels of subject-relation indirection) before dispatching requests to OpenFGA 1.6.

## Bad vs Good Implementations
### Unbounded Contextual Tuples with Circular Reference Vulnerability vs. Bounded DAG-Validated Context

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Untrusted dynamic tuples are directly forwarded to OpenFGA without cycle or depth verification. An attacker can construct recursive transitive relations (e.g., folder:A parent folder:B, folder:B parent folder:A) or massive nested chains, driving OpenFGA graph resolution nodes to exhaustion, saturating the OpenFGA worker pool, and triggering DoS without request timeouts.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

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

// ANTI-PATTERN: Directly merging arbitrary client contextual tuples
// without cycle detection, depth limits, or timeout budgets.
export async function authorizeUser(req: { 
  user: string; 
  relation: string; 
  object: string; 
  dynamicTuples?: Array<{ user: string; relation: string; object: string }> 
}): Promise<boolean> {
  const checkPayload: ClientCheckRequest = {
    user: req.user,
    relation: req.relation,
    object: req.object,
    contextualTuples: req.dynamicTuples ?? [], // VULNERABILITY: Cyclic or deep chains trigger unbounded graph traversal DoS
  };

  // No timeout: catastrophic tail latencies lock the event loop / HTTP connection
  const response = await fgaClient.check(checkPayload);
  return response.allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: Implements pre-flight DAG verification using cycle detection and depth checking, caps the contextual tuple count to 20, binds evaluation to an explicit 150ms AbortSignal budget, and strictly fails closed when cycles, depth limits, or traversal timeouts are encountered.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

const MAX_CONTEXTUAL_TUPLES = 20;
const MAX_TRAVERSAL_DEPTH = 5;
const CHECK_TIMEOUT_MS = 150;

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

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

function validateAcyclicBoundedGraph(tuples: FgaTuple[], maxDepth: number): void {
  if (tuples.length > MAX_CONTEXTUAL_TUPLES) {
    throw new Error(`Contextual tuple limit exceeded: ${tuples.length} > ${MAX_CONTEXTUAL_TUPLES}`);
  }

  const adj = new Map<string, string[]>();
  for (const t of tuples) {
    const targets = adj.get(t.user) ?? [];
    targets.push(t.object);
    adj.set(t.user, targets);
  }

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

  function dfs(node: string, depth: number): void {
    if (depth > maxDepth) {
      throw new Error(`Graph depth invariant violated: depth > ${maxDepth}`);
    }
    visited.add(node);
    recStack.add(node);

    const neighbors = adj.get(node) ?? [];
    for (const neighbor of neighbors) {
      if (!visited.has(neighbor)) {
        dfs(neighbor, depth + 1);
      } else if (recStack.has(neighbor)) {
        throw new Error(`Contextual cycle detected at relation node: ${node} -> ${neighbor}`);
      }
    }
    recStack.delete(node);
  }

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

export async function authorizeUser(req: {
  user: string;
  relation: string;
  object: string;
  dynamicTuples?: FgaTuple[];
}): Promise<boolean> {
  const dynamicTuples = req.dynamicTuples ?? [];

  try {
    validateAcyclicBoundedGraph(dynamicTuples, MAX_TRAVERSAL_DEPTH);
  } catch (validationErr) {
    // Fail closed on graph cycle or depth anomalies
    return false;
  }

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

  try {
    const checkPayload: ClientCheckRequest = {
      user: req.user,
      relation: req.relation,
      object: req.object,
      contextualTuples: dynamicTuples,
    };

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

    return response.allowed ?? false;
  } catch (error) {
    // Fail closed on timeout, OpenFGA node limit exhaustion, or network abort
    return false;
  } finally {
    clearTimeout(timeout);
  }
}
```

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 Contextual Tuple Traversal Depth and Cycle Detection Invariant

OpenFGA 1.6 Contextual Tuple Traversal Depth and Cycle Detection Invariant defines an industrial-grade behavioral standard for security engineering. Enforces strict pre-flight acyclicity validation, traversal depth bounding, and bounded context timeouts when submitting contextual tuples to OpenFGA 1.6 check APIs. Prevents denial-of-service, goroutine starvation, and catastrophic tail-latency degradation caused by circular references or deeply nested dynamic relation graphs in ReBAC authorization pipelines. 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 Graph Injection Leading to ReBAC Cycle Exploitation and Algorithmic DoS 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 Graph Injection Leading to ReBAC Cycle Exploitation and Algorithmic DoSCritical
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 cap on dynamic contextual tuples (max 20 tuples per check invocation) before dispatching to the OpenFGA client.

Engineers MUST ALWAYS enforce a hard cap on dynamic contextual tuples (max 20 tuples per check invocation) before dispatching to the OpenFGA client.

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 ALWAYS run an in-memory directed cycle check (e.g., depth-first search or topological sort) on contextual tuples containing transitive relations prior to calling OpenFGA check or batchCheck APIs.

Engineers MUST ALWAYS run an in-memory directed cycle check (e.g., depth-first search or topological sort) on contextual tuples containing transitive relations prior to calling OpenFGA check or batchCheck 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

Engineers MUST configure an explicit timeout using AbortController (strictly <= 200ms) for all OpenFGA authorization checks to prevent p99 tail-latency cascade across calling services.

Engineers MUST configure an explicit timeout using AbortController (strictly <= 200ms) for all OpenFGA authorization checks to prevent p99 tail-latency cascade across calling services.

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 fail closed (default deny

Services MUST fail closed (default deny: { allowed: false }) whenever OpenFGA returns resolve_node_limit errors, cycle detection warnings, or contextual traversal timeouts.

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

Engineers MUST NOT allow unauthenticated or client-controlled arbitrary subject/relation/object tuples to be merged into contextual tuples without strict schema-level whitelist sanitization.

Engineers MUST NOT allow unauthenticated or client-controlled arbitrary subject/relation/object tuples to be merged into contextual tuples without strict schema-level whitelist sanitization.

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.
6

Code SHOULD enforce a maximum contextual chain depth limit (<= 5 levels of subject-relation indirection) before dispatching requests to OpenFGA 1.6.

Code SHOULD enforce a maximum contextual chain depth limit (<= 5 levels of subject-relation indirection) before dispatching requests to OpenFGA 1.6.

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

Enforces strict pre-flight acyclicity validation, traversal depth bounding, and bounded context timeouts when submitting contextual tuples to OpenFGA 1.6 check APIs. Prevents denial-of-service, goroutine starvation, and catastrophic tail-latency degradation caused by circular references or deeply nested dynamic relation graphs in ReBAC authorization pipelines. 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 Graph Injection Leading to ReBAC Cycle Exploitation and Algorithmic DoS) 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