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

OpenFGA 1.6 Contextual Tuple Bounded-Resolution Invariant

Enforces deterministic depth ceilings, strict cardinality limits, and deduplicated subgraph traversal when injecting dynamic contextual tuples into OpenFGA 1.6 Check calls. Prevents algorithmic graph-traversal exhaustion attacks, circular dependency deadlocks, and severe tail-latency spikes across real-time RBAC/ABAC authorization boundaries.

Prohibited Anti-Pattern: Unbounded Contextual Tuple Ingestion Inducing Pathological Graph Traversal and Latency Explosions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA 1.6 Contextual Tuple Bounded-Resolution Invariant - Enforces deterministic depth ceilings, strict cardinality limits, and deduplicated subgraph traversal when injecting dynamic contextual tuples into OpenFGA 1.6 Check calls. Prevents algorithmic graph-traversal exhaustion attacks, circular dependency deadlocks, and severe tail-latency spikes across real-time RBAC/ABAC authorization boundaries.
globs: src/**/auth/**/*.{ts,js,go}, src/**/guards/**/*.{ts,js,go}, src/**/authorization/**/*.{ts,js,go}, src/**/openfga/**/*.{ts,js,go}, lib/**/permissions/**/*.{ts,js,go}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuple-bounded-resolution"
---

# OpenFGA 1.6 Contextual Tuple Bounded-Resolution Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded Contextual Tuple Ingestion Inducing Pathological Graph Traversal and Latency Explosions

## System Constraints
You are a Principal Security Architect and Performance Engineer enforcing the OpenFGA 1.6 Contextual Tuple Bounded-Resolution Invariant. Mandate that every authorization evaluation incorporating dynamic contextual tuples adheres strictly to bounded graph resolution limits, tuple cardinality thresholds, canonical deduplication, and fail-closed timeout budgets to safeguard distributed authorization engines against tail-latency amplification and graph explosion DoS vulnerabilities.

## Strict Guidelines
- Engineers MUST ALWAYS validate and enforce a strict cardinality cap (maximum 50 contextual tuples by default) prior to dispatching queries to the OpenFGA client.
- Engineers MUST canonicalize, sort, and deduplicate contextual tuples prior to request invocation to maximize OpenFGA subgraph memoization and internal cache hits.
- Engineers MUST NOT inject cyclical or self-referential contextual tuples (e.g., `user:X` related to `user:X` or reflexive direct relations) into OpenFGA Check requests.
- Services MUST bound the authorization evaluation using an aggressive, explicit cancellation deadline (e.g., `AbortSignal.timeout(150)` max 150ms) to prevent p99 tail-latency propagation.
- Services MUST configure OpenFGA client max-depth and max-checks-per-node limits explicitly to enforce finite subgraph traversal boundaries.
- Components NEVER accept raw, unsanitized client-supplied arrays as contextual tuples without schema validation and user-ID binding.

## Bad vs Good Implementations
### Bounded and Deduplicated Contextual Tuple Resolution vs. Unbounded Injection

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accepting untrusted contextual tuples without cardinality limits allows attackers to inject hundreds of arbitrary relations or cyclic graphs. Omitting deduplication prevents OpenFGA from leveraging internal memoization caches, and omitting an explicit AbortSignal timeout allows deep subgraph traversals to tie up authorization worker threads and produce multi-second p99 tail-latency spikes.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

// ANTI-PATTERN: Direct injection of client-provided contextual tuples without bounds,
// deduplication, cycle checks, or timeouts. Exposes the engine to graph explosion DoS.
export async function checkAccessUnbounded(
  userId: string,
  relation: string,
  objectId: string,
  untrustedContextualTuples: Array<{ user: string; relation: string; object: string }>
): Promise<boolean> {
  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation,
    object: objectId,
    contextualTuples: untrustedContextualTuples,
  });

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

#### Production Standard (Correct)
> **Standard**: Enforces a hard limit on contextual tuple cardinality, eliminates redundant relations to maximize OpenFGA traversal memoization, discards self-referential cycles, and establishes a strict 150ms timeout using AbortSignal to eliminate tail-latency amplification attacks.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

const MAX_CONTEXTUAL_TUPLES = 50;
const CHECK_TIMEOUT_MS = 150;

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

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

