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

OpenFGA Contextual Tuple Graph Traversal Bounded-Depth & Tenant Barrier Invariant

Enforces strict tenant boundary isolation and deterministic graph evaluation horizons during Relationship-Based Access Control (ReBAC) evaluations with OpenFGA. Prevents arbitrary cyclic contextual tuple injection, unbounded graph resolution denial-of-service, and cross-tenant privilege escalation (New Enemy problem).

Prohibited Anti-Pattern: Unsanitized Contextual Tuples and Unbounded Graph Traversal in OpenFGA Check Calls

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Contextual Tuple Graph Traversal Bounded-Depth & Tenant Barrier Invariant - Enforces strict tenant boundary isolation and deterministic graph evaluation horizons during Relationship-Based Access Control (ReBAC) evaluations with OpenFGA. Prevents arbitrary cyclic contextual tuple injection, unbounded graph resolution denial-of-service, and cross-tenant privilege escalation (New Enemy problem).
globs: src/**/authz/**/*.ts, src/**/permissions/**/*.ts, src/**/security/**/*.ts, src/**/fga/**/*.ts, src/**/middleware/authorize*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuple-bounded-depth-invariant"
---

# OpenFGA Contextual Tuple Graph Traversal Bounded-Depth & Tenant Barrier Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unsanitized Contextual Tuples and Unbounded Graph Traversal in OpenFGA Check Calls

## System Constraints
You are a Principal Security Architect enforcing the OpenFGA Contextual Tuple Graph Traversal Bounded-Depth and Tenant Isolation Invariant. You must reject any authorization check that permits arbitrary, user-controlled contextual tuples, missing tenant boundary assertions, or unconstrained recursive evaluation depths that expose systems to ReBAC exhaustion or cross-tenant privilege escalation.

## Strict Guidelines
- Engineers MUST ALWAYS validate and sanitize all contextual tuples against a strict schema and enforce that tuple subjects and objects reside strictly within the authenticated tenant boundary.
- Engineers MUST NEVER allow untrusted client input to directly inject arbitrary contextual tuples into OpenFGA `check`, `expand`, or `listObjects` invocations.
- Engineers MUST explicitly constrain OpenFGA evaluation depth via client configurations (e.g., setting `max_checks_per_call` and client-side evaluation timeouts) to prevent recursive graph expansion attacks.
- Services MUST ensure contextual tuples only represent transient, request-scoped facts (e.g., ephemeral step-up authentication or temporary break-glass scopes) and NEVER substitute persistent state storage.
- Engineers MUST enforce strict type-safe assertion barriers on contextual tuple relations to prevent cross-type traversal and transitive group leakage ('New Enemy' vulnerability).
- Components NEVER execute OpenFGA authorization checks without fallback circuit breakers and bounded cancellation signals (e.g., `AbortSignal` with maximum 500ms deadline).

## Bad vs Good Implementations
### Unsanitized Contextual Tuples Allowing Multi-Tenant Graph Hijacking and Cycle Exhaustion

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Untrusted contextual tuples are passed directly to OpenFGA without tenant validation, schema enforcement, or depth limiting. An attacker can supply circular group memberships triggering excessive compute or construct cross-tenant relation paths, causing DoS or unauthorized privilege escalation.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

