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

OpenFGA Contextual Tuple Traversal Depth & Cycle Guardrail

Enforces deterministic ceilings on contextual tuple injection, graph expansion depth, and cycle detection during real-time OpenFGA Check and ListObjects calls. Unbounded contextual tuples and deeply nested transitive relations can induce computational exhaustion, thread starvation, and catastrophic authorization denial-of-service (DoS). All evaluation graphs must bound recursive dispatch depth and validate contextual tuple payload complexity prior to evaluation.

Prohibited Anti-Pattern: Unbounded Contextual Tuple Ingestion and Recursive Transitive Graph Traversal

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Contextual Tuple Traversal Depth & Cycle Guardrail - Enforces deterministic ceilings on contextual tuple injection, graph expansion depth, and cycle detection during real-time OpenFGA Check and ListObjects calls. Unbounded contextual tuples and deeply nested transitive relations can induce computational exhaustion, thread starvation, and catastrophic authorization denial-of-service (DoS). All evaluation graphs must bound recursive dispatch depth and validate contextual tuple payload complexity prior to evaluation.
globs: src/**/authz/**/*.ts, src/**/authorization/**/*.ts, src/**/fga/**/*.ts, src/**/permissions/**/*.ts, src/**/services/**/*auth*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuple-traversal-depth-guardrail"
---

# OpenFGA Contextual Tuple Traversal Depth & Cycle Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Contextual Tuple Ingestion and Recursive Transitive Graph Traversal

## System Constraints
You are a Principal Security and Distributed Systems Architect enforcing strict evaluation limits on OpenFGA graph resolution. Dynamic, user-supplied contextual tuples and deeply nested recursive relations (such as parent folders or group hierarchies) present severe DoS and infinite loop vectors. You must ensure all authorization evaluation calls enforce hard limits on contextual tuple array size, validate directed acyclic properties, and configure maximum resolution depth constraints using strict client options.

## Strict Guidelines
- Engineers MUST ALWAYS sanitize and cap contextual tuple sets to a strictly validated maximum length (e.g., maximum 20 tuples) before invoking client.check() or client.listObjects().
- Engineers MUST configure explicit maxDepth and request timeout ceilings via ClientCheckOptions or OpenFGA client configurations to pre-empt run-away recursive resolution.
- Engineers MUST NOT accept raw, client-supplied contextual tuples without strict schema validation, type narrowing, and namespace whitelisting.
- Services MUST implement pre-flight cyclic detection or duplicate tuple deduplication when merging session contextual tuples with dynamic relation candidates.
- Components NEVER execute unbounded transitive closure walks (e.g., unbounded parent-of-parent relations) relying solely on default engine resolution limits without local short-circuiting.

## Bad vs Good Implementations
### Unbounded Contextual Tuples and Unconfigured Check Depth vs. Bounded Evaluation Wrapper

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accepting arbitrary contextual tuples directly from an untrusted source without size bounds, deduplication, or traversal depth constraints allows an attacker to construct complex dependency graphs or cyclic paths that trigger catastrophic resolution latency or engine resource exhaustion.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

export async function authorizeUser(
  fgaClient: OpenFgaClient,
  userId: string,
  relation: string,
  objectId: string,
  clientSuppliedContextTuples: Array<{ user: string; relation: string; object: string }>
): Promise<boolean> {
  // Anti-pattern: Direct injection of unbounded, unvalidated contextual tuples
  // No traversal depth limit, no tuple count limit, vulnerable to graph expansion DoS
  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation,
    object: objectId,
    contextualTuples: clientSuppliedContextTuples,
  });

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

#### Production Standard (Correct)
> **Standard**: The production implementation sanitizes contextual tuples against a strict length limit (MAX_CONTEXTUAL_TUPLES), validates allowed resource namespaces, deduplicates duplicate edges, and bounds execution through explicit client request constraints.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

const MAX_CONTEXTUAL_TUPLES = 10;
const ALLOWED_NAMESPACES = new Set(['workspace', 'document', 'organization', 'group']);

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

