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

OpenFGA Modular Schema Cyclic AST Depth and Recursion Guardrail

Enforces static AST cycle detection and strict recursion depth bounds on modular OpenFGA authorization schemas and contextual tuple expansions. Prevents authorization engine exhaustion and Denial-of-Service (DoS) attacks caused by mutually referential tuple-to-userset relations across cross-module graph traversals.

Prohibited Anti-Pattern: Unbounded Recursive Tuple Expansion and Undetected Cross-Module Cycles in OpenFGA Schemas

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Modular Schema Cyclic AST Depth and Recursion Guardrail - Enforces static AST cycle detection and strict recursion depth bounds on modular OpenFGA authorization schemas and contextual tuple expansions. Prevents authorization engine exhaustion and Denial-of-Service (DoS) attacks caused by mutually referential tuple-to-userset relations across cross-module graph traversals.
globs: src/authz/**/*.ts, src/security/**/*.ts, schema/**/*.fga, schema/**/*.json
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-modular-schema-cyclic-ast-depth-guardrail"
---

# OpenFGA Modular Schema Cyclic AST Depth and Recursion Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded Recursive Tuple Expansion and Undetected Cross-Module Cycles in OpenFGA Schemas

## System Constraints
You are a Principal Software Architect enforcing authorization engine resilience. You must mandate AST-level cycle detection and recursion depth caps on OpenFGA modular schemas to prevent distributed denial-of-service vulnerabilities via malicious graph expansions.

## Strict Guidelines
- Engineers MUST ALWAYS run directed acyclic graph (DAG) cycle detection (e.g., Tarjan's or DFS with 3-color marking) across modular relation definitions before uploading authorization models to OpenFGA.
- Engineers MUST NOT allow unconstrained self-referential or mutually referential tuple-to-userset (TTU) relationships (e.g., `member from parent` where `parent` can be self-referential) without an explicit, bounded depth guard.
- Code MUST strictly validate incoming contextual tuples against dynamic traversal limits (maximum expansion depth <= 5) to block runtime cyclic expansion attempts.
- Services MUST enforce request timeouts and configure OpenFGA client options with finite `max_parallel_requests` and strict expansion resolve limits.
- Components NEVER accept raw, user-supplied tenant graph hierarchies without pre-validating that parent-child relationships do not form an edge cycle in the tenant relation store.

## Bad vs Good Implementations
### Modular Schema AST Expansion and Contextual Tuple Cycle Guardrail

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Contextual tuples derived from untrusted client input are passed directly to OpenFGA Check without validation. If the contextual graph contains cycles (e.g., Tenant A is parent of Tenant B, Tenant B is parent of Tenant A), the authorization engine executes recursive path traversals, leading to CPU exhaustion, goroutine starvation, and authorization DoS.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

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

// ANTI-PATTERN: Naively injecting user-supplied contextual tuples into OpenFGA Check
// without cycle detection or expansion depth limits, enabling cyclic graph DoS.
export async function verifyTenantAccessBad(
  fgaClient: OpenFgaClient,
  userId: string,
  tenantId: string,
  contextualHierarchy: TenantHierarchyNode[]
): Promise<boolean> {
  // Injected contextual tuples can contain cycles: e.g. NodeA -> NodeB -> NodeA
  const contextualTuples = contextualHierarchy.map((node) => ({
    user: `tenant:${node.parentId}`,
    relation: 'parent',
    object: `tenant:${node.id}`,
  }));

  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'can_access',
    object: `tenant:${tenantId}`,
    contextualTuples,
  });

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

#### Production Standard (Correct)
> **Standard**: Implements a 3-color cycle detection algorithm and enforces a strict maximum traversal depth limit (MAX_EXPANSION_DEPTH = 5) on the input hierarchy graph. Any cyclic paths or expansions that exceed the depth ceiling are rejected with a deterministic error before triggering queries on the OpenFGA authorization engine.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

export interface TenantHierarchyNode {
  id: string;
  parentId?: string;
}

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

const MAX_EXPANSION_DEPTH = 5;

/**
 * Validates that contextual tenant hierarchy forms a strictly bounded DAG with no cycles.
 */
