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

OpenFGA 1.8 Contextual Tuple Traversal Depth & Cycle Guardrail

Enforces strict boundaries, cycle prevention, and volume capping on OpenFGA contextual tuples to prevent catastrophic graph traversals during Zanzibar authorization checks. Unbounded dynamic tuple injection leads to distributed denial of service, memory exhaustion, and breached sub-millisecond evaluation SLOs. Mandates deterministic graph evaluation constraints before dispatching runtime checks.

Prohibited Anti-Pattern: Injecting Unsanitized Dynamic Contextual Tuples Causing Unbounded Graph Traversal and ReDoS-Style Exhaustion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA 1.8 Contextual Tuple Traversal Depth & Cycle Guardrail - Enforces strict boundaries, cycle prevention, and volume capping on OpenFGA contextual tuples to prevent catastrophic graph traversals during Zanzibar authorization checks. Unbounded dynamic tuple injection leads to distributed denial of service, memory exhaustion, and breached sub-millisecond evaluation SLOs. Mandates deterministic graph evaluation constraints before dispatching runtime checks.
globs: src/**/auth*/**/*.{ts,tsx,js,jsx}, src/**/guards/**/*.{ts,tsx,js,jsx}, src/**/policies/**/*.{ts,tsx,js,jsx}, src/**/access/**/*.{ts,tsx,js,jsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuples-depth-cycle-guardrail"
---

# OpenFGA 1.8 Contextual Tuple Traversal Depth & Cycle Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Injecting Unsanitized Dynamic Contextual Tuples Causing Unbounded Graph Traversal and ReDoS-Style Exhaustion

## System Constraints
You are a Principal Security Architect specializing in Google Zanzibar implementations and OpenFGA 1.8 internals. You mandate strict bounds on contextual tuples, traversal depth limits, cycle detection, and pre-evaluation sanitation to preserve sub-millisecond deterministic authorization evaluation. Enforce non-negotiable compile-time and runtime validation invariants.

## Strict Guidelines
- Engineers MUST ALWAYS enforce a hard upper bound (MAX_CONTEXTUAL_TUPLES <= 20) on contextual tuple collections passed to OpenFGA check evaluations.
- Engineers MUST NOT allow unvalidated or client-supplied relation types or target objects into contextual tuples without strict schema whitelisting.
- Code MUST sanitize contextual tuples to ensure no self-referential or cyclic graph edges are introduced prior to calling the authorization engine.
- Services MUST configure OpenFGA client timeout deadlines (<= 50ms) and use ConsistencyPreference.MINIMIZE_LATENCY for high-throughput operational paths.
- Components NEVER accept contextual tuples containing wildcard or type-bound public access modifiers (* or user:*) unless explicitly attested by cryptographic signature.

## Bad vs Good Implementations
### Unbounded Contextual Tuples Leading to Traversal Amplification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accepting dynamicContextTuples directly from request inputs without array size limits, relation whitelisting, or cycle detection permits adversarial graph construction. An attacker can construct recursive transitive relations or hundreds of mock relations, inducing catastrophic traversal latency and engine CPU exhaustion.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { Request, Response } from 'express';

const fga = new OpenFgaClient({ apiUrl: process.env.FGA_API_URL! });

export async function authorizeUserRequest(req: Request, res: Response) {
  const { userId, documentId, dynamicContextTuples } = req.body;

  // CRITICAL SECURITY FLAW: Directly forwarding arbitrary contextual tuples
  // allows attackers to inject cyclical relationships, deep inheritance chains,
  // or massive tuple arrays that cause OpenFGA graph traversal exhaustion.
  const { allowed } = await fga.check({
    user: `user:${userId}`,
    relation: 'can_view',
    object: `document:${documentId}`,
    contextualTuples: dynamicContextTuples
  });

  if (!allowed) {
    return res.status(403).json({ error: 'Access Denied' });
  }
  return res.status(200).json({ status: 'ok' });
}
```

#### Production Standard (Correct)
> **Standard**: Imposes strict runtime defenses: caps tuple count to 10, sanitizes identifiers, validates relations against an allowlist, rejects wildcards and immediate self-cycles, deduplicates edges, forces latency-minimized consistency, and wraps evaluation in an explicit 35ms AbortController timeout.
```typescript
import { OpenFgaClient, ClientCheckRequest, ConsistencyPreference } from '@openfga/sdk';
import { Request, Response } from 'express';

const MAX_CONTEXTUAL_TUPLES = 10;
const ALLOWED_DYNAMIC_RELATIONS = new Set(['temporary_viewer', 'current_session_grant']);
const CHECK_TIMEOUT_MS = 35;

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

function sanitizeContextualTuples(
  tuples: unknown[],
  targetUser: string,
  targetObject: string
): ClientCheckRequest['contextualTuples'] {
  if (!Array.isArray(tuples) || tuples.length > MAX_CONTEXTUAL_TUPLES) {
    throw new Error(`Contextual tuples exceeds safe limit of ${MAX_CONTEXTUAL_TUPLES}`);
  }

  const sanitized: ClientCheckRequest['contextualTuples'] = [];
  const seenEdges = new Set<string>();

  for (const item of tuples as RawContextualTuple[]) {
    if (!item?.user || !item?.relation || !item?.object) {
      throw new Error('Malformed contextual tuple payload');
    }

    // Invariant: Enforce relation whitelist
    if (!ALLOWED_DYNAMIC_RELATIONS.has(item.relation)) {
      throw new Error(`Unauthorized dynamic relation: ${item.relation}`);
    }

    // Invariant: Immediate self-referential cycle detection
    if (item.user === item.object) {
      throw new Error('Cyclic direct self-assignment detected');
    }

    // Invariant: Prevent wildcards and duplicate edges
    if (item.user.includes('*') || item.object.includes('*')) {
      throw new Error('Wildcards forbidden in contextual evaluation');
    }

    const edgeKey = `${item.user}#${item.relation}@${item.object}`;
    if (seenEdges.has(edgeKey)) continue;
    seenEdges.add(edgeKey);

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

  return sanitized;
}

export async function authorizeUserRequest(req: Request, res: Response) {
  const { userId, documentId, dynamicContextTuples } = req.body;

  const safeUser = `user:${encodeURIComponent(userId)}`;
  const safeObject = `document:${encodeURIComponent(documentId)}`;

  let validTuples: ClientCheckRequest['contextualTuples'] = [];
  try {
    validTuples = sanitizeContextualTuples(dynamicContextTuples, safeUser, safeObject);
  } catch (err) {
    return res.status(400).json({ error: (err as Error).message });
  }

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

  try {
    const response = await fga.check(
      {
        user: safeUser,
        relation: 'can_view',
        object: safeObject,
        contextualTuples: validTuples,
        consistency: ConsistencyPreference.MINIMIZE_LATENCY
      },
      { signal: controller.signal }
    );

    if (!response.allowed) {
      return res.status(403).json({ error: 'Access Denied' });
    }
    return res.status(200).json({ status: 'ok' });
  } catch (err: any) {
    return res.status(err.name === 'AbortError' ? 504 : 500).json({ error: 'Authorization evaluation failed' });
  } finally {
    clearTimeout(timeout);
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA 1.8 Contextual Tuple Traversal Depth & Cycle Guardrail

OpenFGA 1.8 Contextual Tuple Traversal Depth & Cycle Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces strict boundaries, cycle prevention, and volume capping on OpenFGA contextual tuples to prevent catastrophic graph traversals during Zanzibar authorization checks. Unbounded dynamic tuple injection leads to distributed denial of service, memory exhaustion, and breached sub-millisecond evaluation SLOs. Mandates deterministic graph evaluation constraints before dispatching runtime checks. 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 Causing Unbounded Graph Traversal and ReDoS-Style 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 DriftInjecting Unsanitized Dynamic Contextual Tuples Causing Unbounded Graph Traversal and ReDoS-Style 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 a hard upper bound (MAX_CONTEXTUAL_TUPLES <= 20) on contextual tuple collections passed to OpenFGA check evaluations.

Engineers MUST ALWAYS enforce a hard upper bound (MAX_CONTEXTUAL_TUPLES <= 20) on contextual tuple collections passed to OpenFGA check evaluations.

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 allow unvalidated or client-supplied relation types or target objects into contextual tuples without strict schema whitelisting.

Engineers MUST NOT allow unvalidated or client-supplied relation types or target objects into contextual tuples without strict schema 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.
3

Code MUST sanitize contextual tuples to ensure no self-referential or cyclic graph edges are introduced prior to calling the authorization engine.

Code MUST sanitize contextual tuples to ensure no self-referential or cyclic graph edges are introduced prior to calling the authorization engine.

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 configure OpenFGA client timeout deadlines (<= 50ms) and use ConsistencyPreference.MINIMIZE_LATENCY for high-throughput operational paths.

Services MUST configure OpenFGA client timeout deadlines (<= 50ms) and use ConsistencyPreference.MINIMIZE_LATENCY for high-throughput operational paths.

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 accept contextual tuples containing wildcard or type-bound public access modifiers (* or user

Components NEVER accept contextual tuples containing wildcard or type-bound public access modifiers (* or user:*) unless explicitly attested by cryptographic signature.

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

Enforces strict boundaries, cycle prevention, and volume capping on OpenFGA contextual tuples to prevent catastrophic graph traversals during Zanzibar authorization checks. Unbounded dynamic tuple injection leads to distributed denial of service, memory exhaustion, and breached sub-millisecond evaluation SLOs. Mandates deterministic graph evaluation constraints before dispatching runtime checks. 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 Causing Unbounded Graph Traversal and ReDoS-Style 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