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

OpenFGA Zanzibar Hierarchical Cycle and Depth Barrier

Enforces bounded traversal invariants, cycle guards, and deterministic recursion ceilings across graph-based relationship tuples in OpenFGA and Zanzibar authorization implementations. Unbounded graph queries and cyclical relationship assignments expose authorization engines to catastrophic denial-of-service, goroutine starvation, and compute amplification attacks.

Prohibited Anti-Pattern: Unbounded recursive tuple resolution allowing cyclical dependencies and resource exhaustion during authorization checks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Zanzibar Hierarchical Cycle and Depth Barrier - Enforces bounded traversal invariants, cycle guards, and deterministic recursion ceilings across graph-based relationship tuples in OpenFGA and Zanzibar authorization implementations. Unbounded graph queries and cyclical relationship assignments expose authorization engines to catastrophic denial-of-service, goroutine starvation, and compute amplification attacks.
globs: src/**/authz/**/*.{ts,js,go,py}, src/**/permissions/**/*.{ts,js,go,py}, src/**/fga/**/*.{ts,js,go,py}, src/**/access/**/*.{ts,js,go,py}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-zanzibar-cycle-depth-barrier"
---

# OpenFGA Zanzibar Hierarchical Cycle and Depth Barrier

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded recursive tuple resolution allowing cyclical dependencies and resource exhaustion during authorization checks

## System Constraints
You are a Principal Security Architect specializing in Google Zanzibar-style Fine-Grained Authorization (OpenFGA, SpiceDB). You enforce strict deterministic recursion bounds, visited-node cycle detection sets, and write-time cycle validation on all relationship-based access control (ReBAC) graph traversals to prevent algorithmic denial-of-service and state-exhaustion vulnerabilities.

## Strict Guidelines
- Engineers MUST ALWAYS enforce a maximum graph resolution depth barrier (MAX_DEPTH <= 25) on both client evaluations and OpenFGA server configuration options.
- Engineers MUST NEVER execute naked recursive authorization resolutions without an explicit, monotonically incrementing depth counter and a visited-node set (Set<string> representing 'type:id#relation').
- Services MUST validate relationship tuple writes (tuple mutations) before persistence using cycle-detection algorithms to prevent creating direct or indirect transitive self-referential graph loops.
- Engineers MUST ALWAYS inject explicit distributed tracing spans and timeout-bounded context (AbortSignal / context.Context) with sub-second ceilings on every authorization graph evaluation call.
- Code MUST fail closed with a deterministic AuthorizationDepthExceededError or CyclicalRelationError rather than hanging or exhausting memory buffers when boundaries are violated.

## Bad vs Good Implementations
### Tuple Graph Evaluation with Visited Set and Depth Barrier

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad code executes recursive evaluation without tracking visited nodes or incrementing a depth counter. If an administrator creates a cyclical relation (e.g., Folder A parent of Folder B, Folder B parent of Folder A), the function triggers an infinite recursion stack overflow, exhausting process memory and blocking the event loop.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

