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

OpenFGA Contextual Tuple Graph Traversal and Latency Bounds Guardrail

Enforces deterministic computational and memory bounds on OpenFGA dynamic contextual tuples during Check and Expand evaluations. Prevents algorithmic complexity denial-of-service (ReDoS/GraphDoS) and p99 latency degradation by capping contextual tuple cardinality, depth, and payload size to guarantee sub-10ms authorization response times.

Prohibited Anti-Pattern: Unbounded contextual tuple injection triggering combinatorial graph traversals and engine latency spikes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Contextual Tuple Graph Traversal and Latency Bounds Guardrail - Enforces deterministic computational and memory bounds on OpenFGA dynamic contextual tuples during Check and Expand evaluations. Prevents algorithmic complexity denial-of-service (ReDoS/GraphDoS) and p99 latency degradation by capping contextual tuple cardinality, depth, and payload size to guarantee sub-10ms authorization response times.
globs: src/auth/**/*.ts, src/services/authz/**/*.ts, src/middleware/authorization/**/*.ts, lib/openfga/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuple-bounded-traversal-standard"
---

# OpenFGA Contextual Tuple Graph Traversal and Latency Bounds Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded contextual tuple injection triggering combinatorial graph traversals and engine latency spikes

## System Constraints
You are a Principal Engineer enforcing the OpenFGA Contextual Tuple Graph Traversal Standard. Mandate deterministic computational bounds, strict tuple payload validation, cardinality limits (maximum 20 contextual tuples per evaluation), and a hard 10ms execution budget for ReBAC evaluations.

## Strict Guidelines
- Engineers MUST ALWAYS validate and strictly enforce cardinality limits on contextual_tuples (maximum 20 tuples per Check invocation) prior to issuing the API request.
- Engineers MUST NOT inject cyclic, self-referencing, or arbitrarily nested relation paths into dynamic contextual tuple payloads.
- Code SHOULD enforce strict structural schema validation on user, relation, and object fields using canonical OpenFGA type constraints before graph traversal.
- Services MUST enforce an end-to-end deadline of 10ms (with a 15ms hard abort timeout) on OpenFGA Check operations using an AbortController or context deadline.
- Components NEVER pass unbounded user-controlled collections (such as raw Active Directory claims or multi-tenant group hierarchies) directly into contextual tuples without pre-filtering and deduping against the authorization model schema.

## Bad vs Good Implementations
### Unbounded dynamic tuple injection vs. bounded, validated contextual authorization check

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly mapping an unbounded array of external groups into contextual tuples without cardinality limits, depth validation, or request deadlines exposes the authorization engine to algorithmic traversal exhaustion and latency degradation far beyond 10ms.
```typescript
import { OpenFgaClient, type ClientCheckRequest } from '@openfga/sdk';

export async function evaluateAccess(
  fgaClient: OpenFgaClient,
  userId: string,
  resourceId: string,
  dynamicGroups: string[] // User-supplied or identity-provider groups with arbitrary length
): Promise<boolean> {
  // ANTI-PATTERN: Blindly converting unbounded lists into contextual tuples.
  // A user with hundreds of groups causes catastrophic graph expansion,
  // memory exhaustion in the FGA engine, and p99 latency spikes exceeding 250ms.
  const contextualTuples = dynamicGroups.map((groupId) => ({
    user: `user:${userId}`,
    relation: 'member',
    object: `group:${groupId}`,
  }));

  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'viewer',
    object: `document:${resourceId}`,
    contextualTuples,
  });

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

#### Production Standard (Correct)
> **Standard**: Enforces a strict upper bound of 20 contextual tuples, deduplicates entries, sanitizes identifiers, and binds the invocation to a strict 10ms abort deadline, preventing graph traversal attacks and ensuring bounded latency.
```typescript
import { OpenFgaClient, type ClientCheckRequest } from '@openfga/sdk';

const MAX_CONTEXTUAL_TUPLES = 20;
const EVALUATION_TIMEOUT_MS = 10;