// PRODUCTION INVARIANT: Validated, bounded cardinality, deduplicated, acyclic guardrail
export async function checkAccessBounded(
  userId: string,
  relation: string,
  objectId: string,
  rawContextualTuples: readonly TupleKey[]
): Promise<boolean> {
  if (rawContextualTuples.length > MAX_CONTEXTUAL_TUPLES) {
    throw new Error(`Contextual tuple cardinality limit exceeded (max: ${MAX_CONTEXTUAL_TUPLES})`);
  }

  // Deduplicate and canonicalize tuples to optimize OpenFGA subgraph traversal caching
  const tupleSet = new Set<string>();
  const boundedTuples: TupleKey[] = [];

  for (const t of rawContextualTuples) {
    // Reject self-referential relations that cause traversal overhead or cycles
    if (t.user === t.object) {
      continue;
    }
    const key = `${t.user}#${t.relation}@${t.object}`;
    if (!tupleSet.has(key)) {
      tupleSet.add(key);
      boundedTuples.push({ user: t.user, relation: t.relation, object: t.object });
    }
  }

  const payload: ClientCheckRequest = {
    user: `user:${userId}`,
    relation,
    object: objectId,
    contextualTuples: boundedTuples,
  };

  try {
    const response = await fgaClient.check(payload, {
      signal: AbortSignal.timeout(CHECK_TIMEOUT_MS),
    });
    return response.allowed ?? false;
  } catch (error) {
    // Fail closed on timeout or resolution abort to preserve security invariants
    return false;
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA 1.6 Contextual Tuple Bounded-Resolution Invariant

OpenFGA 1.6 Contextual Tuple Bounded-Resolution Invariant defines an industrial-grade behavioral standard for security engineering. Enforces deterministic depth ceilings, strict cardinality limits, and deduplicated subgraph traversal when injecting dynamic contextual tuples into OpenFGA 1.6 Check calls. Prevents algorithmic graph-traversal exhaustion attacks, circular dependency deadlocks, and severe tail-latency spikes across real-time RBAC/ABAC authorization boundaries. 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 Ingestion Inducing Pathological Graph Traversal and Latency Explosions 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 Ingestion Inducing Pathological Graph Traversal and Latency ExplosionsCritical
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 enforce a strict cardinality cap (maximum 50 contextual tuples by default) prior to dispatching queries to the OpenFGA client.

Engineers MUST ALWAYS validate and enforce a strict cardinality cap (maximum 50 contextual tuples by default) prior to dispatching queries to the OpenFGA client.

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 canonicalize, sort, and deduplicate contextual tuples prior to request invocation to maximize OpenFGA subgraph memoization and internal cache hits.

Engineers MUST canonicalize, sort, and deduplicate contextual tuples prior to request invocation to maximize OpenFGA subgraph memoization and internal cache hits.

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 inject cyclical or self-referential contextual tuples (e.g., `user

Engineers MUST NOT inject cyclical or self-referential contextual tuples (e.g., `user:X` related to `user:X` or reflexive direct relations) into OpenFGA Check requests.

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 bound the authorization evaluation using an aggressive, explicit cancellation deadline (e.g., `AbortSignal.timeout(150)` max 150ms) to prevent p99 tail-latency propagation.

Services MUST bound the authorization evaluation using an aggressive, explicit cancellation deadline (e.g., `AbortSignal.timeout(150)` max 150ms) to prevent p99 tail-latency propagation.

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 configure OpenFGA client max-depth and max-checks-per-node limits explicitly to enforce finite subgraph traversal boundaries.

Services MUST configure OpenFGA client max-depth and max-checks-per-node limits explicitly to enforce finite subgraph traversal boundaries.

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 accept raw, unsanitized client-supplied arrays as contextual tuples without schema validation and user-ID binding.

Components NEVER accept raw, unsanitized client-supplied arrays as contextual tuples without schema validation and user-ID binding.

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.6 Contextual Tuple Bounded-Resolution Invariant critical for AI coding assistants?

Enforces deterministic depth ceilings, strict cardinality limits, and deduplicated subgraph traversal when injecting dynamic contextual tuples into OpenFGA 1.6 Check calls. Prevents algorithmic graph-traversal exhaustion attacks, circular dependency deadlocks, and severe tail-latency spikes across real-time RBAC/ABAC authorization boundaries. 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 Ingestion Inducing Pathological Graph Traversal and Latency Explosions) 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