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

OpenFGA 1.6 Traversal Depth Bound and Conditional CEL Latency Guardrail

Prevents unbounded distributed graph traversal, cascading latency degradation, and resource exhaustion in OpenFGA 1.6 Zanzibar authorization engines. Mandates strict client-side timeout propagation, bounded contextual tuple evaluation, depth-limited model relations, and O(1) Common Expression Language (CEL) conditionals under deep multi-tenant hierarchies.

Prohibited Anti-Pattern: Unconstrained Recursive Relation Traversal and Unbounded Dynamic CEL Context Causing Authorization Engine DoS

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA 1.6 Traversal Depth Bound and Conditional CEL Latency Guardrail - Prevents unbounded distributed graph traversal, cascading latency degradation, and resource exhaustion in OpenFGA 1.6 Zanzibar authorization engines. Mandates strict client-side timeout propagation, bounded contextual tuple evaluation, depth-limited model relations, and O(1) Common Expression Language (CEL) conditionals under deep multi-tenant hierarchies.
globs: src/**/*.ts, src/auth/**/*.ts, models/**/*.fga, src/infrastructure/auth/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-conditional-evaluation-traversal-guard"
---

# OpenFGA 1.6 Traversal Depth Bound and Conditional CEL Latency Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unconstrained Recursive Relation Traversal and Unbounded Dynamic CEL Context Causing Authorization Engine DoS

## System Constraints
You are a Principal Security Architect enforcing OpenFGA 1.6 authorization invariants. You must prevent recursive graph explosion and CEL-induced denial of service across fine-grained tenancy trees. Enforce strict sub-200ms check deadlines, boundary caps on contextual tuples, deterministic non-nested CEL conditions, and explicit traversal depth boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS enforce strict per-request context timeouts (budgeted <= 150ms) using AbortSignal on all OpenFGA `check`, `listObjects`, and `listRelations` calls.
- Engineers MUST NOT pass unbounded or unvalidated contextual tuples in `check` payloads; array size MUST be capped (maximum 20 tuples) and payload sizes strictly validated.
- Services MUST bound CEL conditions in OpenFGA models to primitive type comparisons (e.g., timestamps, strings, IP networks) and MUST NOT execute complex collection loops or regex operations within conditions.
- Models MUST NOT define unrestricted mutually-recursive relations (e.g., folder -> parent -> folder) without a depth-limited structural boundary or explicit tenancy root anchor.
- Code MUST handle OpenFGA `FgaApiValidationError`, `ClientError`, and timeout-induced `DEADLINE_EXCEEDED` errors with fail-closed semantics, never falling through to permissive access defaults.

## Bad vs Good Implementations
### Unbounded Check Call vs Bound Conditional Check with Timeout

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omits execution timeouts (allowing graph traversals to hang indefinitely), accepts an unvalidated number of contextual tuples allowing client-driven memory exhaustion, passes arbitrary context into CEL conditions, and lacks fail-closed error handling.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

export async function authorizeUser(
  userId: string,
  documentId: string,
  action: string,
  dynamicContext: Record<string, any>
): Promise<boolean> {
  // VULNERABILITY: No timeout set, passing arbitrary dynamic context directly
  // into conditional CEL evaluation, and querying deeply nested recursive graph
  // without traversal bounds or error differentiation.
  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation: action,
    object: `document:${documentId}`,
    contextualTuples: dynamicContext.extraTuples, // Unbounded array injection
    context: dynamicContext.claims, // Arbitrary payload can trigger complex CEL recursion
  });

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

