This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: openfga-rebac-cyclic-evaluation-guardrails

OpenFGA Zanzibar Hierarchical ReBAC Cyclic Evaluation & Recursion Guardrails

Enforces strict recursion depth bounding, cyclic relation validation, and context-propagated cycle detection across OpenFGA/Zanzibar ReBAC authorization evaluations. Prevents unbounded graph traversals, distributed stack exhaustion, and Denial of Service (DoS) attacks caused by mutually nested relations or unconstrained transitive closure evaluations.

Prohibited Anti-Pattern: Unbounded ReBAC graph expansion via cyclic or deeply nested relation-tuple evaluation without traversal bounds and cycle-breaking context

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Zanzibar Hierarchical ReBAC Cyclic Evaluation & Recursion Guardrails - Enforces strict recursion depth bounding, cyclic relation validation, and context-propagated cycle detection across OpenFGA/Zanzibar ReBAC authorization evaluations. Prevents unbounded graph traversals, distributed stack exhaustion, and Denial of Service (DoS) attacks caused by mutually nested relations or unconstrained transitive closure evaluations.
globs: src/authz/**/*.{ts,js,go,py}, src/security/**/*.{ts,js,go,py}, src/models/**/*.fga, src/services/authz/**/*.{ts,js,go,py}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-rebac-cyclic-evaluation-guardrails"
---

# OpenFGA Zanzibar Hierarchical ReBAC Cyclic Evaluation & Recursion Guardrails

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded ReBAC graph expansion via cyclic or deeply nested relation-tuple evaluation without traversal bounds and cycle-breaking context

## System Constraints
You are a Principal Security Architect and Distributed Systems Engineer specializing in Zanzibar-style Relation-Based Access Control (ReBAC) and OpenFGA. Enforce strict invariants against recursive graph traversal loops, unbounded tuple expansion, and cluster exhaustion during authorization evaluations. Require all relation traversal queries, tuple writes, and schema designs to include deterministic cycle detection, bounded recursion depth limits, and timeout-enforced distributed context propagation.

## Strict Guidelines
- Engineers MUST ALWAYS enforce strict cycle detection prior to persisting relational tuples that permit nested or self-referential inheritance (e.g., group-in-group, folder-in-folder).
- Engineers MUST NOT issue OpenFGA `check` or `expand` calls without passing explicit timeout deadlines and setting bounded traversal depth constraints (e.g., max resolve depth <= 25).
- Services MUST validate directed acyclic graph (DAG) topology during write-time tuple operations using depth-first search (DFS) with memoized visited sets before committing transactional edge writes.
- Engineers MUST structure OpenFGA models to avoid mutual relation definitions unless guarded by distinct base types and strict sub-relation qualifiers.
- Code SHOULD propagate tracing and graph-path telemetry in contextual tuples during dynamic evaluation to detect and immediately abort redundant traversal branches.
- Components NEVER execute raw unbounded recursive resolve operations on user-controlled transitive relation-tuples without circuit-breaking thresholds.

## Bad vs Good Implementations
### Tuple Write Cycle Prevention & Bounded Evaluation Guardrail

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Writing nested transitive tuples without verifying graph acyclicity allows circular memberships (e.g., A -> B -> A). Subsequent check requests will induce unbounded recursion or cause resource starvation across the evaluation cluster if cycle detection or search limits are omitted.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

// ANTI-PATTERN: Blindly writing nested parent-child tuple without cycle checks
// and checking permissions with no depth bounding or timeout context.
export async function addNestedGroupMember(parentId: string, childId: string) {
  await fgaClient.writeTuples([{
    user: `group:${childId}#member`,
    relation: 'member',
    object: `group:${parentId}`,
  }]);
}

export async function checkAccess(userId: string, groupId: string): Promise<boolean> {
  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'member',
    object: `group:${groupId}`,
  });
  return response.allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: Validates graph topology before persisting relation tuples to proactively prevent cycles, limits traversal depth via maxDepth, and binds execution to a cancellation signal with a strict timeout.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

const MAX_RECURSION_DEPTH = 15;
const EVALUATION_TIMEOUT_MS = 2500;

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

