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

OpenFGA Transitive Relation Cycle-Detection and Traversal Circuit-Breaker Standard

Enforces deterministic recursion termination, hop-budget bounding, and cycle-detection circuit breakers across OpenFGA authorization checks and client-side graph traversals. Protects authorization engines and distributed query layers from algorithmic complexity denial-of-service (ReDoS/Graph DoS) caused by circular group memberships or unbounded transitive relationship expansion.

Prohibited Anti-Pattern: Unbounded Recursive Traversal and Silent Circular Relationship Expansion in Authorization Graphs

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Transitive Relation Cycle-Detection and Traversal Circuit-Breaker Standard - Enforces deterministic recursion termination, hop-budget bounding, and cycle-detection circuit breakers across OpenFGA authorization checks and client-side graph traversals. Protects authorization engines and distributed query layers from algorithmic complexity denial-of-service (ReDoS/Graph DoS) caused by circular group memberships or unbounded transitive relationship expansion.
globs: src/**/authz/**/*.ts, src/**/fga/**/*.ts, src/**/permissions/**/*.ts, src/**/services/auth/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-transitive-cycle-detection-circuit-breaker"
---

# OpenFGA Transitive Relation Cycle-Detection and Traversal Circuit-Breaker Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded Recursive Traversal and Silent Circular Relationship Expansion in Authorization Graphs

## System Constraints
You are a Principal Security Architect enforcing hard bounds, cycle detection, and circuit breakers for OpenFGA transitive authorization traversals. You must reject any recursive graph traversal that lacks explicit hop-depth limits, visited-node registries, deterministic circuit breaking, and OpenFGA context budget propagation.

## Strict Guidelines
- Engineers MUST ALWAYS configure a strict traversal depth budget (default max 15 hops) in OpenFGA client check requests and internal graph traversers.
- Engineers MUST NOT issue unbounded or depth-ignorant `check` or `expand` calls that permit circular relationship evaluations to exhaust engine resources.
- Code SHOULD maintain an immutable visited-set (or color-marked graph registry) to short-circuit repeated node evaluations before querying downstream storage or FGA clusters.
- Services MUST implement a circuit-breaker mechanism that trips upon detecting repeated cycles or consecutive traversal timeouts, failing closed by default.
- Components NEVER execute raw recursive expansion routines without explicit deadline context (`AbortSignal`) and telemetry instrumentation recording traversed edge counts.

## Bad vs Good Implementations
### Unbounded Nested Relation Evaluation vs Circuit-Broken Traversal

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The traversal lacks cycle tracking, depth budgeting, and execution deadlines. Circular parent references (group:A -> group:B -> group:A) trigger infinite recursive calls, depleting the call stack and exhausting the OpenFGA query engine.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

