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-guardrail

OpenFGA 1.6 Contextual Tuple Bounded Resolution & Graph Invariant Guardrail

Enforces strict bounds, relation whitelisting, and cycle-safe ingestion on dynamic OpenFGA contextual tuples during authorization checks. Prevents unbounded graph traversals, traversal-induced denial of service (DoS), and latency degradation to guarantee deterministic sub-10ms p99 ReBAC resolutions.

Prohibited Anti-Pattern: Injecting Unsanitized, Unbounded Dynamic Contextual Tuples into OpenFGA Check Calls

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA 1.6 Contextual Tuple Bounded Resolution & Graph Invariant Guardrail - Enforces strict bounds, relation whitelisting, and cycle-safe ingestion on dynamic OpenFGA contextual tuples during authorization checks. Prevents unbounded graph traversals, traversal-induced denial of service (DoS), and latency degradation to guarantee deterministic sub-10ms p99 ReBAC resolutions.
globs: src/**/*.{ts,tsx,js,jsx}, lib/**/*.{ts,js}, services/**/*.{ts,js}, fga/**/*.fga
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuple-bounded-resolution-guardrail"
---

# OpenFGA 1.6 Contextual Tuple Bounded Resolution & Graph Invariant Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Injecting Unsanitized, Unbounded Dynamic Contextual Tuples into OpenFGA Check Calls

## System Constraints
You are a Principal Software Architect enforcing the OpenFGA 1.6 Contextual Tuple Bounded Resolution Guardrail. Dynamic contextual tuples allow runtime authorization evaluation but introduce critical attack surfaces: unbounded array sizing leads to database connection exhaustion, while unchecked dynamic hierarchy relations can construct cyclic or exponential subgraphs causing catastrophic traversal depth expansion. You MUST mandate strict input boundaries, relation allowlisting, explicit context deadlines, and schema verification on every authorization check invocation.

## Strict Guidelines
- Engineers MUST ALWAYS bound contextual tuples to a hard limit (maximum 20 tuples per Check evaluation) validated at runtime via schema boundaries.
- Engineers MUST NOT allow client-supplied contextual tuples to modify structural or transitive hierarchy relations (e.g., 'parent', 'owner', 'tenant', 'group_member'); contextual tuples MUST ONLY supply ephemeral, localized state (e.g., 'current_device', 'ephemeral_ip_grant', 'session_verified').
- Code MUST enforce strict runtime validation on user, relation, and object formatting using typed schemas (e.g., Zod) before constructing OpenFGA ClientCheckRequest payloads.
- Services MUST execute OpenFGA Check operations with an explicit AbortSignal deadline configured for no more than 25ms total execution time to fail fast against traversal degradation.
- Components NEVER accept arbitrary tuple dictionaries or untyped JSON arrays from untrusted HTTP request bodies directly into OpenFGA SDK check functions.

## Bad vs Good Implementations
### Unbounded Contextual Tuples vs. Bounded, Allowlisted Ephemeral Tuple Ingestion

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Client input is injected directly into OpenFGA contextualTuples. An attacker can provide hundreds of tuples or forge structural relations (such as folder:A#parent@folder:B and folder:B#parent@folder:A), triggering recursive evaluation loops, high CPU utilization on OpenFGA clusters, and severe p99 latency spikes exceeding SLA limits.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { Request, Response } from 'express';

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

// ANTI-PATTERN: Direct injection of client-supplied contextual tuples
// Allows unconstrained array sizing and structural cycle injection (e.g., parent/ancestor loops)
export async function authorizeDocumentAccess(req: Request, res: Response) {
  const { userId, documentId, dynamicTuples } = req.body;

  const { allowed } = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'can_read',
    object: `document:${documentId}`,
    contextualTuples: dynamicTuples, // DANGEROUS: Unbounded & allows recursive graph expansion
  });

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

#### Production Standard (Correct)
> **Standard**: The updated implementation strictly caps contextual tuples using Zod to a maximum of 10 items, allowlists only ephemeral operational relations (preventing structural cycle injection), validates string syntax, and enforces an explicit 25ms AbortSignal deadline to guarantee fail-safe sub-10ms p99 behavior.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';
import { z } from 'zod';
import { Request, Response } from 'express';

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

const MAX_CONTEXTUAL_TUPLES = 10;
const ALLOWED_EPHEMERAL_RELATIONS = ['device_trusted', 'mfa_verified', 'ip_allowlisted'] as const;

