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

Bounded Contextual Tuple Evaluation and Graph Fan-Out Guardrail for OpenFGA

Enforces strict bounds, validation, and recursion limits on dynamic contextual tuples passed to OpenFGA Check requests. Unbounded contextual tuple injection exposes fine-grained authorization graphs to algorithmic complexity exhaustion, cyclic traversals, and tail-latency degradation. This rule mandates explicit cardinality caps, relation whitelisting, and evaluation timeouts on all dynamic authorization paths.

Prohibited Anti-Pattern: Injecting Unbounded or Arbitrary Client-Controlled Contextual Tuples into OpenFGA Check Evaluations

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bounded Contextual Tuple Evaluation and Graph Fan-Out Guardrail for OpenFGA - Enforces strict bounds, validation, and recursion limits on dynamic contextual tuples passed to OpenFGA Check requests. Unbounded contextual tuple injection exposes fine-grained authorization graphs to algorithmic complexity exhaustion, cyclic traversals, and tail-latency degradation. This rule mandates explicit cardinality caps, relation whitelisting, and evaluation timeouts on all dynamic authorization paths.
globs: src/auth/**/*.{ts,tsx,js,jsx}, src/security/**/*.{ts,tsx,js,jsx}, src/services/auth/**/*.{ts,tsx,js,jsx}, src/middleware/**/*.{ts,tsx,js,jsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-bounded-contextual-tuple-fanout-guard"
---

# Bounded Contextual Tuple Evaluation and Graph Fan-Out Guardrail for OpenFGA

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Injecting Unbounded or Arbitrary Client-Controlled Contextual Tuples into OpenFGA Check Evaluations

## System Constraints
You are a Principal Engineer enforcing OpenFGA Bounded Contextual Tuple Evaluation Pipeline. Mandate invariants that prevent algorithmic latency degradation, cyclic fan-out, and graph-traversal Denial of Service (ReBAC DoS) during real-time authorization checks. Contextual tuples must be validated against a strict schema, deduplicated, bounded to a maximum cardinality, and executed under strict deadline timeouts.

## Strict Guidelines
- Engineers MUST ALWAYS enforce strict cardinality caps (maximum allowed contextual tuples, default <= 20) on all OpenFGA `check` requests.
- Engineers MUST NOT forward raw, unvalidated, or unsanitized client-provided relationships or object IDs into the OpenFGA contextual tuple collection.
- Code SHOULD sanitize, normalize, and deduplicate contextual tuples prior to dispatch to prevent duplicate traversal branch evaluation.
- Services MUST enforce strict execution deadlines and abort-signal timeouts (e.g., <= 150ms) on all contextual evaluation calls.
- Components NEVER permit arbitrary transitive relations (such as parent/child cycles) to be dynamically injected via contextual tuples without relationship-type whitelisting.

## Bad vs Good Implementations
### Enforcing Bounded Contextual Tuple Pipeline with Cardinality, Whitelisting, and Deadlines

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Client-controlled arrays of arbitrary length and arbitrary relations are passed directly to OpenFGA. An adversary can pass hundreds of cyclic or deep parent-child relationships, causing the OpenFGA graph traversal engine to fan out exponentially, leading to request timeouts, high CPU saturation, and authorization denial of service.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

interface ClientAuthRequest {
  user: string;
  relation: string;
  object: string;
  dynamicRoles: Array<{ user: string; relation: string; object: string }>;
}

export async function authorizeUser(fgaClient: OpenFgaClient, req: ClientAuthRequest): Promise<boolean> {
  // VULNERABILITY: Raw client input forwarded directly without cardinality checks,
  // relation whitelisting, or timeout. Allows deep nested graphs or recursive loops
  // causing algorithmic complexity exhaustion and latency degradation.
  const response = await fgaClient.check({
    user: req.user,
    relation: req.relation,
    object: req.object,
    contextualTuples: req.dynamicRoles.map(tuple => ({
      user: tuple.user,
      relation: tuple.relation,
      object: tuple.object,
    })),
  });

  return Boolean(response.allowed);
}
```

#### Production Standard (Correct)
> **Standard**: Enforces bounded traversal invariants: caps the contextual tuple count to 20, deduplicates tuples via a composite key, validates relations against an explicit safe whitelist, eliminates identity self-cycles, and imposes a 150ms timeout using AbortController to guarantee strict bounds on OpenFGA graph fan-out latency.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

interface ClientAuthRequest {
  user: string;
  relation: string;
  object: string;
  dynamicRoles?: ContextualTupleInput[];
}

const MAX_CONTEXTUAL_TUPLES = 20;
const ALLOWED_CONTEXTUAL_RELATIONS = new Set(['viewer_context', 'ephemeral_collaborator', 'session_operator']);
const EVALUATION_TIMEOUT_MS = 150;

export async function authorizeUser(fgaClient: OpenFgaClient, req: ClientAuthRequest): Promise<boolean> {
  const dynamicRoles = req.dynamicRoles ?? [];

  if (dynamicRoles.length > MAX_CONTEXTUAL_TUPLES) {
    throw new Error(`Contextual tuple threshold exceeded: maximum ${MAX_CONTEXTUAL_TUPLES} allowed.`);
  }

  const deduplicatedTuples = new Map<string, ContextualTupleInput>();

  for (const tuple of dynamicRoles) {
    if (!ALLOWED_CONTEXTUAL_RELATIONS.has(tuple.relation)) {
      throw new Error(`Forbidden contextual relation: ${tuple.relation}`);
    }

    // Prevent cyclic self-referential graph injection
    if (tuple.user === tuple.object) {
      continue;
    }

    const key = `${tuple.user}#${tuple.relation}@${tuple.object}`;
    deduplicatedTuples.set(key, tuple);
  }

  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), EVALUATION_TIMEOUT_MS);

  try {
    const response = await fgaClient.check(
      {
        user: req.user,
        relation: req.relation,
        object: req.object,
        contextualTuples: Array.from(deduplicatedTuples.values()),
      },
      {
        signal: controller.signal,
      }
    );

    return Boolean(response.allowed);
  } 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: Bounded Contextual Tuple Evaluation and Graph Fan-Out Guardrail for OpenFGA