// VULNERABLE: Directly accepting client-provided contextual tuples and omitting tenant boundaries
export async function authorizeUserAction(
  userId: string,
  relation: string,
  resourceId: string,
  clientSuppliedContextTuples: Array<{ user: string; relation: string; object: string }>
) {
  // Attacker can pass cycles: [{ user: 'user:X', relation: 'member', object: 'group:Y' }, { user: 'group:Y', relation: 'member', object: 'group:Y' }]
  // Attacker can pass foreign tenant objects: object: 'tenant-b:document-123'
  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation,
    object: `document:${resourceId}`,
    contextualTuples: clientSuppliedContextTuples,
  });

  return response.allowed;
}
```

#### Production Standard (Correct)
> **Standard**: Contextual tuples are strictly synthesized from validated server-side parameters with rigid tenant namespaces. Evaluation depth is bounded by strict schema relations and a rigid 400ms cancellation signal, preventing ReBAC evaluation denial-of-service and multi-tenant leakage.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';
import { z } from 'zod';

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

const ALLOWED_EPHEMERAL_RELATIONS = ['transient_editor', 'break_glass_viewer'] as const;

interface AuthorizationContext {
  tenantId: string;
  userId: string;
  action: 'view' | 'edit';
  documentId: string;
  ephemeralRole?: typeof ALLOWED_EPHEMERAL_RELATIONS[number];
}

export async function authorizeTenantAction(ctx: AuthorizationContext): Promise<boolean> {
  // 1. Enforce strict bounded execution horizon (deterministic timeout)
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), 400);

  try {
    // 2. Validate tenant-scoped identifier invariants
    const tenantPrefix = `tenant:${ctx.tenantId}`;
    const userEntity = `user:${ctx.tenantId}_${ctx.userId}`;
    const documentEntity = `document:${ctx.tenantId}_${ctx.documentId}`;

    // 3. Strict whitelist & synthesis of contextual tuples (never accept raw external tuples)
    const contextualTuples: ClientCheckRequest['contextualTuples'] = [];
    if (ctx.ephemeralRole && ALLOWED_EPHEMERAL_RELATIONS.includes(ctx.ephemeralRole)) {
      contextualTuples.push({
        user: userEntity,
        relation: ctx.ephemeralRole,
        object: documentEntity,
      });
    }

    const response = await fgaClient.check(
      {
        user: userEntity,
        relation: ctx.action === 'edit' ? 'can_edit' : 'can_view',
        object: documentEntity,
        contextualTuples,
      },
      { signal: controller.signal }
    );

    return Boolean(response.allowed);
  } catch (error) {
    // Fail closed on evaluation timeout, graph cycle, or context cancellation
    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 Bounded-Depth & Tenant Barrier Invariant

OpenFGA Contextual Tuple Graph Traversal Bounded-Depth & Tenant Barrier Invariant defines an industrial-grade behavioral standard for security engineering. Enforces strict tenant boundary isolation and deterministic graph evaluation horizons during Relationship-Based Access Control (ReBAC) evaluations with OpenFGA. Prevents arbitrary cyclic contextual tuple injection, unbounded graph resolution denial-of-service, and cross-tenant privilege escalation (New Enemy problem). 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: Unsanitized Contextual Tuples and Unbounded Graph Traversal in OpenFGA Check Calls 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 DriftUnsanitized Contextual Tuples and Unbounded Graph Traversal in OpenFGA Check CallsCritical
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 sanitize all contextual tuples against a strict schema and enforce that tuple subjects and objects reside strictly within the authenticated tenant boundary.

Engineers MUST ALWAYS validate and sanitize all contextual tuples against a strict schema and enforce that tuple subjects and objects reside strictly within the authenticated tenant boundary.

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 NEVER allow untrusted client input to directly inject arbitrary contextual tuples into OpenFGA `check`, `expand`, or `listObjects` invocations.

Engineers MUST NEVER allow untrusted client input to directly inject arbitrary contextual tuples into OpenFGA `check`, `expand`, or `listObjects` invocations.

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 explicitly constrain OpenFGA evaluation depth via client configurations (e.g., setting `max_checks_per_call` and client-side evaluation timeouts) to prevent recursive graph expansion attacks.

Engineers MUST explicitly constrain OpenFGA evaluation depth via client configurations (e.g., setting `max_checks_per_call` and client-side evaluation timeouts) to prevent recursive graph expansion attacks.

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 contextual tuples only represent transient, request-scoped facts (e.g., ephemeral step-up authentication or temporary break-glass scopes) and NEVER substitute persistent state storage.

Services MUST ensure contextual tuples only represent transient, request-scoped facts (e.g., ephemeral step-up authentication or temporary break-glass scopes) and NEVER substitute persistent state storage.

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

Engineers MUST enforce strict type-safe assertion barriers on contextual tuple relations to prevent cross-type traversal and transitive group leakage ('New Enemy' vulnerability).

Engineers MUST enforce strict type-safe assertion barriers on contextual tuple relations to prevent cross-type traversal and transitive group leakage ('New Enemy' vulnerability).

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

Components NEVER execute OpenFGA authorization checks without fallback circuit breakers and bounded cancellation signals (e.g., `AbortSignal` with maximum 500ms deadline).

Components NEVER execute OpenFGA authorization checks without fallback circuit breakers and bounded cancellation signals (e.g., `AbortSignal` with maximum 500ms deadline).

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 Bounded-Depth & Tenant Barrier Invariant critical for AI coding assistants?

Enforces strict tenant boundary isolation and deterministic graph evaluation horizons during Relationship-Based Access Control (ReBAC) evaluations with OpenFGA. Prevents arbitrary cyclic contextual tuple injection, unbounded graph resolution denial-of-service, and cross-tenant privilege escalation (New Enemy problem). 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 (Unsanitized Contextual Tuples and Unbounded Graph Traversal in OpenFGA Check Calls) 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