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

OpenFGA Modular Composition Cycle Detection & Traversal Depth Guardrail

Enforces static acyclic graph (DAG) verification and bounded expansion depth across modular OpenFGA authorization schemas prior to compilation or ingestion. Prevents cross-module cyclic relation references and transitive tuple_to_userset loops that trigger denial-of-service or stack exhaustion in authorization evaluation engines.

Prohibited Anti-Pattern: Unchecked Dynamic Module Composition Permitting Infinite Traversal Recursion Cycles

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Modular Composition Cycle Detection & Traversal Depth Guardrail - Enforces static acyclic graph (DAG) verification and bounded expansion depth across modular OpenFGA authorization schemas prior to compilation or ingestion. Prevents cross-module cyclic relation references and transitive tuple_to_userset loops that trigger denial-of-service or stack exhaustion in authorization evaluation engines.
globs: src/authz/**/*.ts, src/security/**/*.ts, schemas/**/*.fga, src/models/fga/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-modular-composition-cycle-detection-guardrail"
---

# OpenFGA Modular Composition Cycle Detection & Traversal Depth Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unchecked Dynamic Module Composition Permitting Infinite Traversal Recursion Cycles

## System Constraints
You are a Principal Security Architect enforcing OpenFGA Modular Model Composition Cycle-Detection Guardrails. Mandate that every dynamic or build-time composition of modular OpenFGA relation definitions constructs a unified cross-module Relation Dependency Graph (RDG) and executes Tarjan's or cycle-detection DFS prior to serialization or engine registration. Unbounded tuple_to_userset cycles and module-crossing circular dependencies are critical security vulnerabilities that MUST trigger immediate compilation failures.

## Strict Guidelines
- Engineers MUST ALWAYS construct an explicit cross-module directed relation graph (RDG) before compiling or writing OpenFGA modular schemas.
- Engineers MUST NOT merge modular schema definitions by naive string concatenation or unvalidated type merging.
- Code SHOULD validate the composed schema against a strict maximum evaluation hop count (Max Traversal Depth <= 15).
- Services MUST reject schema uploads at build/deploy time if any Strongly Connected Component (SCC) of size > 1 is detected across computed_userset or tuple_to_userset edges.
- Components NEVER allow self-referential or transitive cyclic relations unless explicitly guarded by disjoint type constraints and acyclic database tuple invariant checks.

## Bad vs Good Implementations
### Cross-Module Model Composition Validation with Cycle & Depth Detection

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Naive concatenation and dictionary merging of modular OpenFGA schemas ignores cross-module relation pointers. If Module A defines 'folder#editor -> parent#editor' and Module B defines 'parent -> folder#editor', an uninspected cycle causes evaluation engines to spin or crash under Check/ListObjects queries.
```typescript
import { TypeDefinition, RelationMetadata } from '@openfga/sdk';

interface FgaModule {
  typeDefinitions: TypeDefinition[];
}

// ANTI-PATTERN: Naively merging modular schemas without cross-module cycle analysis
export function assembleModularModel(modules: FgaModule[]): TypeDefinition[] {
  const combined: Record<string, TypeDefinition> = {};

  for (const mod of modules) {
    for (const typeDef of mod.typeDefinitions) {
      if (!combined[typeDef.type]) {
        combined[typeDef.type] = typeDef;
      } else {
        // Blindly merges relations, allowing circular references across modules
        combined[typeDef.type].relations = {
          ...combined[typeDef.type].relations,
          ...typeDef.relations,
        };
      }
    }
  }
  return Object.values(combined);
}
```

