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

Deterministic Traversal Depth Bounding and Cycle Rejection for OpenFGA Zanzibar Engines

Enforces strict limits on graph traversal depth, contextual tuple cardinality, and cycle detection during distributed Zanzibar relationship evaluations. Eliminates exponential expansion and goroutine/thread starvation to guarantee sub-5ms P99 authorization latencies.

Prohibited Anti-Pattern: Unbounded Contextual Graph Traversal and Missing Cycle Guardrails Causing Evaluation Hangs and ReBAC DoS

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Deterministic Traversal Depth Bounding and Cycle Rejection for OpenFGA Zanzibar Engines - Enforces strict limits on graph traversal depth, contextual tuple cardinality, and cycle detection during distributed Zanzibar relationship evaluations. Eliminates exponential expansion and goroutine/thread starvation to guarantee sub-5ms P99 authorization latencies.
globs: src/auth/**/*.{ts,tsx}, src/lib/fga/**/*.{ts,tsx}, src/services/authz/**/*.{ts,tsx}, src/middleware/authz/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-zanzibar-deterministic-traversal-guardrail"
---

# Deterministic Traversal Depth Bounding and Cycle Rejection for OpenFGA Zanzibar Engines

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded Contextual Graph Traversal and Missing Cycle Guardrails Causing Evaluation Hangs and ReBAC DoS

## System Constraints
You are a Principal Security Architect enforcing the OpenFGA Zanzibar Distributed Contextual Tuple Evaluation Standard. You must guarantee that every graph evaluation request is bounded by deterministic depth, cycle detection, strict contextual tuple cardinality, and explicit cancellation deadlines to prevent denial-of-service vulnerabilities and latency SLA breaches.

## Strict Guidelines
- Engineers MUST ALWAYS enforce strict cardinality caps (maximum 20 tuples) and validate tuple schema on client-supplied contextual tuples prior to OpenFGA dispatch.
- Engineers MUST NOT dispatch evaluation queries without explicit client-side timeout deadlines configured to less than 5ms for local networks and 25ms for distributed deployments.
- Code SHOULD enforce deterministic recursion limits (e.g., maxResolveNodeLimit <= 25) to prevent catastrophic graph explosion on cyclical or deeply nested group hierarchies.
- Services MUST reject circular contextual tuples through in-memory directed acyclic graph (DAG) validation prior to executing the evaluation check.
- Components NEVER execute unbounded Check or ListObjects operations against OpenFGA without propagating standard cancellation contexts and fail-closed fallbacks.

## Bad vs Good Implementations
### Unbounded Contextual Tuple Evaluation vs Bounded Cycle-Safe Evaluation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accepting unvalidated, unbounded contextual tuples allows attackers to craft cyclic or deeply nested relationship graphs, causing recursion storms, high CPU consumption, and evaluation latencies far exceeding acceptable SLAs.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

// ANTI-PATTERN: Blindly trust client contextual tuples, omit timeouts,
// and invoke check without depth ceilings or cycle detection.
export async function authorizeUser(
  userId: string,
  relation: string,
  documentId: string,
  clientContextualTuples: Array<{ user: string; relation: string; object: string }>
): Promise<boolean> {
  // VULNERABILITY: If client supplies cyclical tuples (A is member of B, B is member of A),
  // or hundreds of arbitrary tuples, the Zanzibar resolver hangs and consumes unbounded cluster compute.
  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation,
    object: `document:${documentId}`,
    contextualTuples: clientContextualTuples,
  });

  return response.allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: Pre-validates contextual tuples for maximum cardinality and acyclicity using DFS cycle detection. Enforces strict node-resolution ceilings on the client instance and uses an AbortController deadline to guarantee deterministic sub-5ms fail-closed execution.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

const MAX_CONTEXTUAL_TUPLES = 10;
const EVALUATION_TIMEOUT_MS = 5;
const MAX_RESOLVE_NODE_LIMIT = 25;

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

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

