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

OpenFGA Graph Traversal Depth and Dynamic Cycle Quarantine Standard

Enforces strict Directed Acyclic Graph (DAG) invariants, traversal depth constraints, and real-time cycle detection for OpenFGA Relationship-Based Access Control (RebAC). Prevents authorization denial-of-service (DoS) and guarantees sub-millisecond evaluation bounds by intercepting cyclical tuple writes and binding check resolution budgets.

Prohibited Anti-Pattern: Unbounded RebAC Tuple Ingestion and Unguarded Nested Graph Checks Causing Catastrophic Traversal Cycles

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Graph Traversal Depth and Dynamic Cycle Quarantine Standard - Enforces strict Directed Acyclic Graph (DAG) invariants, traversal depth constraints, and real-time cycle detection for OpenFGA Relationship-Based Access Control (RebAC). Prevents authorization denial-of-service (DoS) and guarantees sub-millisecond evaluation bounds by intercepting cyclical tuple writes and binding check resolution budgets.
globs: src/authz/**/*.{ts,tsx}, src/security/**/*.{ts,tsx}, src/services/fga/**/*.{ts,tsx}, src/middleware/auth/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-graph-traversal-depth-cycle-quarantine-standard"
---

# OpenFGA Graph Traversal Depth and Dynamic Cycle Quarantine Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded RebAC Tuple Ingestion and Unguarded Nested Graph Checks Causing Catastrophic Traversal Cycles

## System Constraints
You are a Principal Security Architect enforcing the OpenFGA Dynamic Tuple Graph Traversal Depth and Cycle Quarantine Standard. You must mandate strict DAG validation prior to tuple ingestion, enforce explicit traversal depth thresholds, configure timeout boundaries on all RebAC evaluations, and immediately quarantine recursive circular entity relationships.

## Strict Guidelines
- Engineers MUST ALWAYS validate potential cycles (e.g., transitive closure or topological cycle checks) before persisting new relationship tuples that establish hierarchical edges (e.g., group:parent, folder:parent).
- Engineers MUST NOT issue OpenFGA client check requests without setting an explicit Context deadline or AbortSignal bounded to a strict SLA (sub-25ms default execution budget).
- Services MUST route detected cyclical or invalid hierarchical relationship mutations into an isolated quarantine table/dead-letter queue (DLQ) with an invariant security alert.
- Engineers MUST configure and validate a bounded contextual tuple depth (maximum traversal depth limit, typically <= 15 hops) in OpenFGA configurations to eliminate infinite graph descent.
- Components NEVER execute raw bulk tuple insertions directly against the OpenFGA storage engine without atomic transactional cycle verification against current graph state.

## Bad vs Good Implementations
### Dynamic RebAC Tuple Ingestion with Cycle Check and SLA Bound

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly writing recursive group-in-group relationships without cycle detection can introduce circular dependencies. When OpenFGA evaluates checks across circular graphs without depth limits or client-side execution budgets, it risks thread starvation, high CPU utilization, and latency degradation (auth DoS).
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

