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

OpenFGA Contextual Tuple Evaluation Timeout & Cycle-Breaking Guardrail

Enforces strict deadline propagation, cycle detection, and input cardinality bounds when executing OpenFGA authorization checks with contextual tuples. Prevents unbounded graph traversals, distributed resource exhaustion, and Denial-of-Service attacks triggered by circular group memberships or deep nested relational paths during dynamic authorization queries.

Prohibited Anti-Pattern: Unbounded Contextual Tuples with Missing Deadlines Leading to Graph Traversals and Resource Exhaustion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Contextual Tuple Evaluation Timeout & Cycle-Breaking Guardrail - Enforces strict deadline propagation, cycle detection, and input cardinality bounds when executing OpenFGA authorization checks with contextual tuples. Prevents unbounded graph traversals, distributed resource exhaustion, and Denial-of-Service attacks triggered by circular group memberships or deep nested relational paths during dynamic authorization queries.
globs: src/auth/**/*.{ts,js}, src/services/**/*.{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-timeout-cycle-breaking-guardrail"
---

# OpenFGA Contextual Tuple Evaluation Timeout & Cycle-Breaking Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded Contextual Tuples with Missing Deadlines Leading to Graph Traversals and Resource Exhaustion

## System Constraints
You are a Principal Security Architect enforcing resilient Fine-Grained Authorization (FGA) patterns. Contextual tuples passed to OpenFGA Check and ListObjects APIs evaluate transient relationships in-memory alongside persistent tuples. Malicious actors or misconfigured graph definitions can introduce cyclic dependencies or excessive depth, causing recursive evaluation loops and catastrophic server-side resource exhaustion. You must mandate strict request timeouts via AbortSignal, enforce a ceiling on contextual tuple counts, sanitize relational graph inputs against cyclic duplicates, and guarantee fail-closed fallback mechanisms.

## Strict Guidelines
- Engineers MUST ALWAYS enforce strict timeouts on OpenFGA Check calls using AbortController with a maximum deadline (e.g., 200ms for online API checks).
- Engineers MUST validate and limit the total count of contextual tuples injected into a single Check request (default maximum: 20 tuples) to prevent memory exhaustion.
- Engineers MUST NOT accept arbitrary self-referential or cyclic contextual tuples (e.g., user:X is member of group:A, where group:A is member of group:A) directly from untrusted client input.
- Code MUST fail closed with an explicit denial whenever an OpenFGA evaluation times out, aborts, or returns a 4xx/5xx evaluation error.
- Services MUST implement in-memory visited-node cycle detection or structural validation before transforming request payloads into OpenFGA contextual tuples.
- Engineers MUST configure OpenFGA client instances with maxRetries set to 0 or 1 for online evaluation checks to avoid compounding latency during degraded cluster states.

## Bad vs Good Implementations
### Vulnerable vs. Resilient OpenFGA Contextual Tuple Evaluation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The check function accepts arbitrary numbers of contextual tuples without validation, permitting self-referencing loops and deeply nested graph structures. It lacks an AbortSignal timeout, meaning a cyclic or pathological evaluation path will monopolize OpenFGA engine resources and block client threads until HTTP sockets drop.
```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 checkAccess(userId: string, objectId: string, untrustedTuples: Array<{ user: string; relation: string; object: string }>) {
  // VULNERABILITY 1: Unbounded contextual tuples passed directly from untrusted input
  // VULNERABILITY 2: No evaluation timeout or AbortController
  // VULNERABILITY 3: Cyclic relational paths can freeze the evaluation thread
  // VULNERABILITY 4: Inadequate error handling fails open or causes unhandled promise rejections
  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'viewer',
    object: `document:${objectId}`,
    contextualTuples: untrustedTuples,
  });

  return response.allowed;
}
```

#### Production Standard (Correct)
> **Standard**: Enforces a strict 200ms evaluation deadline using AbortController, limits contextual tuples to 20, eliminates self-referential relations, deduplicates entries, and guarantees fail-closed behavior on timeouts or engine errors.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

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

const MAX_CONTEXTUAL_TUPLES = 20;
const CHECK_TIMEOUT_MS = 200;

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

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

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

  for (const tuple of tuples) {
    // Reject direct self-referential loops
    if (tuple.user === tuple.object) {
      continue;
    }
    const key = `${tuple.user}#${tuple.relation}@${tuple.object}`;
    if (!seen.has(key)) {
      seen.add(key);
      sanitized.push(tuple);
    }
  }
  return sanitized;
}

