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

OpenFGA Contextual Tuple Cyclic Expansion Depth and Memory Guardrail

Mandates strict bounds on contextual tuple array size, acyclic relationship validation, and client-side execution timeouts for OpenFGA 1.6 authorization calls. Unbounded or cyclic transient tuples injected into real-time check evaluations trigger exponential sub-graph traversals, causing severe latency degradation, worker thread starvation, and Denial-of-Service (DoS) vulnerabilities.

Prohibited Anti-Pattern: Injecting Unsanitized Dynamic Contextual Tuples Directly into Authorization Checks Without Depth Caps or Graph Bounds

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Contextual Tuple Cyclic Expansion Depth and Memory Guardrail - Mandates strict bounds on contextual tuple array size, acyclic relationship validation, and client-side execution timeouts for OpenFGA 1.6 authorization calls. Unbounded or cyclic transient tuples injected into real-time check evaluations trigger exponential sub-graph traversals, causing severe latency degradation, worker thread starvation, and Denial-of-Service (DoS) vulnerabilities.
globs: src/**/auth/**/*.{ts,js}, src/**/authorization/**/*.{ts,js}, src/**/fga/**/*.{ts,js}, src/**/guards/**/*.{ts,js}, src/**/middleware/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuple-cyclic-expansion-guardrail"
---

# OpenFGA Contextual Tuple Cyclic Expansion Depth and Memory Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Injecting Unsanitized Dynamic Contextual Tuples Directly into Authorization Checks Without Depth Caps or Graph Bounds

## System Constraints
You are a Principal Software Architect enforcing enterprise-grade security standards for Fine-Grained Authorization (OpenFGA). You must ensure all evaluations involving contextual tuples strictly bound graph traversal depth, sanitize and deduplicate tuple sets, prevent cyclic references in transient relation graphs, and enforce explicit execution deadlines to prevent graph-expansion denial-of-service vulnerabilities.

## Strict Guidelines
- Engineers MUST ALWAYS validate and cap the maximum number of contextual tuples passed to an OpenFGA Check or ListObjects evaluation (strictly enforce N <= 20).
- Engineers MUST NOT accept arbitrary caller-defined contextual tuples directly into authorization calls without strict schema validation and cycle pre-checking.
- Services MUST enforce strict call timeouts (maximum 2000ms) using AbortSignal/AbortController when invoking the OpenFGA evaluation APIs.
- Engineers MUST sanitize contextual tuples to ensure no reflexive or cyclic relations exist (e.g., entity A is member of entity B, and entity B is member of entity A) before dispatching requests to OpenFGA.
- Components NEVER pass unindexed or cross-tenant contextual tuples that force the OpenFGA resolver engine to evaluate deep hierarchical unions or recursive intersections beyond the configured server threshold.

## Bad vs Good Implementations
### Mitigating Graph-Expansion DoS with Contextual Tuple Guardrails

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly ingesting contextual tuples without bounding length, detecting cycles, or applying a strict timeout allows malicious actors to craft recursive or self-referential relationship chains. This induces exponential graph traversal in OpenFGA's resolution engine, exhausting server CPU and memory.
```typescript
import { OpenFgaClient, type ClientCheckRequest } from '@openfga/sdk';

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

// ANTI-PATTERN: Blindly forwarding arbitrary contextual tuples from untrusted user input
export async function evaluateAccessUnsafe(reqBody: any): Promise<boolean> {
  const checkRequest: ClientCheckRequest = {
    user: reqBody.user,
    relation: reqBody.relation,
    object: reqBody.object,
    // DANGEROUS: Unbounded array, unchecked cyclic graph definitions
    // Caller can pass hundreds of nested 'parent' or 'member' tuples causing exponential expansion
    contextualTuples: reqBody.transientTuples,
  };

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

#### Production Standard (Correct)
> **Standard**: Imposes a hard cap on tuple count (MAX_CONTEXTUAL_TUPLES), inspects and rejects reflexive/reciprocal relationship cycles, and enforces an explicit AbortSignal timeout to protect the authorization cluster from graph-expansion denial-of-service.
```typescript
import { OpenFgaClient, type ClientCheckRequest, type TupleKey } from '@openfga/sdk';

const MAX_CONTEXTUAL_TUPLES = 10;
const CHECK_TIMEOUT_MS = 1500;

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

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

