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

OpenFGA Distributed Graph Cyclic Expansion Fencing and Traversal Bounding

Deeply nested multi-tenant Relationship-Based Access Control (ReBAC) models risk unbounded recursive graph expansions and cyclic traversals during authorization evaluations. This rule enforces strict traversal depth ceilings, deterministic cycle fencers, propagation deadlines, and edge-budgeting to prevent thread starvation, high-cardinality latency amplification, and authorization DoS vectors.

Prohibited Anti-Pattern: Unbounded Recursive Traversal and Unfenced Graph Expansion in ReBAC Authorizers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Distributed Graph Cyclic Expansion Fencing and Traversal Bounding - Deeply nested multi-tenant Relationship-Based Access Control (ReBAC) models risk unbounded recursive graph expansions and cyclic traversals during authorization evaluations. This rule enforces strict traversal depth ceilings, deterministic cycle fencers, propagation deadlines, and edge-budgeting to prevent thread starvation, high-cardinality latency amplification, and authorization DoS vectors.
globs: src/**/authz/**/*.{ts,js,go,py}, src/**/authorization/**/*.{ts,js,go,py}, src/**/openfga/**/*.{ts,js,go,py}, src/**/*.fga
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-cyclic-expansion-fencing-guardrail"
---

# OpenFGA Distributed Graph Cyclic Expansion Fencing and Traversal Bounding

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded Recursive Traversal and Unfenced Graph Expansion in ReBAC Authorizers

## System Constraints
You are a Principal Security Architect enforcing OpenFGA Distributed Graph Cyclic Expansion Fencing. You must mandate deterministic recursion depth limits, context-propagated traversal budgets, and strict timeout deadlines across all OpenFGA client calls and schema designs. Reject any open-ended relational expansion that permits self-referential or mutually nested relation loops without cyclic edge fencing and strict AbortController deadlines.

## Strict Guidelines
- Engineers MUST ALWAYS enforce strict contextual deadlines (e.g., max 15ms-25ms) via AbortSignal on all OpenFGA `check`, `expand`, and `listObjects` operations.
- Engineers MUST NOT define mutual parent-child or group-nesting relations in OpenFGA DSL schemas without static acyclic validation or contextual edge traversal ceilings.
- Services MUST inject a deterministic `max_depth` or traversal budget guard into client-side evaluation wrappers before querying OpenFGA clusters.
- Components NEVER execute unbounded multi-hop batch evaluations without token-bucket rate limiting and circuit breakers configured for downstream FGA clusters.
- Authorization clients SHOULD instrument open telemetry metrics capturing graph expansion hop counts, cache hit ratios, and cycle fence tripping events.

## Bad vs Good Implementations
### Unbounded vs Fenced OpenFGA Check Execution

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Invokes OpenFGA without timeout ceilings or cancellation context. If a user belongs to a cyclic or deeply nested folder/workspace hierarchy, OpenFGA can traverse millions of potential paths, exhausting the node process thread pool and OpenFGA query worker pools.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

// ANTI-PATTERN: Unbounded recursive evaluation without timeout deadlines,
// cycle fencing, or contextual abort signals. Deeply nested groups cause
// OpenFGA to exhaust resolution threads and induce cascading service failure.
export async function checkAccessUnsafe(
  userId: string,
  relation: string,
  objectId: string
): Promise<boolean> {
  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation,
    object: objectId,
  });
  return response.allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: Enforces an AbortController deadline (25ms ceiling), tracks visited traversal edges to abort cycles before dispatch, and limits recursion depth to eliminate worker exhaustion and latency tail spikes.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

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

const FGA_MAX_EVALUATION_MS = 25;
const MAX_RELATION_EXPANSION_DEPTH = 5;

export interface FencedCheckOptions {
  currentDepth?: number;
  visitedEdges?: ReadonlySet<string>;
}

