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

OpenFGA Contextual Tuple Graph Recursion Depth & Cycle Mitigation Guardrail

Enforces pre-evaluation cycle detection, bounded contextual tuple graph depth, and deterministic execution timeouts for OpenFGA authorization checks. Prevents fine-grained authorization clusters from thread starvation and distributed denial-of-service caused by circular references or deeply nested dynamic relation expansions.

Prohibited Anti-Pattern: Unvalidated Contextual Tuples Triggering Circular Graph Traversal and Authorization Cluster Starvation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Contextual Tuple Graph Recursion Depth & Cycle Mitigation Guardrail - Enforces pre-evaluation cycle detection, bounded contextual tuple graph depth, and deterministic execution timeouts for OpenFGA authorization checks. Prevents fine-grained authorization clusters from thread starvation and distributed denial-of-service caused by circular references or deeply nested dynamic relation expansions.
globs: src/auth/**/*.{ts,tsx}, src/security/**/*.{ts,tsx}, src/middleware/**/*.{ts,tsx}, src/services/auth/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuple-cycle-depth-mitigation"
---

# OpenFGA Contextual Tuple Graph Recursion Depth & Cycle Mitigation Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unvalidated Contextual Tuples Triggering Circular Graph Traversal and Authorization Cluster Starvation

## System Constraints
You are a Principal Software Architect enforcing OpenFGA authorization resiliency and security guardrails. Mandate pre-evaluation cycle detection, recursion depth constraints, contextual tuple payload size limits, and fail-closed timeout boundaries for all dynamic Relationship-Based Access Control (ReBAC) evaluations.

## Strict Guidelines
- Engineers MUST ALWAYS validate runtime contextual tuples for Directed Acyclic Graph (DAG) invariants via cycle detection before passing them to OpenFGA check evaluations.
- Engineers MUST NOT forward raw, untrusted user-supplied contextual tuples directly into OpenFGA client check or batch check calls without boundary enforcement.
- Code SHOULD strictly enforce maximum tuple limits (e.g., maximum 25 contextual tuples per evaluation) and wrap every check in a defensive AbortSignal with a strict timeout (e.g., <= 200ms).
- Services MUST configure OpenFGA clients with deterministic evaluation depth limits and catch resolution loop or timeout errors, defaulting to an explicit fail-closed access denial.
- Components NEVER construct self-referential or reciprocal relationship tuples (e.g., `user:X` related to `group:Y` where `group:Y` is concurrently declared a parent of `group:X`) within the contextual scope.

## Bad vs Good Implementations
### Contextual Tuple Cycle Detection and Depth Bounded Check

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Contextual tuples are directly forwarded to OpenFGA without validating graph topology or enforcing boundaries. Malicious or misconfigured requests can introduce cyclic dependencies or excessive depth, causing OpenFGA evaluation goroutines to stall, consume high CPU/memory, and exhaust the authorization cluster's connection pools.
```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: Forwards arbitrary contextual tuples directly from client request.
// Susceptible to circular graph loops (A -> B -> A) and unbounded recursion DoS.
export async function authorizeUserBad(reqBody: { 
  user: string; 
  relation: string; 
  object: string; 
  contextualTuples: Array<{ user: string; relation: string; object: string }> 
}): Promise<boolean> {
  const response = await fgaClient.check({
    user: reqBody.user,
    relation: reqBody.relation,
    object: reqBody.object,
    contextualTuples: reqBody.contextualTuples,
  });

  return response.allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: The hardened implementation bounds the number of contextual tuples, performs a topological depth-first cycle check to verify DAG invariants prior to remote dispatch, limits execution with an AbortSignal timeout, and guarantees fail-closed behavior on evaluation errors.
```typescript
import { OpenFgaClient, ClientCheckRequest, TupleKey } 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 AUTH_CHECK_TIMEOUT_MS = 200;

export class CyclicRelationshipError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'CyclicRelationshipError';
  }
}