Bounded Contextual Tuple Evaluation and Graph Fan-Out Guardrail for OpenFGA defines an industrial-grade behavioral standard for security engineering. Enforces strict bounds, validation, and recursion limits on dynamic contextual tuples passed to OpenFGA Check requests. Unbounded contextual tuple injection exposes fine-grained authorization graphs to algorithmic complexity exhaustion, cyclic traversals, and tail-latency degradation. This rule mandates explicit cardinality caps, relation whitelisting, and evaluation timeouts on all dynamic authorization paths. 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 Unbounded or Arbitrary Client-Controlled Contextual Tuples into OpenFGA Check Evaluations 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 Unbounded or Arbitrary Client-Controlled Contextual Tuples into OpenFGA Check EvaluationsCritical
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 strict cardinality caps (maximum allowed contextual tuples, default <= 20) on all OpenFGA `check` requests.

Engineers MUST ALWAYS enforce strict cardinality caps (maximum allowed contextual tuples, default <= 20) on all 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.
2

Engineers MUST NOT forward raw, unvalidated, or unsanitized client-provided relationships or object IDs into the OpenFGA contextual tuple collection.

Engineers MUST NOT forward raw, unvalidated, or unsanitized client-provided relationships or object IDs into the OpenFGA contextual tuple collection.

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 sanitize, normalize, and deduplicate contextual tuples prior to dispatch to prevent duplicate traversal branch evaluation.

Code SHOULD sanitize, normalize, and deduplicate contextual tuples prior to dispatch to prevent duplicate traversal branch evaluation.

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 strict execution deadlines and abort-signal timeouts (e.g., <= 150ms) on all contextual evaluation calls.

Services MUST enforce strict execution deadlines and abort-signal timeouts (e.g., <= 150ms) on all contextual evaluation calls.

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 permit arbitrary transitive relations (such as parent/child cycles) to be dynamically injected via contextual tuples without relationship-type whitelisting.

Components NEVER permit arbitrary transitive relations (such as parent/child cycles) to be dynamically injected via contextual tuples without relationship-type 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Bounded Contextual Tuple Evaluation and Graph Fan-Out Guardrail for OpenFGA critical for AI coding assistants?

Enforces strict bounds, validation, and recursion limits on dynamic contextual tuples passed to OpenFGA Check requests. Unbounded contextual tuple injection exposes fine-grained authorization graphs to algorithmic complexity exhaustion, cyclic traversals, and tail-latency degradation. This rule mandates explicit cardinality caps, relation whitelisting, and evaluation timeouts on all dynamic authorization paths. 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 Unbounded or Arbitrary Client-Controlled Contextual Tuples into OpenFGA Check Evaluations) 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

Bounded