export async function checkAccess(
  userId: string,
  objectId: string,
  rawTuples: TupleKey[] = []
): Promise<boolean> {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), CHECK_TIMEOUT_MS);

  try {
    const contextualTuples = validateAndDeduplicateTuples(rawTuples);
    const checkPayload: ClientCheckRequest = {
      user: `user:${userId}`,
      relation: 'viewer',
      object: `document:${objectId}`,
      contextualTuples,
    };

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

    return Boolean(response.allowed);
  } catch (error: unknown) {
    // Fail closed: Log the error and deny access
    console.error('OpenFGA check evaluation aborted or failed:', error);
    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 Evaluation Timeout & Cycle-Breaking Guardrail

OpenFGA Contextual Tuple Evaluation Timeout & Cycle-Breaking Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces strict deadline propagation, cycle detection, and input cardinality bounds when executing OpenFGA authorization checks with contextual tuples. Prevents unbounded graph traversals, distributed resource exhaustion, and Denial-of-Service attacks triggered by circular group memberships or deep nested relational paths during dynamic authorization queries. 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 with Missing Deadlines Leading to Graph Traversals and Resource 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 with Missing Deadlines Leading to Graph Traversals and Resource 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 timeouts on OpenFGA Check calls using AbortController with a maximum deadline (e.g., 200ms for online API checks).

Engineers MUST ALWAYS enforce strict timeouts on OpenFGA Check calls using AbortController with a maximum deadline (e.g., 200ms for online API checks).

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 validate and limit the total count of contextual tuples injected into a single Check request (default maximum

Engineers MUST validate and limit the total count of contextual tuples injected into a single Check request (default maximum: 20 tuples) to prevent memory exhaustion.

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 arbitrary self-referential or cyclic contextual tuples (e.g., user

Engineers MUST NOT accept arbitrary self-referential or cyclic contextual tuples (e.g., user:X is member of group:A, where group:A is member of group:A) directly from untrusted client input.

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

Code MUST fail closed with an explicit denial whenever an OpenFGA evaluation times out, aborts, or returns a 4xx/5xx evaluation error.

Code MUST fail closed with an explicit denial whenever an OpenFGA evaluation times out, aborts, or returns a 4xx/5xx evaluation error.

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 implement in-memory visited-node cycle detection or structural validation before transforming request payloads into OpenFGA contextual tuples.

Services MUST implement in-memory visited-node cycle detection or structural validation before transforming request payloads into OpenFGA contextual tuples.

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.
6

Engineers MUST configure OpenFGA client instances with maxRetries set to 0 or 1 for online evaluation checks to avoid compounding latency during degraded cluster states.

Engineers MUST configure OpenFGA client instances with maxRetries set to 0 or 1 for online evaluation checks to avoid compounding latency during degraded cluster states.

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 Evaluation Timeout & Cycle-Breaking Guardrail critical for AI coding assistants?

Enforces strict deadline propagation, cycle detection, and input cardinality bounds when executing OpenFGA authorization checks with contextual tuples. Prevents unbounded graph traversals, distributed resource exhaustion, and Denial-of-Service attacks triggered by circular group memberships or deep nested relational paths during dynamic authorization queries. 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 with Missing Deadlines Leading to Graph Traversals and Resource 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