function validateAcyclicContext(tuples: TupleKey[]): void {
  if (tuples.length > MAX_CONTEXTUAL_TUPLES) {
    throw new Error(`Contextual tuple cardinality exceeds limit of ${MAX_CONTEXTUAL_TUPLES}`);
  }

  const adjacency = new Map<string, Set<string>>();
  for (const { user, object } of tuples) {
    if (user === object) {
      throw new Error(`Direct reflexive cycle detected: ${user}`);
    }
    const neighbors = adjacency.get(user) ?? new Set<string>();
    neighbors.add(object);
    adjacency.set(user, neighbors);
  }

  const visited = new Set<string>();
  const recursionStack = new Set<string>();

  const detectCycle = (node: string): boolean => {
    visited.add(node);
    recursionStack.add(node);
    for (const neighbor of adjacency.get(node) ?? []) {
      if (!visited.has(neighbor) && detectCycle(neighbor)) return true;
      if (recursionStack.has(neighbor)) return true;
    }
    recursionStack.delete(node);
    return false;
  };

  for (const node of adjacency.keys()) {
    if (!visited.has(node) && detectCycle(node)) {
      throw new Error(`Cyclic contextual tuple detected at node: ${node}`);
    }
  }
}

export async function authorizeUser(
  userId: string,
  relation: string,
  documentId: string,
  clientContextualTuples: TupleKey[]
): Promise<boolean> {
  validateAcyclicContext(clientContextualTuples);

  const checkPayload: ClientCheckRequest = {
    user: `user:${userId}`,
    relation,
    object: `document:${documentId}`,
    contextualTuples: clientContextualTuples,
  };

  const abortController = new AbortController();
  const timeoutHandle = setTimeout(() => abortController.abort(), EVALUATION_TIMEOUT_MS);

  try {
    const response = await fgaClient.check(checkPayload, {
      signal: abortController.signal,
    });
    return response.allowed ?? false;
  } catch (error) {
    // Fail closed immediately upon timeout or traversal boundary error
    return false;
  } finally {
    clearTimeout(timeoutHandle);
  }
}
```

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: Deterministic Traversal Depth Bounding and Cycle Rejection for OpenFGA Zanzibar Engines

Deterministic Traversal Depth Bounding and Cycle Rejection for OpenFGA Zanzibar Engines defines an industrial-grade behavioral standard for security engineering. Enforces strict limits on graph traversal depth, contextual tuple cardinality, and cycle detection during distributed Zanzibar relationship evaluations. Eliminates exponential expansion and goroutine/thread starvation to guarantee sub-5ms P99 authorization latencies. 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 Contextual Graph Traversal and Missing Cycle Guardrails Causing Evaluation Hangs and ReBAC DoS 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 Contextual Graph Traversal and Missing Cycle Guardrails Causing Evaluation Hangs and ReBAC DoSCritical
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 cardinality caps (maximum 20 tuples) and validate tuple schema on client-supplied contextual tuples prior to OpenFGA dispatch.

Engineers MUST ALWAYS enforce strict cardinality caps (maximum 20 tuples) and validate tuple schema on client-supplied contextual tuples prior to OpenFGA dispatch.

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 dispatch evaluation queries without explicit client-side timeout deadlines configured to less than 5ms for local networks and 25ms for distributed deployments.

Engineers MUST NOT dispatch evaluation queries without explicit client-side timeout deadlines configured to less than 5ms for local networks and 25ms for distributed deployments.

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 enforce deterministic recursion limits (e.g., maxResolveNodeLimit <= 25) to prevent catastrophic graph explosion on cyclical or deeply nested group hierarchies.

Code SHOULD enforce deterministic recursion limits (e.g., maxResolveNodeLimit <= 25) to prevent catastrophic graph explosion on cyclical or deeply nested group hierarchies.

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 reject circular contextual tuples through in-memory directed acyclic graph (DAG) validation prior to executing the evaluation check.

Services MUST reject circular contextual tuples through in-memory directed acyclic graph (DAG) validation prior to executing the evaluation check.

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 unbounded Check or ListObjects operations against OpenFGA without propagating standard cancellation contexts and fail-closed fallbacks.

Components NEVER execute unbounded Check or ListObjects operations against OpenFGA without propagating standard cancellation contexts and fail-closed fallbacks.

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 Deterministic Traversal Depth Bounding and Cycle Rejection for OpenFGA Zanzibar Engines critical for AI coding assistants?

Enforces strict limits on graph traversal depth, contextual tuple cardinality, and cycle detection during distributed Zanzibar relationship evaluations. Eliminates exponential expansion and goroutine/thread starvation to guarantee sub-5ms P99 authorization latencies. 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 Contextual Graph Traversal and Missing Cycle Guardrails Causing Evaluation Hangs and ReBAC DoS) 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

Deterministic