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

OpenFGA Hierarchical Contextual Tuples Depth Boundary and Complexity Guard

Enforces strict recursion depth limits, cycle detection, and tuple payload cardinality constraints when passing client-supplied contextual tuples to OpenFGA Check and ListObjects APIs. Prevents Algorithmic Complexity Denial of Service (Graph-DoS) caused by adversarial deeply nested or cyclic relationship graph resolutions during dynamic authorization evaluation.

Prohibited Anti-Pattern: Injecting Unbounded or Cyclic Dynamic Contextual Tuples into OpenFGA Check Calls

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Hierarchical Contextual Tuples Depth Boundary and Complexity Guard - Enforces strict recursion depth limits, cycle detection, and tuple payload cardinality constraints when passing client-supplied contextual tuples to OpenFGA Check and ListObjects APIs. Prevents Algorithmic Complexity Denial of Service (Graph-DoS) caused by adversarial deeply nested or cyclic relationship graph resolutions during dynamic authorization evaluation.
globs: src/auth/**/*.ts, src/security/**/*.ts, src/services/fga/**/*.ts, src/middleware/authorization/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuples-depth-boundary"
---

# OpenFGA Hierarchical Contextual Tuples Depth Boundary and Complexity Guard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Injecting Unbounded or Cyclic Dynamic Contextual Tuples into OpenFGA Check Calls

## System Constraints
You are a Principal Security Architect specializing in Fine-Grained Authorization (FGA) and graph-based access control systems. You mandate strict validation invariants on all OpenFGA evaluations utilizing runtime contextual tuples. Dynamic graph edges injected via contextual tuples must never bypass pre-flight cycle checks, cardinality clamps, and depth boundaries, preventing CPU and memory exhaustion in the authorization engine.

## Strict Guidelines
- Engineers MUST ALWAYS enforce a hard upper bound on the cardinality of contextual tuples per request (e.g., maximum 20 tuples).
- Engineers MUST validate contextual tuple relationships against a strict Directed Acyclic Graph (DAG) invariant with maximum traversal depth <= 10 before forwarding to the OpenFGA client.
- Engineers MUST NOT forward raw, unvalidated client-provided entity hierarchies directly into OpenFGA contextual_tuples.
- Code MUST reject cyclic tuple paths with an explicit HTTP 400 Validation Error prior to invoking authorization engine resolution.
- Services MUST configure OpenFGA evaluation bounds using explicit request timeouts and utilize deterministic hashing of contextual tuples for query memoization.
- Components NEVER execute recursive graph generation of contextual tuples without an invariant depth-limiting decrement counter.

## Bad vs Good Implementations
### Unbounded Dynamic Contextual Tuple Resolution (Vulnerable to Graph-DoS)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Client-supplied hierarchy nodes are transformed directly into OpenFGA contextual tuples without depth checking, cardinality clamping, or cycle detection. Injected deep parent-child chains or cyclic structures force the authorization engine into exhaustive graph resolutions, causing latency spikes and potential denial of service.
```typescript
import { OpenFgaApi, ClientCheckRequest } from '@openfga/sdk';

interface HierarchyNode {
  id: string;
  parentId?: string;
}

export async function authorizeDocumentAccess(
  fgaClient: OpenFgaApi,
  userId: string,
  documentId: string,
  clientHierarchy: HierarchyNode[] // Untrusted client input
): Promise<boolean> {
  // VULNERABLE: Direct conversion of untrusted hierarchical payload into contextual tuples
  // An attacker can supply deeply nested chains (A -> B -> C -> ... -> 1000 nodes)
  // or self-referential cycles that cause exponential evaluation overhead and engine starvation
  const contextualTuples = clientHierarchy.map((node) => ({
    user: `folder:${node.parentId}`,
    relation: 'parent',
    object: `folder:${node.id}`
  }));

  const request: ClientCheckRequest = {
    user: `user:${userId}`,
    relation: 'viewer',
    object: `document:${documentId}`,
    contextualTuples
  };

  const response = await fgaClient.check(request);
  return response.allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: Validates the hierarchy before dispatching to OpenFGA. Enforces a maximum tuple count of 20, rejects self-references, executes DFS cycle detection, and bounds traversal depth to 8 levels, fully shielding the authorization cluster from algorithmic complexity attacks.
```typescript
import { OpenFgaApi, ClientCheckRequest } from '@openfga/sdk';

const MAX_CONTEXTUAL_TUPLES = 20;
const MAX_TRAVERSAL_DEPTH = 8;

interface HierarchyNode {
  id: string;
  parentId?: string;
}

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

