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

OpenFGA 1.8 Contextual Tuple Depth and Cycle Guardrail

Enforces strict structural constraints, acyclicity validation, and execution budgets on OpenFGA 1.8 contextual tuples and relationship queries. Prevents unbounded graph traversal, catastrophic algorithmic complexity, and goroutine/stack exhaustion in multi-tenant authorization evaluations.

Prohibited Anti-Pattern: Injecting Unbounded or Cyclic Contextual Tuples into Authorization Checks Without Pre-Evaluation Graph Constraints and Traversal Budgets

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA 1.8 Contextual Tuple Depth and Cycle Guardrail - Enforces strict structural constraints, acyclicity validation, and execution budgets on OpenFGA 1.8 contextual tuples and relationship queries. Prevents unbounded graph traversal, catastrophic algorithmic complexity, and goroutine/stack exhaustion in multi-tenant authorization evaluations.
globs: src/auth/**/*.{ts,js}, src/security/**/*.{ts,js}, src/services/fga/**/*.{ts,js}, src/middleware/auth/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-rebac-contextual-tuple-depth-cycle-limit-standard"
---

# OpenFGA 1.8 Contextual Tuple Depth and Cycle Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Injecting Unbounded or Cyclic Contextual Tuples into Authorization Checks Without Pre-Evaluation Graph Constraints and Traversal Budgets

## System Constraints
You are a Principal Security Architect enforcing the OpenFGA 1.8 ReBAC Contextual Tuple Depth & Cycle Limit Standard. You must mandate strict limits on contextual tuple size, enforce DAG acyclicity checks prior to dispatching authorization checks, configure explicit traversal deadlines with AbortSignal, and guarantee fail-closed semantics across all graph evaluations.

## Strict Guidelines
- Engineers MUST ALWAYS validate that contextual tuples form a strict Directed Acyclic Graph (DAG) using deterministic cycle detection before sending checks to OpenFGA.
- Engineers MUST ALWAYS enforce a strict upper bound on contextual tuples (default: maximum 25 tuples per request) to prevent evaluation payload amplification attacks.
- Engineers MUST NOT pass untrusted or cross-tenant user/object identifiers into contextual tuples without enforcing tenant isolation boundaries on both object and user namespaces.
- Services MUST ALWAYS bind OpenFGA check evaluations to an explicit request deadline using AbortSignal/context cancellation (maximum 150ms for synchronous authorization path).
- Components NEVER execute raw OpenFGA check calls with fallback to permissive access; all cycle errors, resolution-limit-exceeded codes, and timeouts MUST fail closed (deny access).

## Bad vs Good Implementations
### Contextual Tuple Validation and Bounded Check Execution

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Untrusted contextual tuples are passed directly to the OpenFGA engine without length validation, tenant isolation, or cycle detection. Cyclic relationships (e.g., docA parent of docB and docB parent of docA) cause graph traversal expansion, latency spikes, and potential stack exhaustion. Catch block dangerously falls back to allowing access instead of failing closed.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

// Flawed: Raw caller-provided contextual tuples forwarded with no depth, cycle, or size limits
export async function checkAccess(userId: string, objectId: string, relation: string, userContextTuples: Array<{ user: string; relation: string; object: string }>) {
  try {
    const response = await fgaClient.check({
      user: `user:${userId}`,
      relation,
      object: `document:${objectId}`,
      contextualTuples: userContextTuples, // Vulnerable to unbounded recursion and cycle DoS
    });
    return response.allowed ?? false;
  } catch (error) {
    // Anti-pattern: Soft error logging or non-deterministic fallback
    console.error('FGA Check failed, allowing fallback', error);
    return true;
  }
}
```

#### Production Standard (Correct)
> **Standard**: Enforces a strict tuple budget, runs deterministic cycle detection over contextual relationships before query dispatch, namespaces identifiers to enforce tenant boundaries, bounds latency with an AbortSignal, and rigorously fails closed on any traversal failure or timeout.
```typescript
import { OpenFgaClient, ClientCheckRequest } 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 CHECK_TIMEOUT_MS = 150;

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

