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

Deterministic Traversal Depth and Cycle Governance for OpenFGA Contextual Tuples

Enforces strict recursion depth bounding and deterministic cycle memoization during real-time OpenFGA and Zanzibar authorization checks. Prevents stack exhaustion, authorization service denial-of-service (DoS), and unbounded RPC fan-out caused by circular or deeply nested contextual relationships. Mandates fail-closed semantics and visited-node state tracking across all graph traversal boundaries.

Prohibited Anti-Pattern: Unbounded Contextual Tuple Ingestion and Recursive Graph Traversal Without Cycle Detection

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Deterministic Traversal Depth and Cycle Governance for OpenFGA Contextual Tuples - Enforces strict recursion depth bounding and deterministic cycle memoization during real-time OpenFGA and Zanzibar authorization checks. Prevents stack exhaustion, authorization service denial-of-service (DoS), and unbounded RPC fan-out caused by circular or deeply nested contextual relationships. Mandates fail-closed semantics and visited-node state tracking across all graph traversal boundaries.
globs: src/auth/**/*.{ts,tsx}, src/security/**/*.{ts,tsx}, src/access-control/**/*.{ts,tsx}, src/middleware/auth/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-zanzibar-cyclic-traversal-depth-governor"
---

# Deterministic Traversal Depth and Cycle Governance for OpenFGA Contextual Tuples

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded Contextual Tuple Ingestion and Recursive Graph Traversal Without Cycle Detection

## System Constraints
You are a Principal Security Architect enforcing Zanzibar/OpenFGA authorization invariants. You must prevent graph recursion exploits, ReDoS, and denial of service across authorization pipelines by mandating strict cycle detection, deterministic depth governors, and fail-closed resolution boundaries for dynamic and contextual tuples.

## Strict Guidelines
- Engineers MUST ALWAYS bound graph recursion depth to a deterministic threshold (default maximum depth <= 15) when expanding relations or injecting contextual tuples.
- Engineers MUST NOT pass untrusted or unvalidated dynamic contextual tuples directly into OpenFGA Check calls without cycle pre-screening.
- Code SHOULD maintain an explicit visited node registry (`Set<string>`) formatted as canonical entity-relation keys (`${type}:${id}#${relation}`) to detect cycles in constant time.
- Services MUST fail closed with a typed `AuthorizationDepthExceededError` or `CyclicRelationDetectedError` when graph limits are breached.
- Components NEVER execute authorization resolution without propagation of an explicit `AbortSignal` with an aggressive timeout (<= 1500ms).

## Bad vs Good Implementations
### Contextual Tuple Graph Resolution with Depth Governor and Cycle Detection

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Contextual tuples are directly mapped and sent to OpenFGA without validating graph depth or detecting cyclic dependencies. If contextual input includes circular references (e.g., group:A member of group:B, group:B member of group:A), authorization engines can experience memory exhaustion, exponential query expansion, and distributed Denial-of-Service.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

interface DynamicMembership {
  userId: string;
  groupId: string;
  parentGroupId?: string;
}

// VULNERABLE: Recursively accumulates contextual tuples without cycle detection or depth governance.
// An adversary creating cyclic links (Group A -> Group B -> Group A) will trigger stack overflow or infinite loops.
export async function resolveContextualTuplesUnsafe(
  fgaClient: OpenFgaClient,
  userId: string,
  objectId: string,
  membershipTree: DynamicMembership[]
): Promise<boolean> {
  const contextualTuples = membershipTree.map((item) => ({
    user: `user:${item.userId}`,
    relation: 'member',
    object: `group:${item.groupId}`,
  }));

  // Unbounded contextual tuples injected directly
  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'viewer',
    object: `document:${objectId}`,
    contextualTuples,
  });

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