#### Production Standard (Correct)
> **Standard**: Implements an explicit 150ms AbortSignal deadline, restricts contextual tuple injection to a validated upper bound of 10, sanitizes condition inputs to primitive CEL-safe fields, and guarantees fail-closed exception handling.
```typescript
import { OpenFgaClient, FgaApiError } from '@openfga/sdk';

const MAX_CONTEXTUAL_TUPLES = 10;
const CHECK_TIMEOUT_MS = 150;

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

interface ValidatedConditionContext {
  current_time: string;
  client_ip: string;
}

export async function authorizeUser(
  userId: string,
  documentId: string,
  action: 'read' | 'write' | 'admin',
  context: ValidatedConditionContext,
  scopedAncestors: Array<{ entity: string; parent: string }> = []
): Promise<boolean> {
  if (scopedAncestors.length > MAX_CONTEXTUAL_TUPLES) {
    throw new Error('Contextual graph expansion exceeds traversal boundary');
  }

  // Enforce rigid request-scoped latency boundary
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), CHECK_TIMEOUT_MS);

  try {
    const response = await fgaClient.check(
      {
        user: `user:${userId}`,
        relation: action,
        object: `document:${documentId}`,
        context: {
          current_time: context.current_time,
          client_ip: context.client_ip,
        },
        contextualTuples: scopedAncestors.map((rel) => ({
          user: rel.parent,
          relation: 'parent',
          object: rel.entity,
        })),
      },
      { signal: controller.signal }
    );

    return Boolean(response.allowed);
  } catch (error: unknown) {
    // Fail-closed on latency boundaries, cancellation, or engine errors
    if (error instanceof Error && error.name === 'AbortError') {
      throw new Error(`FGA authorization timed out after ${CHECK_TIMEOUT_MS}ms (fail-closed)`);
    }
    if (error instanceof FgaApiError) {
      throw new Error(`OpenFGA check failed with status ${error.statusCode}: Access Denied`);
    }
    throw error;
  } finally {
    clearTimeout(timeoutId);
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA 1.6 Traversal Depth Bound and Conditional CEL Latency Guardrail

OpenFGA 1.6 Traversal Depth Bound and Conditional CEL Latency Guardrail defines an industrial-grade behavioral standard for security engineering. Prevents unbounded distributed graph traversal, cascading latency degradation, and resource exhaustion in OpenFGA 1.6 Zanzibar authorization engines. Mandates strict client-side timeout propagation, bounded contextual tuple evaluation, depth-limited model relations, and O(1) Common Expression Language (CEL) conditionals under deep multi-tenant hierarchies. 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: Unconstrained Recursive Relation Traversal and Unbounded Dynamic CEL Context Causing Authorization Engine 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 DriftUnconstrained Recursive Relation Traversal and Unbounded Dynamic CEL Context Causing Authorization Engine 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 per-request context timeouts (budgeted <= 150ms) using AbortSignal on all OpenFGA `check`, `listObjects`, and `listRelations` calls.

Engineers MUST ALWAYS enforce strict per-request context timeouts (budgeted <= 150ms) using AbortSignal on all OpenFGA `check`, `listObjects`, and `listRelations` calls.

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 unbounded or unvalidated contextual tuples in `check` payloads

Engineers MUST NOT pass unbounded or unvalidated contextual tuples in `check` payloads; array size MUST be capped (maximum 20 tuples) and payload sizes strictly validated.

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 bound CEL conditions in OpenFGA models to primitive type comparisons (e.g., timestamps, strings, IP networks) and MUST NOT execute complex collection loops or regex operations within conditions.

Services MUST bound CEL conditions in OpenFGA models to primitive type comparisons (e.g., timestamps, strings, IP networks) and MUST NOT execute complex collection loops or regex operations within conditions.

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

Models MUST NOT define unrestricted mutually-recursive relations (e.g., folder -> parent -> folder) without a depth-limited structural boundary or explicit tenancy root anchor.

Models MUST NOT define unrestricted mutually-recursive relations (e.g., folder -> parent -> folder) without a depth-limited structural boundary or explicit tenancy root anchor.

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

Code MUST handle OpenFGA `FgaApiValidationError`, `ClientError`, and timeout-induced `DEADLINE_EXCEEDED` errors with fail-closed semantics, never falling through to permissive access defaults.

Code MUST handle OpenFGA `FgaApiValidationError`, `ClientError`, and timeout-induced `DEADLINE_EXCEEDED` errors with fail-closed semantics, never falling through to permissive access defaults.

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 1.6 Traversal Depth Bound and Conditional CEL Latency Guardrail critical for AI coding assistants?

Prevents unbounded distributed graph traversal, cascading latency degradation, and resource exhaustion in OpenFGA 1.6 Zanzibar authorization engines. Mandates strict client-side timeout propagation, bounded contextual tuple evaluation, depth-limited model relations, and O(1) Common Expression Language (CEL) conditionals under deep multi-tenant hierarchies. 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 (Unconstrained Recursive Relation Traversal and Unbounded Dynamic CEL Context Causing Authorization Engine 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

OpenFGA