// PRODUCTION INVARIANT: Contextual deadline fencing, explicit cycle prevention,
// and bounded traversal limits guarantee sub-millisecond evaluation ceilings.
export async function checkAccessFenced(
  userId: string,
  relation: string,
  objectId: string,
  options: FencedCheckOptions = {}
): Promise<boolean> {
  const depth = options.currentDepth ?? 0;
  const edgeKey = `${userId}#${relation}@${objectId}`;

  if (depth > MAX_RELATION_EXPANSION_DEPTH) {
    throw new Error(`[FGA_FENCE] Traversal depth ceiling exceeded: ${depth}`);
  }

  if (options.visitedEdges?.has(edgeKey)) {
    throw new Error(`[FGA_FENCE] Cyclic relationship detected across edge: ${edgeKey}`);
  }

  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), FGA_MAX_EVALUATION_MS);

  try {
    const payload: ClientCheckRequest = {
      user: `user:${userId}`,
      relation,
      object: objectId,
      contextualTuples: [],
    };

    const response = await fgaClient.check(payload, {
      signal: controller.signal,
    });

    return Boolean(response.allowed);
  } catch (error: unknown) {
    if (error instanceof Error && error.name === 'AbortError') {
      throw new Error(`[FGA_TIMEOUT] Authorization check exceeded deadline of ${FGA_MAX_EVALUATION_MS}ms`);
    }
    throw error;
  } finally {
    clearTimeout(timeoutId);
  }
}
```

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 Distributed Graph Cyclic Expansion Fencing and Traversal Bounding

OpenFGA Distributed Graph Cyclic Expansion Fencing and Traversal Bounding defines an industrial-grade behavioral standard for security engineering. Deeply nested multi-tenant Relationship-Based Access Control (ReBAC) models risk unbounded recursive graph expansions and cyclic traversals during authorization evaluations. This rule enforces strict traversal depth ceilings, deterministic cycle fencers, propagation deadlines, and edge-budgeting to prevent thread starvation, high-cardinality latency amplification, and authorization DoS vectors. 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 Unfenced Graph Expansion in ReBAC Authorizers 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 Unfenced Graph Expansion in ReBAC AuthorizersCritical
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 contextual deadlines (e.g., max 15ms-25ms) via AbortSignal on all OpenFGA `check`, `expand`, and `listObjects` operations.

Engineers MUST ALWAYS enforce strict contextual deadlines (e.g., max 15ms-25ms) via AbortSignal on all OpenFGA `check`, `expand`, and `listObjects` operations.

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 define mutual parent-child or group-nesting relations in OpenFGA DSL schemas without static acyclic validation or contextual edge traversal ceilings.

Engineers MUST NOT define mutual parent-child or group-nesting relations in OpenFGA DSL schemas without static acyclic validation or contextual edge traversal ceilings.

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 inject a deterministic `max_depth` or traversal budget guard into client-side evaluation wrappers before querying OpenFGA clusters.

Services MUST inject a deterministic `max_depth` or traversal budget guard into client-side evaluation wrappers before querying OpenFGA 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

Components NEVER execute unbounded multi-hop batch evaluations without token-bucket rate limiting and circuit breakers configured for downstream FGA clusters.

Components NEVER execute unbounded multi-hop batch evaluations without token-bucket rate limiting and circuit breakers configured for downstream 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.
5

Authorization clients SHOULD instrument open telemetry metrics capturing graph expansion hop counts, cache hit ratios, and cycle fence tripping events.

Authorization clients SHOULD instrument open telemetry metrics capturing graph expansion hop counts, cache hit ratios, and cycle fence tripping events.

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 Distributed Graph Cyclic Expansion Fencing and Traversal Bounding critical for AI coding assistants?

Deeply nested multi-tenant Relationship-Based Access Control (ReBAC) models risk unbounded recursive graph expansions and cyclic traversals during authorization evaluations. This rule enforces strict traversal depth ceilings, deterministic cycle fencers, propagation deadlines, and edge-budgeting to prevent thread starvation, high-cardinality latency amplification, and authorization DoS vectors. 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 Unfenced Graph Expansion in ReBAC Authorizers) 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