export function validateHierarchyAcyclic(
  rootId: string,
  nodes: TenantHierarchyNode[],
  maxDepth: number = MAX_EXPANSION_DEPTH
): void {
  const adjList = new Map<string, string[]>();
  for (const node of nodes) {
    if (node.parentId) {
      const existing = adjList.get(node.id) ?? [];
      existing.push(node.parentId);
      adjList.set(node.id, existing);
    }
  }

  // 3-color DFS marking: 0 = unvisited, 1 = visiting (in stack), 2 = visited
  const visited = new Map<string, number>();

  function dfs(currentId: string, currentDepth: number): void {
    if (currentDepth > maxDepth) {
      throw new AuthorizationSecurityError(
        `AST depth limit exceeded: hierarchy exceeds max traversal depth of ${maxDepth}`
      );
    }

    visited.set(currentId, 1); // Mark visiting
    const parents = adjList.get(currentId) ?? [];

    for (const parent of parents) {
      const state = visited.get(parent) ?? 0;
      if (state === 1) {
        throw new AuthorizationSecurityError(
          `Cyclic relation detected in contextual AST: node ${currentId} references ${parent}`
        );
      }
      if (state === 0) {
        dfs(parent, currentDepth + 1);
      }
    }

    visited.set(currentId, 2); // Mark visited
  }

  dfs(rootId, 1);
}

export async function verifyTenantAccessGood(
  fgaClient: OpenFgaClient,
  userId: string,
  tenantId: string,
  contextualHierarchy: TenantHierarchyNode[]
): Promise<boolean> {
  // Invariant Guardrail: Strictly validate DAG acyclicity and bound AST depth before evaluation
  validateHierarchyAcyclic(tenantId, contextualHierarchy, MAX_EXPANSION_DEPTH);

  const contextualTuples = contextualHierarchy
    .filter((n) => Boolean(n.parentId))
    .map((node) => ({
      user: `tenant:${node.parentId}`,
      relation: 'parent',
      object: `tenant:${node.id}`,
    }));

  const response = await fgaClient.check(
    {
      user: `user:${userId}`,
      relation: 'can_access',
      object: `tenant:${tenantId}`,
      contextualTuples,
    },
    {
      // Strictly bound client-side request timeout
      requestTimeoutMs: 1500,
    }
  );

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

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 Modular Schema Cyclic AST Depth and Recursion Guardrail

OpenFGA Modular Schema Cyclic AST Depth and Recursion Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces static AST cycle detection and strict recursion depth bounds on modular OpenFGA authorization schemas and contextual tuple expansions. Prevents authorization engine exhaustion and Denial-of-Service (DoS) attacks caused by mutually referential tuple-to-userset relations across cross-module graph traversals. 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 Recursive Tuple Expansion and Undetected Cross-Module Cycles in OpenFGA Schemas 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 Recursive Tuple Expansion and Undetected Cross-Module Cycles in OpenFGA SchemasCritical
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 directed acyclic graph (DAG) cycle detection (e.g., Tarjan's or DFS with 3-color marking) across modular relation definitions before uploading authorization models to OpenFGA.

Engineers MUST ALWAYS run directed acyclic graph (DAG) cycle detection (e.g., Tarjan's or DFS with 3-color marking) across modular relation definitions before uploading authorization models 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 NOT allow unconstrained self-referential or mutually referential tuple-to-userset (TTU) relationships (e.g., `member from parent` where `parent` can be self-referential) without an explicit, bounded depth guard.

Engineers MUST NOT allow unconstrained self-referential or mutually referential tuple-to-userset (TTU) relationships (e.g., `member from parent` where `parent` can be self-referential) without an explicit, bounded depth guard.

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 MUST strictly validate incoming contextual tuples against dynamic traversal limits (maximum expansion depth <= 5) to block runtime cyclic expansion attempts.

Code MUST strictly validate incoming contextual tuples against dynamic traversal limits (maximum expansion depth <= 5) to block runtime cyclic expansion attempts.

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 request timeouts and configure OpenFGA client options with finite `max_parallel_requests` and strict expansion resolve limits.

Services MUST enforce request timeouts and configure OpenFGA client options with finite `max_parallel_requests` and strict expansion resolve limits.

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 accept raw, user-supplied tenant graph hierarchies without pre-validating that parent-child relationships do not form an edge cycle in the tenant relation store.

Components NEVER accept raw, user-supplied tenant graph hierarchies without pre-validating that parent-child relationships do not form an edge cycle in the tenant relation store.

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 Modular Schema Cyclic AST Depth and Recursion Guardrail critical for AI coding assistants?

Enforces static AST cycle detection and strict recursion depth bounds on modular OpenFGA authorization schemas and contextual tuple expansions. Prevents authorization engine exhaustion and Denial-of-Service (DoS) attacks caused by mutually referential tuple-to-userset relations across cross-module graph traversals. 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 Recursive Tuple Expansion and Undetected Cross-Module Cycles in OpenFGA Schemas) 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