function validateHierarchyDAG(nodes: HierarchyNode[]): void {
  if (nodes.length > MAX_CONTEXTUAL_TUPLES) {
    throw new GraphComplexityViolationError(`Contextual tuple count ${nodes.length} exceeds max limit of ${MAX_CONTEXTUAL_TUPLES}`);
  }

  const adj = new Map<string, string[]>();
  for (const node of nodes) {
    if (node.parentId) {
      if (node.id === node.parentId) {
        throw new GraphComplexityViolationError(`Self-referential loop detected at node: ${node.id}`);
      }
      const children = adj.get(node.parentId) ?? [];
      children.push(node.id);
      adj.set(node.parentId, children);
    }
  }

  // Validate acyclicity and calculate maximum depth using DFS
  const visited = new Set<string>();
  const recursionStack = new Set<string>();

  function getDepth(current: string, currentDepth: number): number {
    if (currentDepth > MAX_TRAVERSAL_DEPTH) {
      throw new GraphComplexityViolationError(`Contextual hierarchy exceeds maximum depth boundary of ${MAX_TRAVERSAL_DEPTH}`);
    }
    if (recursionStack.has(current)) {
      throw new GraphComplexityViolationError(`Cycle detected involving node: ${current}`);
    }
    if (visited.has(current)) {
      return currentDepth;
    }

    visited.add(current);
    recursionStack.add(current);

    let maxChildDepth = currentDepth;
    for (const child of adj.get(current) ?? []) {
      maxChildDepth = Math.max(maxChildDepth, getDepth(child, currentDepth + 1));
    }

    recursionStack.delete(current);
    return maxChildDepth;
  }

  for (const node of nodes) {
    if (node.parentId && !visited.has(node.parentId)) {
      getDepth(node.parentId, 1);
    }
  }
}

export async function authorizeDocumentAccess(
  fgaClient: OpenFgaApi,
  userId: string,
  documentId: string,
  clientHierarchy: HierarchyNode[]
): Promise<boolean> {
  validateHierarchyDAG(clientHierarchy);

  const contextualTuples = clientHierarchy
    .filter((node): node is HierarchyNode & { parentId: string } => Boolean(node.parentId))
    .map((node) => ({
      user: `folder:${node.parentId}`,
      relation: 'parent',
      object: `folder:${node.id}`
    }));

  const request: ClientCheckRequest = {
    user: `user:${userId}`,
    relation: 'viewer',
    object: `document:${documentId}`,
    contextualTuples
  };

  const response = await fgaClient.check(request);
  return response.allowed ?? false;
}
```

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA Hierarchical Contextual Tuples Depth Boundary and Complexity Guard

OpenFGA Hierarchical Contextual Tuples Depth Boundary and Complexity Guard defines an industrial-grade behavioral standard for security engineering. Enforces strict recursion depth limits, cycle detection, and tuple payload cardinality constraints when passing client-supplied contextual tuples to OpenFGA Check and ListObjects APIs. Prevents Algorithmic Complexity Denial of Service (Graph-DoS) caused by adversarial deeply nested or cyclic relationship graph resolutions during dynamic authorization evaluation. 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 Dynamic Contextual Tuples into OpenFGA Check Calls 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 Dynamic Contextual Tuples into OpenFGA Check CallsCritical
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 upper bound on the cardinality of contextual tuples per request (e.g., maximum 20 tuples).

Engineers MUST ALWAYS enforce a hard upper bound on the cardinality of contextual tuples per request (e.g., maximum 20 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.
2

Engineers MUST validate contextual tuple relationships against a strict Directed Acyclic Graph (DAG) invariant with maximum traversal depth <= 10 before forwarding to the OpenFGA client.

Engineers MUST validate contextual tuple relationships against a strict Directed Acyclic Graph (DAG) invariant with maximum traversal depth <= 10 before forwarding 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.
3

Engineers MUST NOT forward raw, unvalidated client-provided entity hierarchies directly into OpenFGA contextual_tuples.

Engineers MUST NOT forward raw, unvalidated client-provided entity hierarchies directly into OpenFGA 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.
4

Code MUST reject cyclic tuple paths with an explicit HTTP 400 Validation Error prior to invoking authorization engine resolution.

Code MUST reject cyclic tuple paths with an explicit HTTP 400 Validation Error prior to invoking authorization engine resolution.

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

Services MUST configure OpenFGA evaluation bounds using explicit request timeouts and utilize deterministic hashing of contextual tuples for query memoization.

Services MUST configure OpenFGA evaluation bounds using explicit request timeouts and utilize deterministic hashing of contextual tuples for query memoization.

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

Components NEVER execute recursive graph generation of contextual tuples without an invariant depth-limiting decrement counter.

Components NEVER execute recursive graph generation of contextual tuples without an invariant depth-limiting decrement counter.

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 Hierarchical Contextual Tuples Depth Boundary and Complexity Guard critical for AI coding assistants?

Enforces strict recursion depth limits, cycle detection, and tuple payload cardinality constraints when passing client-supplied contextual tuples to OpenFGA Check and ListObjects APIs. Prevents Algorithmic Complexity Denial of Service (Graph-DoS) caused by adversarial deeply nested or cyclic relationship graph resolutions during dynamic authorization evaluation. 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 Dynamic Contextual Tuples into OpenFGA Check Calls) 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