function assertNoContextualCycles(tuples: TupleKey[]): void {
  const adjacency = new Map<string, string[]>();
  for (const { user, object } of tuples) {
    if (user === object) {
      throw new CyclicRelationshipError(`Self-referential loop detected: ${user}`);
    }
    const existing = adjacency.get(user) ?? [];
    existing.push(object);
    adjacency.set(user, existing);
  }

  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) ?? [];
    for (const neighbor of neighbors) {
      if (!visited.has(neighbor) && hasCycle(neighbor)) {
        return true;
      } else 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 CyclicRelationshipError(`Cyclic relationship graph detected involving node: ${node}`);
    }
  }
}

export async function authorizeUser(
  user: string,
  relation: string,
  object: string,
  contextualTuples: TupleKey[] = []
): Promise<boolean> {
  if (contextualTuples.length > MAX_CONTEXTUAL_TUPLES) {
    throw new Error(`Contextual tuple threshold exceeded: maximum ${MAX_CONTEXTUAL_TUPLES} allowed`);
  }

  assertNoContextualCycles(contextualTuples);

  const abortController = new AbortController();
  const timeout = setTimeout(() => abortController.abort(), AUTH_CHECK_TIMEOUT_MS);

  try {
    const payload: ClientCheckRequest = {
      user,
      relation,
      object,
      contextualTuples,
    };

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

    return response.allowed ?? false;
  } catch (error) {
    // Fail-closed on timeout, cyclic traversal, or evaluation depth errors
    return false;
  } finally {
    clearTimeout(timeout);
  }
}
```

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 Contextual Tuple Graph Recursion Depth & Cycle Mitigation Guardrail

OpenFGA Contextual Tuple Graph Recursion Depth & Cycle Mitigation Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces pre-evaluation cycle detection, bounded contextual tuple graph depth, and deterministic execution timeouts for OpenFGA authorization checks. Prevents fine-grained authorization clusters from thread starvation and distributed denial-of-service caused by circular references or deeply nested dynamic relation expansions. 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 Tuples Triggering Circular Graph Traversal and Authorization Cluster 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 Tuples Triggering Circular Graph Traversal and Authorization Cluster 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 validate runtime contextual tuples for Directed Acyclic Graph (DAG) invariants via cycle detection before passing them to OpenFGA check evaluations.

Engineers MUST ALWAYS validate runtime contextual tuples for Directed Acyclic Graph (DAG) invariants via cycle detection before passing them to 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.
2

Engineers MUST NOT forward raw, untrusted user-supplied contextual tuples directly into OpenFGA client check or batch check calls without boundary enforcement.

Engineers MUST NOT forward raw, untrusted user-supplied contextual tuples directly into OpenFGA client check or batch check calls without boundary enforcement.

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 strictly enforce maximum tuple limits (e.g., maximum 25 contextual tuples per evaluation) and wrap every check in a defensive AbortSignal with a strict timeout (e.g., <= 200ms).

Code SHOULD strictly enforce maximum tuple limits (e.g., maximum 25 contextual tuples per evaluation) and wrap every check in a defensive AbortSignal with a strict timeout (e.g., <= 200ms).

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 OpenFGA clients with deterministic evaluation depth limits and catch resolution loop or timeout errors, defaulting to an explicit fail-closed access denial.

Services MUST configure OpenFGA clients with deterministic evaluation depth limits and catch resolution loop or timeout errors, defaulting to an explicit fail-closed access denial.

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 self-referential or reciprocal relationship tuples (e.g., `user

Components NEVER construct self-referential or reciprocal relationship tuples (e.g., `user:X` related to `group:Y` where `group:Y` is concurrently declared a parent of `group:X`) within the contextual scope.

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

Enforces pre-evaluation cycle detection, bounded contextual tuple graph depth, and deterministic execution timeouts for OpenFGA authorization checks. Prevents fine-grained authorization clusters from thread starvation and distributed denial-of-service caused by circular references or deeply nested dynamic relation expansions. 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 Tuples Triggering Circular Graph Traversal and Authorization Cluster 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