interface ValidatedTuple {
  user: `user:${string}`;
  relation: string;
  object: `${string}:${string}`;
}

export async function evaluateAccess(
  fgaClient: OpenFgaClient,
  userId: string,
  resourceId: string,
  dynamicGroups: readonly string[]
): Promise<boolean> {
  // INVARIANT 1: Strict deduplication and cardinality bounding
  const uniqueGroups = Array.from(new Set(dynamicGroups)).slice(0, MAX_CONTEXTUAL_TUPLES);

  // INVARIANT 2: Explicit schema and type sanitization
  const contextualTuples: ValidatedTuple[] = uniqueGroups.map((groupId) => ({
    user: `user:${encodeURIComponent(userId)}`,
    relation: 'member',
    object: `group:${encodeURIComponent(groupId)}`,
  }));

  // INVARIANT 3: Strict sub-10ms timeout enforcement via AbortController
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), EVALUATION_TIMEOUT_MS);

  try {
    const payload: ClientCheckRequest = {
      user: `user:${encodeURIComponent(userId)}`,
      relation: 'viewer',
      object: `document:${encodeURIComponent(resourceId)}`,
      contextualTuples,
    };

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

    return response.allowed ?? false;
  } catch (error: unknown) {
    if (error instanceof Error && error.name === 'AbortError') {
      // Fallback: Fail closed on latency budget breach to prevent ReDoS
      throw new Error(`OpenFGA Check exceeded latency budget of ${EVALUATION_TIMEOUT_MS}ms`);
    }
    throw error;
  } finally {
    clearTimeout(timeoutId);
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA Contextual Tuple Graph Traversal and Latency Bounds Guardrail

OpenFGA Contextual Tuple Graph Traversal and Latency Bounds Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces deterministic computational and memory bounds on OpenFGA dynamic contextual tuples during Check and Expand evaluations. Prevents algorithmic complexity denial-of-service (ReDoS/GraphDoS) and p99 latency degradation by capping contextual tuple cardinality, depth, and payload size to guarantee sub-10ms authorization response times. 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 injection triggering combinatorial graph traversals and engine latency spikes 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 injection triggering combinatorial graph traversals and engine latency spikesCritical
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 strictly enforce cardinality limits on contextual_tuples (maximum 20 tuples per Check invocation) prior to issuing the API request.

Engineers MUST ALWAYS validate and strictly enforce cardinality limits on contextual_tuples (maximum 20 tuples per Check invocation) prior to issuing the API request.

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 inject cyclic, self-referencing, or arbitrarily nested relation paths into dynamic contextual tuple payloads.

Engineers MUST NOT inject cyclic, self-referencing, or arbitrarily nested relation paths into dynamic contextual tuple payloads.

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 SHOULD enforce strict structural schema validation on user, relation, and object fields using canonical OpenFGA type constraints before graph traversal.

Code SHOULD enforce strict structural schema validation on user, relation, and object fields using canonical OpenFGA type constraints before graph traversal.

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 enforce an end-to-end deadline of 10ms (with a 15ms hard abort timeout) on OpenFGA Check operations using an AbortController or context deadline.

Services MUST enforce an end-to-end deadline of 10ms (with a 15ms hard abort timeout) on OpenFGA Check operations using an AbortController or context 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.
5

Components NEVER pass unbounded user-controlled collections (such as raw Active Directory claims or multi-tenant group hierarchies) directly into contextual tuples without pre-filtering and deduping against the authorization model schema.

Components NEVER pass unbounded user-controlled collections (such as raw Active Directory claims or multi-tenant group hierarchies) directly into contextual tuples without pre-filtering and deduping against the authorization model schema.

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 and Latency Bounds Guardrail critical for AI coding assistants?

Enforces deterministic computational and memory bounds on OpenFGA dynamic contextual tuples during Check and Expand evaluations. Prevents algorithmic complexity denial-of-service (ReDoS/GraphDoS) and p99 latency degradation by capping contextual tuple cardinality, depth, and payload size to guarantee sub-10ms authorization response times. 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 injection triggering combinatorial graph traversals and engine latency spikes) 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