function assertAcyclicContextualGraph(tuples: FgaTupleKey[]): void {
  if (tuples.length > MAX_CONTEXTUAL_TUPLES) {
    throw new Error(`Contextual tuple threshold exceeded: ${tuples.length} > ${MAX_CONTEXTUAL_TUPLES}`);
  }

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

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

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

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

export async function checkAccess(
  tenantId: string,
  userId: string,
  objectId: string,
  relation: string,
  contextualTuples: FgaTupleKey[] = []
): Promise<boolean> {
  const scopedObject = `${tenantId}:doc:${objectId}`;
  const scopedUser = `${tenantId}:user:${userId}`;

  // 1. Guard against unbounded depth and cycles before dispatch
  assertAcyclicContextualGraph(contextualTuples);

  // 2. Bound execution with explicit timeout to prevent goroutine exhaustion
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), CHECK_TIMEOUT_MS);

  try {
    const payload: ClientCheckRequest = {
      user: scopedUser,
      relation,
      object: scopedObject,
      contextualTuples: contextualTuples.map((t) => ({
        user: t.user.startsWith(`${tenantId}:`) ? t.user : `${tenantId}:${t.user}`,
        relation: t.relation,
        object: t.object.startsWith(`${tenantId}:`) ? t.object : `${tenantId}:${t.object}`,
      })),
    };

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

    return response.allowed === true;
  } catch (error: unknown) {
    // 3. Strict fail-closed policy on graph resolution errors or timeouts
    return false;
  } 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.8 Contextual Tuple Depth and Cycle Guardrail

OpenFGA 1.8 Contextual Tuple Depth and Cycle Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces strict structural constraints, acyclicity validation, and execution budgets on OpenFGA 1.8 contextual tuples and relationship queries. Prevents unbounded graph traversal, catastrophic algorithmic complexity, and goroutine/stack exhaustion in multi-tenant authorization evaluations. 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 Authorization Checks Without Pre-Evaluation Graph Constraints and Traversal Budgets 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 Authorization Checks Without Pre-Evaluation Graph Constraints and Traversal BudgetsCritical
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 form a strict Directed Acyclic Graph (DAG) using deterministic cycle detection before sending checks to OpenFGA.

Engineers MUST ALWAYS validate that contextual tuples form a strict Directed Acyclic Graph (DAG) using deterministic cycle detection before sending checks to OpenFGA.

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 enforce a strict upper bound on contextual tuples (default

Engineers MUST ALWAYS enforce a strict upper bound on contextual tuples (default: maximum 25 tuples per request) to prevent evaluation payload amplification attacks.

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 NOT pass untrusted or cross-tenant user/object identifiers into contextual tuples without enforcing tenant isolation boundaries on both object and user namespaces.

Engineers MUST NOT pass untrusted or cross-tenant user/object identifiers into contextual tuples without enforcing tenant isolation boundaries on both object and user namespaces.

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 ALWAYS bind OpenFGA check evaluations to an explicit request deadline using AbortSignal/context cancellation (maximum 150ms for synchronous authorization path).

Services MUST ALWAYS bind OpenFGA check evaluations to an explicit request deadline using AbortSignal/context cancellation (maximum 150ms for synchronous authorization path).

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 OpenFGA check calls with fallback to permissive access

Components NEVER execute raw OpenFGA check calls with fallback to permissive access; all cycle errors, resolution-limit-exceeded codes, and timeouts MUST fail closed (deny access).

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.8 Contextual Tuple Depth and Cycle Guardrail critical for AI coding assistants?

Enforces strict structural constraints, acyclicity validation, and execution budgets on OpenFGA 1.8 contextual tuples and relationship queries. Prevents unbounded graph traversal, catastrophic algorithmic complexity, and goroutine/stack exhaustion in multi-tenant authorization evaluations. 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 Authorization Checks Without Pre-Evaluation Graph Constraints and Traversal Budgets) 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