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

OpenFGA Contextual Tuple Graph Traversal and Resolution Depth Limiter

Mandates strict operational and structural bounds on OpenFGA authorization queries that supply runtime contextual tuples. Prevents algorithmic complexity Denial-of-Service (DoS) and Policy Decision Point (PDP) thread exhaustion caused by unbounded recursive user-set graph expansions and cyclic relation evaluations.

Prohibited Anti-Pattern: Unbounded Contextual Tuples and Missing PDP Timeouts Inducing Graph Traversal Exhaustion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: "OpenFGA Contextual Tuple Graph Traversal and Resolution Depth Limiter - Mandates strict operational and structural bounds on OpenFGA authorization queries that supply runtime contextual tuples. Prevents algorithmic complexity Denial-of-Service (DoS) and Policy Decision Point (PDP) thread exhaustion caused by unbounded recursive user-set graph expansions and cyclic relation evaluations."
globs: "src/**/authz/**/*.{ts,tsx}, src/**/security/**/*.{ts,tsx}, src/**/guards/**/*.{ts,tsx}, src/**/middleware/**/*.{ts,tsx}"
alwaysApply: true
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuple-traversal-depth-limiter"
---

# OpenFGA Contextual Tuple Graph Traversal and Resolution Depth Limiter

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded Contextual Tuples and Missing PDP Timeouts Inducing Graph Traversal Exhaustion

## System Constraints
You are a Principal Security Architect enforcing resilient OpenFGA ReBAC patterns. Uncontrolled contextual tuples can trigger exponential tree resolution and goroutine exhaustion in the OpenFGA PDP engine. You must enforce strict bounds on contextual tuple payload length, acyclicity pre-checks, PDP request deadlines, and fail-closed error handling.

## Strict Guidelines
- Engineers MUST ALWAYS enforce strict cardinality bounds (e.g., maximum 20 tuples) on contextual tuples supplied to OpenFGA check and list-objects calls.
- Engineers MUST NOT pass unsanitized client-supplied relation graphs directly into contextual tuples without pre-validating object-user identity formats and cycle prevention.
- Code MUST pass an explicit AbortSignal with a strict deadline (e.g., <= 250ms) to every OpenFGA evaluation call to prevent goroutine/thread pooling stalls on deep graph resolutions.
- Services MUST implement fail-closed behavior on timeout or resolution limit errors, treating OpenFGA exhaustion errors as denied access and emitting security telemetry.
- Components NEVER execute recursive user-set evaluations over contextual tuples that permit self-referencing subject-object pairs.

## Bad vs Good Implementations
### Contextual Tuple Evaluation with Depth and Timeout Guardrails

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad implementation accepts an arbitrary number of contextual tuples from callers without cardinality or cycle checks and lacks an AbortSignal timeout. An attacker can supply deeply nested or cyclic transitive relation chains, forcing the OpenFGA PDP engine into excessive recursive evaluations, saturating memory and thread pools.
```typescript
import { OpenFgaClient, type ClientCheckRequest } from '@openfga/sdk';

export async function authorizeUser(
  fgaClient: OpenFgaClient,
  user: string,
  relation: string,
  object: string,
  dynamicTuples: Array<{ user: string; relation: string; object: string }>
): Promise<boolean> {
  // VULNERABLE: Direct pass-through of unbounded contextual tuples,
  // no timeout signal, susceptible to cyclic graph explosion and thread exhaustion.
  const checkRequest: ClientCheckRequest = {
    user,
    relation,
    object,
    contextualTuples: dynamicTuples,
  };

  const response = await fgaClient.check(checkRequest);
  return !!response.allowed;
}
```