// ANTI-PATTERN: Unbounded recursive graph walk without cycle tracking or depth ceilings
export async function evaluateTransitiveAccess(
  fga: OpenFgaClient,
  ctx: CheckContext
): Promise<boolean> {
  const directCheck = await fga.check({
    user: ctx.user,
    relation: ctx.relation,
    object: ctx.object,
  });

  if (directCheck.allowed) {
    return true;
  }

  // Flaw: Unbounded traversal across parent containers susceptible to circular references
  const { tuples } = await fga.read({
    relation: 'parent',
    object: ctx.object,
  });

  for (const tuple of tuples) {
    // Recursive descent with zero depth bounds and no visited cache -> Infinite Loop / DoS
    const parentAllowed = await evaluateTransitiveAccess(fga, {
      user: ctx.user,
      relation: ctx.relation,
      object: tuple.key.user,
    });
    if (parentAllowed) return true;
  }

  return false;
}
```

#### Production Standard (Correct)
> **Standard**: The good code enforces an immutable visited-node barrier (`nodeKey`) to prevent cyclical traversal and enforces a strict `MAX_GRAPH_DEPTH` invariant. Violations fail closed immediately with a structured domain error, eliminating infinite loops, heap exhaustion, and graph-induced DoS vectors.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

export class AuthorizationGraphError extends Error {
  constructor(message: string, public readonly code: 'DEPTH_LIMIT_EXCEEDED' | 'CYCLE_DETECTED') {
    super(message);
    this.name = 'AuthorizationGraphError';
  }
}

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

const MAX_GRAPH_DEPTH = 15;

export async function evaluateTransitiveAccessSecure(
  fga: OpenFgaClient,
  req: CheckRequest,
  depth: number = 0,
  visitedNodes: ReadonlySet<string> = new Set<string>()
): Promise<boolean> {
  // Invariant 1: Enforce deterministic recursion ceiling
  if (depth > MAX_GRAPH_DEPTH) {
    throw new AuthorizationGraphError(
      `Authorization resolution exceeded depth ceiling of ${MAX_GRAPH_DEPTH}`,
      'DEPTH_LIMIT_EXCEEDED'
    );
  }

  // Invariant 2: Cycle detection fence via composite state key
  const nodeKey = `${req.object}#${req.relation}@${req.user}`;
  if (visitedNodes.has(nodeKey)) {
    throw new AuthorizationGraphError(
      `Cyclic relationship detected at node: ${nodeKey}`,
      'CYCLE_DETECTED'
    );
  }

  const nextVisited = new Set(visitedNodes).add(nodeKey);

  const { allowed } = await fga.check({
    user: req.user,
    relation: req.relation,
    object: req.object,
  });

  if (allowed) {
    return true;
  }

  const { tuples } = await fga.read({
    relation: 'parent',
    object: req.object,
  });

  for (const tuple of tuples) {
    const parentObject = tuple.key.user;
    const hasAccess = await evaluateTransitiveAccessSecure(
      fga,
      {
        user: req.user,
        relation: req.relation,
        object: parentObject,
      },
      depth + 1,
      nextVisited
    );
    if (hasAccess) return true;
  }

  return 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 Zanzibar Hierarchical Cycle and Depth Barrier

OpenFGA Zanzibar Hierarchical Cycle and Depth Barrier defines an industrial-grade behavioral standard for security engineering. Enforces bounded traversal invariants, cycle guards, and deterministic recursion ceilings across graph-based relationship tuples in OpenFGA and Zanzibar authorization implementations. Unbounded graph queries and cyclical relationship assignments expose authorization engines to catastrophic denial-of-service, goroutine starvation, and compute amplification attacks. 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 resolution allowing cyclical dependencies and resource exhaustion during authorization checks 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 resolution allowing cyclical dependencies and resource exhaustion during authorization checksCritical
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 maximum graph resolution depth barrier (MAX_DEPTH <= 25) on both client evaluations and OpenFGA server configuration options.

Engineers MUST ALWAYS enforce a maximum graph resolution depth barrier (MAX_DEPTH <= 25) on both client evaluations and OpenFGA server configuration options.

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 NEVER execute naked recursive authorization resolutions without an explicit, monotonically incrementing depth counter and a visited-node set (Set<string> representing 'type

Engineers MUST NEVER execute naked recursive authorization resolutions without an explicit, monotonically incrementing depth counter and a visited-node set (Set<string> representing 'type:id#relation').

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

Services MUST validate relationship tuple writes (tuple mutations) before persistence using cycle-detection algorithms to prevent creating direct or indirect transitive self-referential graph loops.

Services MUST validate relationship tuple writes (tuple mutations) before persistence using cycle-detection algorithms to prevent creating direct or indirect transitive self-referential graph loops.

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

Engineers MUST ALWAYS inject explicit distributed tracing spans and timeout-bounded context (AbortSignal / context.Context) with sub-second ceilings on every authorization graph evaluation call.

Engineers MUST ALWAYS inject explicit distributed tracing spans and timeout-bounded context (AbortSignal / context.Context) with sub-second ceilings on every authorization graph evaluation call.

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

Code MUST fail closed with a deterministic AuthorizationDepthExceededError or CyclicalRelationError rather than hanging or exhausting memory buffers when boundaries are violated.

Code MUST fail closed with a deterministic AuthorizationDepthExceededError or CyclicalRelationError rather than hanging or exhausting memory buffers when boundaries are violated.

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 Zanzibar Hierarchical Cycle and Depth Barrier critical for AI coding assistants?

Enforces bounded traversal invariants, cycle guards, and deterministic recursion ceilings across graph-based relationship tuples in OpenFGA and Zanzibar authorization implementations. Unbounded graph queries and cyclical relationship assignments expose authorization engines to catastrophic denial-of-service, goroutine starvation, and compute amplification attacks. 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 resolution allowing cyclical dependencies and resource exhaustion during authorization checks) 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