const EphemeralTupleSchema = z.object({
  user: z.string().regex(/^user:[a-zA-Z0-9_-]+$/),
  relation: z.enum(ALLOWED_EPHEMERAL_RELATIONS),
  object: z.string().regex(/^(session|network):[a-zA-Z0-9_.-]+$/),
});

const CheckPayloadSchema = z.object({
  userId: z.string().uuid(),
  documentId: z.string().uuid(),
  dynamicTuples: z.array(EphemeralTupleSchema).max(MAX_CONTEXTUAL_TUPLES).default([]),
});

export async function authorizeDocumentAccess(req: Request, res: Response) {
  const parseResult = CheckPayloadSchema.safeParse(req.body);
  if (!parseResult.success) {
    return res.status(400).json({ error: 'Malformed authorization payload', details: parseResult.error.format() });
  }

  const { userId, documentId, dynamicTuples } = parseResult.data;

  const checkRequest: ClientCheckRequest = {
    user: `user:${userId}`,
    relation: 'can_read',
    object: `document:${documentId}`,
    contextualTuples: dynamicTuples,
  };

  try {
    // Bound latency via hard cancellation signal to guarantee sub-10ms p99 operational envelope
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 25);

    const { allowed } = await fgaClient.check(checkRequest, { signal: controller.signal });
    clearTimeout(timeoutId);

    if (!allowed) {
      return res.status(403).json({ error: 'Forbidden' });
    }
    return res.status(200).json({ status: 'ok' });
  } catch (error: unknown) {
    if (error instanceof Error && error.name === 'AbortError') {
      return res.status(504).json({ error: 'Authorization evaluation timeout exceeded' });
    }
    return res.status(500).json({ error: 'Authorization verification failed' });
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA 1.6 Contextual Tuple Bounded Resolution & Graph Invariant Guardrail

OpenFGA 1.6 Contextual Tuple Bounded Resolution & Graph Invariant Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces strict bounds, relation whitelisting, and cycle-safe ingestion on dynamic OpenFGA contextual tuples during authorization checks. Prevents unbounded graph traversals, traversal-induced denial of service (DoS), and latency degradation to guarantee deterministic sub-10ms p99 ReBAC resolutions. 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, Unbounded Dynamic Contextual Tuples into 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 DriftInjecting Unsanitized, Unbounded Dynamic Contextual Tuples into 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 bound contextual tuples to a hard limit (maximum 20 tuples per Check evaluation) validated at runtime via schema boundaries.

Engineers MUST ALWAYS bound contextual tuples to a hard limit (maximum 20 tuples per Check evaluation) validated at runtime via schema 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.
2

Engineers MUST NOT allow client-supplied contextual tuples to modify structural or transitive hierarchy relations (e.g., 'parent', 'owner', 'tenant', 'group_member')

Engineers MUST NOT allow client-supplied contextual tuples to modify structural or transitive hierarchy relations (e.g., 'parent', 'owner', 'tenant', 'group_member'); contextual tuples MUST ONLY supply ephemeral, localized state (e.g., 'current_device', 'ephemeral_ip_grant', 'session_verified').

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 enforce strict runtime validation on user, relation, and object formatting using typed schemas (e.g., Zod) before constructing OpenFGA ClientCheckRequest payloads.

Code MUST enforce strict runtime validation on user, relation, and object formatting using typed schemas (e.g., Zod) before constructing OpenFGA ClientCheckRequest 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.
4

Services MUST execute OpenFGA Check operations with an explicit AbortSignal deadline configured for no more than 25ms total execution time to fail fast against traversal degradation.

Services MUST execute OpenFGA Check operations with an explicit AbortSignal deadline configured for no more than 25ms total execution time to fail fast against traversal degradation.

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 arbitrary tuple dictionaries or untyped JSON arrays from untrusted HTTP request bodies directly into OpenFGA SDK check functions.

Components NEVER accept arbitrary tuple dictionaries or untyped JSON arrays from untrusted HTTP request bodies directly into OpenFGA SDK check functions.

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 & Graph Invariant Guardrail critical for AI coding assistants?

Enforces strict bounds, relation whitelisting, and cycle-safe ingestion on dynamic OpenFGA contextual tuples during authorization checks. Prevents unbounded graph traversals, traversal-induced denial of service (DoS), and latency degradation to guarantee deterministic sub-10ms p99 ReBAC resolutions. 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, Unbounded Dynamic Contextual Tuples into 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