#### Production Standard (Correct)
> **Standard**: Constructs an explicit Relation Dependency Graph (RDG) across all merged modular types. Runs recursive DFS cycle-detection with a strict recursion stack to prevent circular definitions and enforces an upper traversal depth boundary to eliminate infinite evaluation risks.
```typescript
import { TypeDefinition, Userset } from '@openfga/sdk';

interface FgaModule {
  name: string;
  typeDefinitions: TypeDefinition[];
}

export class ModularSchemaValidator {
  private static readonly MAX_EXPANSION_DEPTH = 10;

  public static composeAndVerify(modules: FgaModule[]): TypeDefinition[] {
    const typeDefs: Map<string, TypeDefinition> = new Map();
    const adjacencyList: Map<string, Set<string>> = new Map();

    for (const mod of modules) {
      for (const td of mod.typeDefinitions) {
        const current = typeDefs.get(td.type) ?? { type: td.type, relations: {} };
        current.relations = { ...current.relations, ...td.relations };
        typeDefs.set(td.type, current);
      }
    }

    for (const [type, td] of typeDefs.entries()) {
      for (const [relation, def] of Object.entries(td.relations || {})) {
        const nodeKey = `${type}#${relation}`;
        if (!adjacencyList.has(nodeKey)) adjacencyList.set(nodeKey, new Set());
        this.extractTargetNodes(def, adjacencyList.get(nodeKey)!);
      }
    }

    this.detectCyclesAndDepth(adjacencyList);
    return Array.from(typeDefs.values());
  }

  private static extractTargetNodes(userset: Userset, targets: Set<string>): void {
    if (userset.computedUserset?.relation) {
      targets.add(userset.computedUserset.relation);
    }
    if (userset.tupleToUserset?.tupleset?.relation && userset.tupleToUserset?.computedUserset?.relation) {
      targets.add(`${userset.tupleToUserset.tupleset.relation}#${userset.tupleToUserset.computedUserset.relation}`);
    }
    if (userset.union) userset.union.child.forEach((c) => this.extractTargetNodes(c, targets));
    if (userset.intersection) userset.intersection.child.forEach((c) => this.extractTargetNodes(c, targets));
    if (userset.difference) {
      this.extractTargetNodes(userset.difference.base, targets);
      this.extractTargetNodes(userset.difference.subtract, targets);
    }
  }

  private static detectCyclesAndDepth(graph: Map<string, Set<string>>): void {
    const visited = new Set<string>();
    const recursionStack = new Set<string>();

    const dfs = (node: string, depth: number): void => {
      if (depth > this.MAX_EXPANSION_DEPTH) {
        throw new Error(`Exceeded max traversal depth of ${this.MAX_EXPANSION_DEPTH} at node: ${node}`);
      }
      visited.add(node);
      recursionStack.add(node);

      for (const neighbor of graph.get(node) || []) {
        if (!visited.has(neighbor)) {
          dfs(neighbor, depth + 1);
        } else if (recursionStack.has(neighbor)) {
          throw new Error(`Circular relation detected in modular composition: ${node} -> ${neighbor}`);
        }
      }
      recursionStack.delete(node);
    };

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

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 Composition Cycle Detection & Traversal Depth Guardrail

OpenFGA Modular Composition Cycle Detection & Traversal Depth Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces static acyclic graph (DAG) verification and bounded expansion depth across modular OpenFGA authorization schemas prior to compilation or ingestion. Prevents cross-module cyclic relation references and transitive tuple_to_userset loops that trigger denial-of-service or stack exhaustion in authorization evaluation engines. 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: Unchecked Dynamic Module Composition Permitting Infinite Traversal Recursion Cycles 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 DriftUnchecked Dynamic Module Composition Permitting Infinite Traversal Recursion CyclesCritical
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 construct an explicit cross-module directed relation graph (RDG) before compiling or writing OpenFGA modular schemas.

Engineers MUST ALWAYS construct an explicit cross-module directed relation graph (RDG) before compiling or writing OpenFGA modular schemas.

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 merge modular schema definitions by naive string concatenation or unvalidated type merging.

Engineers MUST NOT merge modular schema definitions by naive string concatenation or unvalidated type merging.

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 validate the composed schema against a strict maximum evaluation hop count (Max Traversal Depth <= 15).

Code SHOULD validate the composed schema against a strict maximum evaluation hop count (Max Traversal Depth <= 15).

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 reject schema uploads at build/deploy time if any Strongly Connected Component (SCC) of size > 1 is detected across computed_userset or tuple_to_userset edges.

Services MUST reject schema uploads at build/deploy time if any Strongly Connected Component (SCC) of size > 1 is detected across computed_userset or tuple_to_userset edges.

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 allow self-referential or transitive cyclic relations unless explicitly guarded by disjoint type constraints and acyclic database tuple invariant checks.

Components NEVER allow self-referential or transitive cyclic relations unless explicitly guarded by disjoint type constraints and acyclic database tuple invariant checks.

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

Enforces static acyclic graph (DAG) verification and bounded expansion depth across modular OpenFGA authorization schemas prior to compilation or ingestion. Prevents cross-module cyclic relation references and transitive tuple_to_userset loops that trigger denial-of-service or stack exhaustion in authorization evaluation engines. 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 (Unchecked Dynamic Module Composition Permitting Infinite Traversal Recursion Cycles) 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