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

OpenFGA 1.6 Contextual Tuple Bounded Depth & Cardinality Guardrail

Enforces strict recursion depth limits, contextual tuple bounds, and request timeouts for OpenFGA 1.6 Check and ListObjects operations. Unchecked contextual tuples and unbounded graph traversals in Relationship-Based Access Control (ReBAC) induce query amplification, goroutine exhaustion, and denial-of-service in high-throughput engines.

Prohibited Anti-Pattern: Unbounded Contextual Tuple Ingestion and Missing Evaluation Depth Bounds in ReBAC Checks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA 1.6 Contextual Tuple Bounded Depth & Cardinality Guardrail - Enforces strict recursion depth limits, contextual tuple bounds, and request timeouts for OpenFGA 1.6 Check and ListObjects operations. Unchecked contextual tuples and unbounded graph traversals in Relationship-Based Access Control (ReBAC) induce query amplification, goroutine exhaustion, and denial-of-service in high-throughput engines.
globs: src/**/auth*/**/*.ts, src/**/authorization/**/*.ts, src/**/fga/**/*.ts, src/**/access-control/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuple-depth-guardrail-openfga-1-6-cont-531"
---

# OpenFGA 1.6 Contextual Tuple Bounded Depth & Cardinality Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Contextual Tuple Ingestion and Missing Evaluation Depth Bounds in ReBAC Checks

## System Constraints
You are a Principal Engineer and Security Architect enforcing the OpenFGA 1.6 Contextual Tuple Depth Traversal Standard. Mandate strict validation on contextual tuple cardinality, execution timeouts, and cycle-depth controls on all authorization evaluations. Reject dynamic runtime tuple generation that bypasses schema validation or injects cyclic relationships.

## Strict Guidelines
- Engineers MUST ALWAYS bound contextual tuples to a hard limit (maximum 20-50 tuples per evaluation) before dispatching OpenFGA Check or ListObjects requests.
- Engineers MUST configure an explicit timeout context (maximum 200ms for Check, 500ms for ListObjects) via AbortController or OpenFGA Client options to prevent cascading thread starvation.
- Engineers MUST NOT accept raw user-supplied contextual tuples directly from request payloads without sanitization against cyclic subject-relation references.
- Services MUST ensure that authorization models (DSL/JSON) rely on canonical schema assertions and avoid recursively nested 'from' relations exceeding a depth of 5.
- Services MUST fallback to fail-closed behavior (reject authorization) on OpenFGA evaluation timeouts, recursion depth errors, or schema resolution failures.

## Bad vs Good Implementations
### Enforcing Contextual Tuple Cardinality and Request Timeout Guardrails

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Contextual tuples are passed unbounded directly from input, allowing an attacker to inject large tuple sets or cyclic relationships that exhaust OpenFGA engine worker pools. There is no evaluation timeout context or fail-closed boundary.
```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,
  relation: string,
  resourceId: string,
  dynamicContextualTuples: Array<{ user: string; relation: string; object: string }>
): Promise<boolean> {
  // Anti-pattern: Unbounded contextual tuples passed directly to engine without timeout or validation
  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation,
    object: `document:${resourceId}`,
    contextualTuples: dynamicContextualTuples,
  });

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

#### Production Standard (Correct)
> **Standard**: Imposes strict cardinality bounds on contextual tuples, guards against immediate self-referential graph cycles, enforces a 200ms AbortController timeout, and guarantees deterministic fail-closed resolution.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

const MAX_CONTEXTUAL_TUPLES = 25;
const CHECK_TIMEOUT_MS = 200;

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

export async function authorizeUser(
  userId: string,
  relation: string,
  resourceId: string,
  dynamicContextualTuples: Array<{ user: string; relation: string; object: string }> = []
): Promise<boolean> {
  // Invariant 1: Hard cardinality limit on contextual tuples to prevent algorithmic DoS
  if (dynamicContextualTuples.length > MAX_CONTEXTUAL_TUPLES) {
    throw new Error(`Contextual tuple limit exceeded: max ${MAX_CONTEXTUAL_TUPLES}`);
  }

  // Invariant 2: Validate against trivial self-referential cyclic edges
  for (const tuple of dynamicContextualTuples) {
    if (tuple.user === tuple.object) {
      throw new Error(`Self-referential contextual tuple detected for object ${tuple.object}`);
    }
  }

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

  try {
    const payload: ClientCheckRequest = {
      user: `user:${userId}`,
      relation,
      object: `document:${resourceId}`,
      contextualTuples: dynamicContextualTuples,
    };

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

    return Boolean(response.allowed);
  } catch (error: unknown) {
    // Invariant 3: Explicit fail-closed behavior on timeout or traversal exhaustion
    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 1.6 Contextual Tuple Bounded Depth & Cardinality Guardrail

OpenFGA 1.6 Contextual Tuple Bounded Depth & Cardinality Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict recursion depth limits, contextual tuple bounds, and request timeouts for OpenFGA 1.6 Check and ListObjects operations. Unchecked contextual tuples and unbounded graph traversals in Relationship-Based Access Control (ReBAC) induce query amplification, goroutine exhaustion, and denial-of-service in high-throughput engines. 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 Missing Evaluation Depth Bounds in ReBAC Checks 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 Missing Evaluation Depth Bounds in ReBAC ChecksCritical
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 contextual tuples to a hard limit (maximum 20-50 tuples per evaluation) before dispatching OpenFGA Check or ListObjects requests.

Engineers MUST ALWAYS bound contextual tuples to a hard limit (maximum 20-50 tuples per evaluation) before dispatching OpenFGA Check or ListObjects requests.

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 an explicit timeout context (maximum 200ms for Check, 500ms for ListObjects) via AbortController or OpenFGA Client options to prevent cascading thread starvation.

Engineers MUST configure an explicit timeout context (maximum 200ms for Check, 500ms for ListObjects) via AbortController or OpenFGA Client options to prevent cascading thread starvation.

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 user-supplied contextual tuples directly from request payloads without sanitization against cyclic subject-relation references.

Engineers MUST NOT accept raw user-supplied contextual tuples directly from request payloads without sanitization against cyclic subject-relation references.

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 ensure that authorization models (DSL/JSON) rely on canonical schema assertions and avoid recursively nested 'from' relations exceeding a depth of 5.

Services MUST ensure that authorization models (DSL/JSON) rely on canonical schema assertions and avoid recursively nested 'from' relations exceeding a depth of 5.

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

Services MUST fallback to fail-closed behavior (reject authorization) on OpenFGA evaluation timeouts, recursion depth errors, or schema resolution failures.

Services MUST fallback to fail-closed behavior (reject authorization) on OpenFGA evaluation timeouts, recursion depth errors, or schema resolution failures.

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 Contextual Tuple Bounded Depth & Cardinality Guardrail critical for AI coding assistants?

Enforces strict recursion depth limits, contextual tuple bounds, and request timeouts for OpenFGA 1.6 Check and ListObjects operations. Unchecked contextual tuples and unbounded graph traversals in Relationship-Based Access Control (ReBAC) induce query amplification, goroutine exhaustion, and denial-of-service in high-throughput engines. 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 Missing Evaluation Depth Bounds in ReBAC Checks) 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