// VULNERABLE: Naive recursive relationship check prone to Graph DoS via circular memberships
export async function isMemberTransitive(userId: string, groupId: string): Promise<boolean> {
  const { allowed } = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'member',
    object: `group:${groupId}`,
  });

  if (allowed) return true;

  // Client-side recursion without visited set or depth guard
  const { tree } = await fgaClient.expand({
    relation: 'parent',
    object: `group:${groupId}`,
  });

  // Unbounded traversal through child relations
  const parentGroups = (tree?.root?.leaf?.users || [])
    .filter((u: string) => u.startsWith('group:'))
    .map((u: string) => u.replace('group:', ''));

  for (const parent of parentGroups) {
    if (await isMemberTransitive(userId, parent)) {
      return true;
    }
  }
  return false;
}
```

#### Production Standard (Correct)
> **Standard**: Implements a strict bounded recursion engine with cycle detection using an immutable visited set, deterministic maximum depth enforcement (15 hops), and request timeouts using AbortSignal to protect against DoS.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

const MAX_TRAVERSAL_DEPTH = 15;

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

interface TraversalContext {
  readonly visited: ReadonlySet<string>;
  readonly currentDepth: number;
  readonly signal: AbortSignal;
}

export async function isMemberTransitive(
  fgaClient: OpenFgaClient,
  userId: string,
  groupId: string,
  ctx: TraversalContext = {
    visited: new Set<string>(),
    currentDepth: 0,
    signal: AbortSignal.timeout(2000),
  }
): Promise<boolean> {
  if (ctx.signal.aborted) {
    throw new GraphTraversalCircuitBreakerError('Authorization traversal aborted: timeout reached');
  }

  const currentObject = `group:${groupId}`;

  // Circuit Breaker 1: Detect cyclic reference
  if (ctx.visited.has(currentObject)) {
    return false;
  }

  // Circuit Breaker 2: Bound recursion depth
  if (ctx.currentDepth >= MAX_TRAVERSAL_DEPTH) {
    throw new GraphTraversalCircuitBreakerError(
      `Transitive relation traversal exceeded max depth of ${MAX_TRAVERSAL_DEPTH}`
    );
  }

  const checkPayload: ClientCheckRequest = {
    user: `user:${userId}`,
    relation: 'member',
    object: currentObject,
  };

  const { allowed } = await fgaClient.check(checkPayload, {
    signal: ctx.signal,
  });

  if (allowed) {
    return true;
  }

  const nextVisited = new Set(ctx.visited).add(currentObject);
  const nextContext: TraversalContext = {
    visited: nextVisited,
    currentDepth: ctx.currentDepth + 1,
    signal: ctx.signal,
  };

  const { tree } = await fgaClient.expand(
    {
      relation: 'parent',
      object: currentObject,
    },
    { signal: ctx.signal }
  );

  const parentGroups = (tree?.root?.leaf?.users ?? [])
    .filter((u): u is string => typeof u === 'string' && u.startsWith('group:'))
    .map((u) => u.replace('group:', ''));

  for (const parentId of parentGroups) {
    if (await isMemberTransitive(fgaClient, userId, parentId, nextContext)) {
      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 Transitive Relation Cycle-Detection and Traversal Circuit-Breaker Standard

OpenFGA Transitive Relation Cycle-Detection and Traversal Circuit-Breaker Standard defines an industrial-grade behavioral standard for security engineering. Enforces deterministic recursion termination, hop-budget bounding, and cycle-detection circuit breakers across OpenFGA authorization checks and client-side graph traversals. Protects authorization engines and distributed query layers from algorithmic complexity denial-of-service (ReDoS/Graph DoS) caused by circular group memberships or unbounded transitive relationship expansion. 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 Traversal and Silent Circular Relationship Expansion in Authorization Graphs 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 Traversal and Silent Circular Relationship Expansion in Authorization GraphsCritical
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 configure a strict traversal depth budget (default max 15 hops) in OpenFGA client check requests and internal graph traversers.

Engineers MUST ALWAYS configure a strict traversal depth budget (default max 15 hops) in OpenFGA client check requests and internal graph traversers.

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 unbounded or depth-ignorant `check` or `expand` calls that permit circular relationship evaluations to exhaust engine resources.

Engineers MUST NOT issue unbounded or depth-ignorant `check` or `expand` calls that permit circular relationship evaluations to exhaust engine resources.

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 maintain an immutable visited-set (or color-marked graph registry) to short-circuit repeated node evaluations before querying downstream storage or FGA clusters.

Code SHOULD maintain an immutable visited-set (or color-marked graph registry) to short-circuit repeated node evaluations before querying downstream storage or FGA clusters.

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 implement a circuit-breaker mechanism that trips upon detecting repeated cycles or consecutive traversal timeouts, failing closed by default.

Services MUST implement a circuit-breaker mechanism that trips upon detecting repeated cycles or consecutive traversal timeouts, failing closed by default.

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 execute raw recursive expansion routines without explicit deadline context (`AbortSignal`) and telemetry instrumentation recording traversed edge counts.

Components NEVER execute raw recursive expansion routines without explicit deadline context (`AbortSignal`) and telemetry instrumentation recording traversed edge counts.

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 Transitive Relation Cycle-Detection and Traversal Circuit-Breaker Standard critical for AI coding assistants?

Enforces deterministic recursion termination, hop-budget bounding, and cycle-detection circuit breakers across OpenFGA authorization checks and client-side graph traversals. Protects authorization engines and distributed query layers from algorithmic complexity denial-of-service (ReDoS/Graph DoS) caused by circular group memberships or unbounded transitive relationship expansion. 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 Traversal and Silent Circular Relationship Expansion in Authorization Graphs) 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