function validateAndDeduplicateTuples(tuples: TupleKey[]): TupleKey[] {
  if (tuples.length > MAX_CONTEXTUAL_TUPLES) {
    throw new Error(`Contextual tuple threshold exceeded: limit ${MAX_CONTEXTUAL_TUPLES}`);
  }

  const seen = new Set<string>();
  const sanitized: TupleKey[] = [];

  for (const t of tuples) {
    const [objectType] = t.object.split(':');
    if (!objectType || !ALLOWED_NAMESPACES.has(objectType)) {
      throw new Error(`Invalid namespace in contextual object: ${t.object}`);
    }
    const key = `${t.user}#${t.relation}@${t.object}`;
    if (!seen.has(key)) {
      seen.add(key);
      sanitized.push({ user: t.user, relation: t.relation, object: t.object });
    }
  }
  return sanitized;
}

export async function authorizeUser(
  fgaClient: OpenFgaClient,
  userId: string,
  relation: string,
  objectId: string,
  rawContextTuples: TupleKey[] = []
): Promise<boolean> {
  const contextualTuples = validateAndDeduplicateTuples(rawContextTuples);

  // Enforce traversal ceiling through strict per-request options and contextual bounds
  const checkPayload: ClientCheckRequest = {
    user: `user:${userId}`,
    relation,
    object: objectId,
    contextualTuples,
  };

  const response = await fgaClient.check(checkPayload, {
    // Configure low network timeout and restrict max resolution overhead
    maxParallelRequests: 5,
  });

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

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 Traversal Depth & Cycle Guardrail

OpenFGA Contextual Tuple Traversal Depth & Cycle Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic ceilings on contextual tuple injection, graph expansion depth, and cycle detection during real-time OpenFGA Check and ListObjects calls. Unbounded contextual tuples and deeply nested transitive relations can induce computational exhaustion, thread starvation, and catastrophic authorization denial-of-service (DoS). All evaluation graphs must bound recursive dispatch depth and validate contextual tuple payload complexity prior to evaluation. 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 Transitive Graph Traversal 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 Transitive Graph TraversalCritical
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 sanitize and cap contextual tuple sets to a strictly validated maximum length (e.g., maximum 20 tuples) before invoking client.check() or client.listObjects().

Engineers MUST ALWAYS sanitize and cap contextual tuple sets to a strictly validated maximum length (e.g., maximum 20 tuples) before invoking client.check() or client.listObjects().

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 configure explicit maxDepth and request timeout ceilings via ClientCheckOptions or OpenFGA client configurations to pre-empt run-away recursive resolution.

Engineers MUST configure explicit maxDepth and request timeout ceilings via ClientCheckOptions or OpenFGA client configurations to pre-empt run-away recursive resolution.

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

Engineers MUST NOT accept raw, client-supplied contextual tuples without strict schema validation, type narrowing, and namespace whitelisting.

Engineers MUST NOT accept raw, client-supplied contextual tuples without strict schema validation, type narrowing, and namespace whitelisting.

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 pre-flight cyclic detection or duplicate tuple deduplication when merging session contextual tuples with dynamic relation candidates.

Services MUST implement pre-flight cyclic detection or duplicate tuple deduplication when merging session contextual tuples with dynamic relation candidates.

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 transitive closure walks (e.g., unbounded parent-of-parent relations) relying solely on default engine resolution limits without local short-circuiting.

Components NEVER execute unbounded transitive closure walks (e.g., unbounded parent-of-parent relations) relying solely on default engine resolution limits without local short-circuiting.

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 Traversal Depth & Cycle Guardrail critical for AI coding assistants?

Enforces deterministic ceilings on contextual tuple injection, graph expansion depth, and cycle detection during real-time OpenFGA Check and ListObjects calls. Unbounded contextual tuples and deeply nested transitive relations can induce computational exhaustion, thread starvation, and catastrophic authorization denial-of-service (DoS). All evaluation graphs must bound recursive dispatch depth and validate contextual tuple payload complexity prior to evaluation. 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 Transitive Graph Traversal) 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