// ANTI-PATTERN: Directly writing hierarchical tuples without pre-flight cycle check
// or bounding graph resolution depth, allowing cycles like group:A -> group:B -> group:A
export async function addGroupMember(parentGroupId: string, childGroupId: string): Promise<void> {
  await fgaClient.write({
    writes: [
      {
        user: `group:${childGroupId}`,
        relation: 'member',
        object: `group:${parentGroupId}`,
      },
    ],
  });

  // Unbounded check execution with no timeout deadline
  const isAuthorized = await fgaClient.check({
    user: `user:123`,
    relation: 'viewer',
    object: `group:${parentGroupId}`,
  });
}
```

#### Production Standard (Correct)
> **Standard**: Implements an intentional pre-flight cycle validation before persisting hierarchical edges, sends detected circular edges to quarantine, and enforces an explicit AbortController SLA timeout on OpenFGA evaluations to prevent infinite traversal hangs.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

const MAX_ALLOWED_TRAVERSAL_DEPTH = 15;
const REBAC_CHECK_TIMEOUT_MS = 25;

export class RebACGuardrailService {
  constructor(
    private readonly fgaClient: OpenFgaClient,
    private readonly quarantineService: { quarantineCycle(edge: { user: string; relation: string; object: string }, reason: string): Promise<void> }
  ) {}

  public async safeAddGroupHierarchy(
    parentGroupId: string,
    childGroupId: string
  ): Promise<{ success: boolean; quarantined?: boolean }> {
    const proposedEdge = {
      user: `group:${childGroupId}`,
      relation: 'member',
      object: `group:${parentGroupId}`,
    };

    // 1. Pre-flight cycle verification: Check if parent is already a member of child (transitive cycle)
    const cycleCheckAbort = new AbortController();
    const timeout = setTimeout(() => cycleCheckAbort.abort(), REBAC_CHECK_TIMEOUT_MS);

    try {
      const wouldCycle = await this.fgaClient.check(
        {
          user: `group:${parentGroupId}`,
          relation: 'member',
          object: `group:${childGroupId}`,
        },
        { signal: cycleCheckAbort.signal }
      );

      if (wouldCycle.allowed) {
        // Invariant broken: Cycle detected, quarantine proposed edge
        await this.quarantineService.quarantineCycle(proposedEdge, 'Recursive group-membership cycle detected');
        return { success: false, quarantined: true };
      }
    } finally {
      clearTimeout(timeout);
    }

    // 2. Commit tuple only after cycle quarantine check passes
    await this.fgaClient.write({
      writes: [proposedEdge],
    });

    return { success: true };
  }

  public async checkAuthorizationWithBudget(
    userId: string,
    relation: string,
    objectId: string
  ): Promise<boolean> {
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), REBAC_CHECK_TIMEOUT_MS);

    try {
      const response = await this.fgaClient.check(
        {
          user: `user:${userId}`,
          relation,
          object: objectId,
          contextualTuples: [],
        },
        {
          signal: controller.signal,
        }
      );
      return response.allowed ?? false;
    } catch (err: unknown) {
      if (err instanceof Error && err.name === 'AbortError') {
        throw new Error(`RebAC SLA breached (> ${REBAC_CHECK_TIMEOUT_MS}ms); aborting evaluation.`);
      }
      throw err;
    } finally {
      clearTimeout(timer);
    }
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA Graph Traversal Depth and Dynamic Cycle Quarantine Standard

OpenFGA Graph Traversal Depth and Dynamic Cycle Quarantine Standard defines an industrial-grade behavioral standard for security engineering. Enforces strict Directed Acyclic Graph (DAG) invariants, traversal depth constraints, and real-time cycle detection for OpenFGA Relationship-Based Access Control (RebAC). Prevents authorization denial-of-service (DoS) and guarantees sub-millisecond evaluation bounds by intercepting cyclical tuple writes and binding check resolution budgets. 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 Tuple Ingestion and Unguarded Nested Graph Checks Causing Catastrophic Traversal 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 DriftUnbounded RebAC Tuple Ingestion and Unguarded Nested Graph Checks Causing Catastrophic Traversal 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 validate potential cycles (e.g., transitive closure or topological cycle checks) before persisting new relationship tuples that establish hierarchical edges (e.g., group

Engineers MUST ALWAYS validate potential cycles (e.g., transitive closure or topological cycle checks) before persisting new relationship tuples that establish hierarchical edges (e.g., group:parent, folder:parent).

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 client check requests without setting an explicit Context deadline or AbortSignal bounded to a strict SLA (sub-25ms default execution budget).

Engineers MUST NOT issue OpenFGA client check requests without setting an explicit Context deadline or AbortSignal bounded to a strict SLA (sub-25ms default execution budget).

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 route detected cyclical or invalid hierarchical relationship mutations into an isolated quarantine table/dead-letter queue (DLQ) with an invariant security alert.

Services MUST route detected cyclical or invalid hierarchical relationship mutations into an isolated quarantine table/dead-letter queue (DLQ) with an invariant security alert.

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 configure and validate a bounded contextual tuple depth (maximum traversal depth limit, typically <= 15 hops) in OpenFGA configurations to eliminate infinite graph descent.

Engineers MUST configure and validate a bounded contextual tuple depth (maximum traversal depth limit, typically <= 15 hops) in OpenFGA configurations to eliminate infinite graph descent.

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 bulk tuple insertions directly against the OpenFGA storage engine without atomic transactional cycle verification against current graph state.

Components NEVER execute raw bulk tuple insertions directly against the OpenFGA storage engine without atomic transactional cycle verification against current graph state.

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 Graph Traversal Depth and Dynamic Cycle Quarantine Standard critical for AI coding assistants?

Enforces strict Directed Acyclic Graph (DAG) invariants, traversal depth constraints, and real-time cycle detection for OpenFGA Relationship-Based Access Control (RebAC). Prevents authorization denial-of-service (DoS) and guarantees sub-millisecond evaluation bounds by intercepting cyclical tuple writes and binding check resolution budgets. 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 Tuple Ingestion and Unguarded Nested Graph Checks Causing Catastrophic Traversal 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