export async function addNestedGroupMember(parentId: string, childId: string): Promise<void> {
  if (parentId === childId) {
    throw new Error('Self-referential membership is prohibited.');
  }

  // Check if childId is already an ancestor of parentId to prevent cycles
  const cycleCheck = await fgaClient.check({
    user: `group:${parentId}#member`,
    relation: 'member',
    object: `group:${childId}`,
    contextualTuples: [],
  }, { maxDepth: MAX_RECURSION_DEPTH });

  if (cycleCheck.allowed) {
    throw new Error(`Cycle detected: group:${parentId} is already an ancestor of group:${childId}`);
  }

  await fgaClient.writeTuples([{
    user: `group:${childId}#member`,
    relation: 'member',
    object: `group:${parentId}`,
  }]);
}

export async function checkAccess(userId: string, groupId: string): Promise<boolean> {
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), EVALUATION_TIMEOUT_MS);

  try {
    const response = await fgaClient.check({
      user: `user:${userId}`,
      relation: 'member',
      object: `group:${groupId}`,
    }, {
      maxDepth: MAX_RECURSION_DEPTH,
      signal: controller.signal,
    });
    return Boolean(response.allowed);
  } finally {
    clearTimeout(timeout);
  }
}
```

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 ReBAC Cyclic Evaluation & Recursion Guardrails

OpenFGA Zanzibar Hierarchical ReBAC Cyclic Evaluation & Recursion Guardrails defines an industrial-grade behavioral standard for security engineering. Enforces strict recursion depth bounding, cyclic relation validation, and context-propagated cycle detection across OpenFGA/Zanzibar ReBAC authorization evaluations. Prevents unbounded graph traversals, distributed stack exhaustion, and Denial of Service (DoS) attacks caused by mutually nested relations or unconstrained transitive closure 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: Unbounded ReBAC graph expansion via cyclic or deeply nested relation-tuple evaluation without traversal bounds and cycle-breaking context 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 ReBAC graph expansion via cyclic or deeply nested relation-tuple evaluation without traversal bounds and cycle-breaking contextCritical
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 strict cycle detection prior to persisting relational tuples that permit nested or self-referential inheritance (e.g., group-in-group, folder-in-folder).

Engineers MUST ALWAYS enforce strict cycle detection prior to persisting relational tuples that permit nested or self-referential inheritance (e.g., group-in-group, folder-in-folder).

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 issue OpenFGA `check` or `expand` calls without passing explicit timeout deadlines and setting bounded traversal depth constraints (e.g., max resolve depth <= 25).

Engineers MUST NOT issue OpenFGA `check` or `expand` calls without passing explicit timeout deadlines and setting bounded traversal depth constraints (e.g., max resolve depth <= 25).

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 directed acyclic graph (DAG) topology during write-time tuple operations using depth-first search (DFS) with memoized visited sets before committing transactional edge writes.

Services MUST validate directed acyclic graph (DAG) topology during write-time tuple operations using depth-first search (DFS) with memoized visited sets before committing transactional edge writes.

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 structure OpenFGA models to avoid mutual relation definitions unless guarded by distinct base types and strict sub-relation qualifiers.

Engineers MUST structure OpenFGA models to avoid mutual relation definitions unless guarded by distinct base types and strict sub-relation qualifiers.

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 SHOULD propagate tracing and graph-path telemetry in contextual tuples during dynamic evaluation to detect and immediately abort redundant traversal branches.

Code SHOULD propagate tracing and graph-path telemetry in contextual tuples during dynamic evaluation to detect and immediately abort redundant traversal branches.

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 raw unbounded recursive resolve operations on user-controlled transitive relation-tuples without circuit-breaking thresholds.

Components NEVER execute raw unbounded recursive resolve operations on user-controlled transitive relation-tuples without circuit-breaking thresholds.

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 ReBAC Cyclic Evaluation & Recursion Guardrails critical for AI coding assistants?

Enforces strict recursion depth bounding, cyclic relation validation, and context-propagated cycle detection across OpenFGA/Zanzibar ReBAC authorization evaluations. Prevents unbounded graph traversals, distributed stack exhaustion, and Denial of Service (DoS) attacks caused by mutually nested relations or unconstrained transitive closure 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 (Unbounded ReBAC graph expansion via cyclic or deeply nested relation-tuple evaluation without traversal bounds and cycle-breaking context) 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