function validateAcyclicContext(tuples: SanitizedTupleInput[]): TupleKey[] {
  if (tuples.length > MAX_CONTEXTUAL_TUPLES) {
    throw new Error(`Contextual tuples exceed hard ceiling limit of ${MAX_CONTEXTUAL_TUPLES}`);
  }

  const adjacency = new Map<string, Set<string>>();
  const sanitized: TupleKey[] = [];

  for (const t of tuples) {
    // Invariant: Reflexive edge prohibition
    if (t.user === t.object) {
      throw new Error(`Reflexive cyclic tuple rejected: ${t.user} -> ${t.object}`);
    }

    // Detect immediate reciprocal cycles (A -> B and B -> A)
    const existingTargets = adjacency.get(t.object);
    if (existingTargets?.has(t.user)) {
      throw new Error(`Direct cycle detected between ${t.user} and ${t.object}`);
    }

    if (!adjacency.has(t.user)) {
      adjacency.set(t.user, new Set());
    }
    adjacency.get(t.user)!.add(t.object);

    sanitized.push({ user: t.user, relation: t.relation, object: t.object });
  }

  return sanitized;
}

export async function evaluateAccessSafe(
  user: string,
  relation: string,
  object: string,
  rawContextualTuples: SanitizedTupleInput[] = []
): Promise<boolean> {
  const boundedTuples = validateAcyclicContext(rawContextualTuples);
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), CHECK_TIMEOUT_MS);

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

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

    return Boolean(response.allowed);
  } finally {
    clearTimeout(timeoutId);
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA Contextual Tuple Cyclic Expansion Depth and Memory Guardrail

OpenFGA Contextual Tuple Cyclic Expansion Depth and Memory Guardrail defines an industrial-grade behavioral standard for security engineering. Mandates strict bounds on contextual tuple array size, acyclic relationship validation, and client-side execution timeouts for OpenFGA 1.6 authorization calls. Unbounded or cyclic transient tuples injected into real-time check evaluations trigger exponential sub-graph traversals, causing severe latency degradation, worker thread starvation, and Denial-of-Service (DoS) vulnerabilities. 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: Injecting Unsanitized Dynamic Contextual Tuples Directly into Authorization Checks Without Depth Caps or Graph Bounds 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 DriftInjecting Unsanitized Dynamic Contextual Tuples Directly into Authorization Checks Without Depth Caps or Graph BoundsCritical
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 validate and cap the maximum number of contextual tuples passed to an OpenFGA Check or ListObjects evaluation (strictly enforce N <= 20).

Engineers MUST ALWAYS validate and cap the maximum number of contextual tuples passed to an OpenFGA Check or ListObjects evaluation (strictly enforce N <= 20).

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 accept arbitrary caller-defined contextual tuples directly into authorization calls without strict schema validation and cycle pre-checking.

Engineers MUST NOT accept arbitrary caller-defined contextual tuples directly into authorization calls without strict schema validation and cycle pre-checking.

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 enforce strict call timeouts (maximum 2000ms) using AbortSignal/AbortController when invoking the OpenFGA evaluation APIs.

Services MUST enforce strict call timeouts (maximum 2000ms) using AbortSignal/AbortController when invoking the OpenFGA evaluation APIs.

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

Engineers MUST sanitize contextual tuples to ensure no reflexive or cyclic relations exist (e.g., entity A is member of entity B, and entity B is member of entity A) before dispatching requests to OpenFGA.

Engineers MUST sanitize contextual tuples to ensure no reflexive or cyclic relations exist (e.g., entity A is member of entity B, and entity B is member of entity A) before dispatching requests to OpenFGA.

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 pass unindexed or cross-tenant contextual tuples that force the OpenFGA resolver engine to evaluate deep hierarchical unions or recursive intersections beyond the configured server threshold.

Components NEVER pass unindexed or cross-tenant contextual tuples that force the OpenFGA resolver engine to evaluate deep hierarchical unions or recursive intersections beyond the configured server threshold.

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 Cyclic Expansion Depth and Memory Guardrail critical for AI coding assistants?

Mandates strict bounds on contextual tuple array size, acyclic relationship validation, and client-side execution timeouts for OpenFGA 1.6 authorization calls. Unbounded or cyclic transient tuples injected into real-time check evaluations trigger exponential sub-graph traversals, causing severe latency degradation, worker thread starvation, and Denial-of-Service (DoS) vulnerabilities. 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 (Injecting Unsanitized Dynamic Contextual Tuples Directly into Authorization Checks Without Depth Caps or Graph Bounds) 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