#### Production Standard (Correct)
> **Standard**: Implements a deterministic cycle detector and depth governor prior to evaluating contextual tuples. DFS detects back-edges via a recursion stack tracking canonical `type:id#relation` keys and throws an explicit `CyclicRelationDetectedError` if loops exist, while capping depth to a strict threshold. The caller catches graph violations and safely fails closed without exhausting server threads.
```typescript
import { OpenFgaClient, ClientTupleKey } from '@openfga/sdk';

export class CyclicRelationDetectedError extends Error {
  constructor(node: string) {
    super(`Cycle detected in authorization graph traversal at node: ${node}`);
    this.name = 'CyclicRelationDetectedError';
  }
}

export class AuthorizationDepthExceededError extends Error {
  constructor(depth: number, maxDepth: number) {
    super(`Authorization graph depth limit exceeded: ${depth} > ${maxDepth}`);
    this.name = 'AuthorizationDepthExceededError';
  }
}

interface Edge {
  from: string;
  relation: string;
  to: string;
}

const MAX_TRAVERSAL_DEPTH = 15;

export function validateAndGovernGraph(
  edges: Edge[],
  maxDepth: number = MAX_TRAVERSAL_DEPTH
): ClientTupleKey[] {
  const adjacency = new Map<string, Array<{ to: string; relation: string }>>();
  for (const edge of edges) {
    const nodeKey = `${edge.from}#${edge.relation}`;
    const existing = adjacency.get(nodeKey) ?? [];
    existing.push({ to: edge.to, relation: edge.relation });
    adjacency.set(nodeKey, existing);
  }

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

  function dfs(currentNode: string, currentDepth: number): void {
    if (currentDepth > maxDepth) {
      throw new AuthorizationDepthExceededError(currentDepth, maxDepth);
    }
    if (recursionStack.has(currentNode)) {
      throw new CyclicRelationDetectedError(currentNode);
    }
    if (visited.has(currentNode)) {
      return;
    }

    visited.add(currentNode);
    recursionStack.add(currentNode);

    const neighbors = adjacency.get(currentNode) ?? [];
    for (const neighbor of neighbors) {
      dfs(`${neighbor.to}#${neighbor.relation}`, currentDepth + 1);
    }

    recursionStack.delete(currentNode);
  }

  for (const edge of edges) {
    dfs(`${edge.from}#${edge.relation}`, 1);
  }

  return edges.map((e) => ({
    user: e.from,
    relation: e.relation,
    object: e.to,
  }));
}

export async function evaluateGovernedAuthorization(
  fgaClient: OpenFgaClient,
  user: string,
  relation: string,
  object: string,
  rawEdges: Edge[],
  signal: AbortSignal
): Promise<boolean> {
  try {
    const safeContextualTuples = validateAndGovernGraph(rawEdges);

    const response = await fgaClient.check(
      {
        user,
        relation,
        object,
        contextualTuples: safeContextualTuples,
      },
      { signal }
    );

    return response.allowed ?? false;
  } catch (error) {
    if (
      error instanceof CyclicRelationDetectedError ||
      error instanceof AuthorizationDepthExceededError
    ) {
      // Fail-closed invariant
      return false;
    }
    throw error;
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Deterministic Traversal Depth and Cycle Governance for OpenFGA Contextual Tuples

Deterministic Traversal Depth and Cycle Governance for OpenFGA Contextual Tuples defines an industrial-grade behavioral standard for security engineering. Enforces strict recursion depth bounding and deterministic cycle memoization during real-time OpenFGA and Zanzibar authorization checks. Prevents stack exhaustion, authorization service denial-of-service (DoS), and unbounded RPC fan-out caused by circular or deeply nested contextual relationships. Mandates fail-closed semantics and visited-node state tracking across all graph traversal boundaries. 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 Tuple Ingestion and Recursive Graph Traversal Without Cycle Detection 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 Tuple Ingestion and Recursive Graph Traversal Without Cycle DetectionCritical
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 bound graph recursion depth to a deterministic threshold (default maximum depth <= 15) when expanding relations or injecting contextual tuples.

Engineers MUST ALWAYS bound graph recursion depth to a deterministic threshold (default maximum depth <= 15) when expanding relations or injecting contextual tuples.

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 pass untrusted or unvalidated dynamic contextual tuples directly into OpenFGA Check calls without cycle pre-screening.

Engineers MUST NOT pass untrusted or unvalidated dynamic contextual tuples directly into OpenFGA Check calls without cycle pre-screening.

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 explicit visited node registry (`Set<string>`) formatted as canonical entity-relation keys (`${type}

Code SHOULD maintain an explicit visited node registry (`Set<string>`) formatted as canonical entity-relation keys (`${type}:${id}#${relation}`) to detect cycles in constant time.

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 fail closed with a typed `AuthorizationDepthExceededError` or `CyclicRelationDetectedError` when graph limits are breached.

Services MUST fail closed with a typed `AuthorizationDepthExceededError` or `CyclicRelationDetectedError` when graph limits are breached.

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 authorization resolution without propagation of an explicit `AbortSignal` with an aggressive timeout (<= 1500ms).

Components NEVER execute authorization resolution without propagation of an explicit `AbortSignal` with an aggressive timeout (<= 1500ms).

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 and Cycle Governance for OpenFGA Contextual Tuples critical for AI coding assistants?

Enforces strict recursion depth bounding and deterministic cycle memoization during real-time OpenFGA and Zanzibar authorization checks. Prevents stack exhaustion, authorization service denial-of-service (DoS), and unbounded RPC fan-out caused by circular or deeply nested contextual relationships. Mandates fail-closed semantics and visited-node state tracking across all graph traversal boundaries. 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 Tuple Ingestion and Recursive Graph Traversal Without Cycle Detection) 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