#### Production Standard (Correct)
> **Standard**: The invariant implementation restricts the maximum contextual tuple count to 20, rejects obvious self-referential cycles, enforces a 250ms AbortController deadline to prevent PDP thread starvation, and guarantees deterministic fail-closed behavior on failures.
```typescript
import { OpenFgaClient, type ClientCheckRequest, type ClientContextualTuple } from '@openfga/sdk';

const MAX_CONTEXTUAL_TUPLES = 20;
const CHECK_TIMEOUT_MS = 250;

export class AuthorizationSecurityError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'AuthorizationSecurityError';
  }
}

function validateContextualTuples(tuples: ClientContextualTuple[]): void {
  if (tuples.length > MAX_CONTEXTUAL_TUPLES) {
    throw new AuthorizationSecurityError(
      `Contextual tuples exceed safety threshold: ${tuples.length} > ${MAX_CONTEXTUAL_TUPLES}`
    );
  }

  // Prevent direct self-referential graph loops before invoking the PDP
  for (const tuple of tuples) {
    if (tuple.user === tuple.object) {
      throw new AuthorizationSecurityError(
        `Self-referential contextual tuple detected: ${tuple.user}`
      );
    }
  }
}

export async function authorizeUser(
  fgaClient: OpenFgaClient,
  user: string,
  relation: string,
  object: string,
  dynamicTuples: ClientContextualTuple[] = []
): Promise<boolean> {
  validateContextualTuples(dynamicTuples);

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

  try {
    const checkRequest: ClientCheckRequest = {
      user,
      relation,
      object,
      contextualTuples: dynamicTuples,
    };

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

    return Boolean(response.allowed);
  } catch (error) {
    // Fail-closed on PDP evaluation failures, timeouts, or graph limits
    return false;
  } 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 Contextual Tuple Graph Traversal and Resolution Depth Limiter

OpenFGA Contextual Tuple Graph Traversal and Resolution Depth Limiter defines an industrial-grade behavioral standard for security engineering. Mandates strict operational and structural bounds on OpenFGA authorization queries that supply runtime contextual tuples. Prevents algorithmic complexity Denial-of-Service (DoS) and Policy Decision Point (PDP) thread exhaustion caused by unbounded recursive user-set graph expansions and cyclic relation evaluations. 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 Tuples and Missing PDP Timeouts Inducing Graph Traversal Exhaustion 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 Tuples and Missing PDP Timeouts Inducing Graph Traversal ExhaustionCritical
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 bounds (e.g., maximum 20 tuples) on contextual tuples supplied to OpenFGA check and list-objects calls.

Engineers MUST ALWAYS enforce strict cardinality bounds (e.g., maximum 20 tuples) on contextual tuples supplied to OpenFGA check and list-objects 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 unsanitized client-supplied relation graphs directly into contextual tuples without pre-validating object-user identity formats and cycle prevention.

Engineers MUST NOT pass unsanitized client-supplied relation graphs directly into contextual tuples without pre-validating object-user identity formats and cycle prevention.

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 MUST pass an explicit AbortSignal with a strict deadline (e.g., <= 250ms) to every OpenFGA evaluation call to prevent goroutine/thread pooling stalls on deep graph resolutions.

Code MUST pass an explicit AbortSignal with a strict deadline (e.g., <= 250ms) to every OpenFGA evaluation call to prevent goroutine/thread pooling stalls on deep graph resolutions.

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 implement fail-closed behavior on timeout or resolution limit errors, treating OpenFGA exhaustion errors as denied access and emitting security telemetry.

Services MUST implement fail-closed behavior on timeout or resolution limit errors, treating OpenFGA exhaustion errors as denied access and emitting security telemetry.

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 recursive user-set evaluations over contextual tuples that permit self-referencing subject-object pairs.

Components NEVER execute recursive user-set evaluations over contextual tuples that permit self-referencing subject-object pairs.

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 Contextual Tuple Graph Traversal and Resolution Depth Limiter critical for AI coding assistants?

Mandates strict operational and structural bounds on OpenFGA authorization queries that supply runtime contextual tuples. Prevents algorithmic complexity Denial-of-Service (DoS) and Policy Decision Point (PDP) thread exhaustion caused by unbounded recursive user-set graph expansions and cyclic relation evaluations. 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 Tuples and Missing PDP Timeouts Inducing Graph Traversal Exhaustion) 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