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

Bounded In-Memory Subtrees for OpenFGA Contextual Tuple Authorization

Enforces strict structural bounds, cardinality limits, and relation allowlists on OpenFGA ephemeral contextual tuples during authorization evaluation. Injecting unconstrained or cyclic contextual tuples into in-memory resolution graphs triggers unbounded graph traversals and memory bloat, causing authorization denial-of-service (AuthDoS).

Prohibited Anti-Pattern: Injecting Arbitrary, Unbounded Ephemeral Tuples into OpenFGA Check Traversals

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bounded In-Memory Subtrees for OpenFGA Contextual Tuple Authorization - Enforces strict structural bounds, cardinality limits, and relation allowlists on OpenFGA ephemeral contextual tuples during authorization evaluation. Injecting unconstrained or cyclic contextual tuples into in-memory resolution graphs triggers unbounded graph traversals and memory bloat, causing authorization denial-of-service (AuthDoS).
globs: src/**/auth/**/*.{ts,tsx}, src/**/fga/**/*.{ts,tsx}, src/**/authorization/**/*.{ts,tsx}, src/**/guards/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-bounded-contextual-tuples-standard"
---

# Bounded In-Memory Subtrees for OpenFGA Contextual Tuple Authorization

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Injecting Arbitrary, Unbounded Ephemeral Tuples into OpenFGA Check Traversals

## System Constraints
You are a Principal Engineer enforcing the OpenFGA Sub-Millisecond Contextual Tuple Authorization Standard. Mandate strict bounds on in-memory relationship graphs to eliminate graph-based Denial-of-Service and latency degradation during contextual access checks.

## Strict Guidelines
- Engineers MUST ALWAYS enforce a deterministic upper bound (hard cap <= 20 tuples) on contextual tuples injected into any OpenFGA check request.
- Engineers MUST NOT allow contextual tuples to specify recursive or transitive relations (e.g., 'parent', 'ancestor', 'member') that trigger uncontrolled graph expansion.
- Code SHOULD restrict contextual tuples to non-hierarchical, direct leaf assignments (e.g., 'is_ip_whitelisted', 'has_temporary_grant', 'session_active').
- Services MUST validate contextual tuples against an explicit schema (user type, relation, object type) and reject any cycle or wildcard projection before dispatching to the OpenFGA client.
- Components NEVER execute OpenFGA evaluations with ephemeral context without an explicit sub-second deadline context (e.g., AbortSignal bounded to <= 50ms).

## Bad vs Good Implementations
### Contextual Tuple Injection Guardrails

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accepting dynamic grants directly into contextualTuples with no length limit, schema validation, or relation allowlisting allows malicious or buggy clients to construct deep recursive trees or cyclic graphs. This forces OpenFGA into pathological graph resolutions, exhausting server memory and exceeding latency SLAs.
```typescript
import { OpenFgaClient, type ClientCheckRequest } from '@openfga/sdk';

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

// Anti-pattern: Unbounded, unsanitized contextual tuples from client request
// Vulnerable to graph traversal explosion, cycles, and AuthDoS
export async function authorizeRequest(user: string, relation: string, object: string, dynamicGrants: Array<{ user: string; relation: string; object: string }>) {
  const checkPayload: ClientCheckRequest = {
    user,
    relation,
    object,
    contextualTuples: dynamicGrants // Unbounded array, unvalidated relations, could contain cyclic parent-child links
  };

  return await fga.check(checkPayload);
}
```

#### Production Standard (Correct)
> **Standard**: The fix enforces a deterministic tuple limit (<= 16), restricts relations to a shallow leaf-only allowlist, prevents self-referencing cycles, deduplicates entries, and bounds execution via an AbortController with a strict 45ms timeout to guarantee sub-millisecond to low-millisecond determinism without AuthDoS risks.
```typescript
import { OpenFgaClient, type ClientCheckRequest, type TupleKey } from '@openfga/sdk';

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

const MAX_CONTEXTUAL_TUPLES = 16;
const ALLOWED_CONTEXTUAL_RELATIONS = new Set(['temporary_viewer', 'session_operator']);
const TIMEOUT_MS = 45;

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

function validateContextualSubtree(tuples: EphemeralGrant[]): TupleKey[] {
  if (tuples.length > MAX_CONTEXTUAL_TUPLES) {
    throw new Error(`Contextual tuple limit exceeded: max ${MAX_CONTEXTUAL_TUPLES}, got ${tuples.length}`);
  }

  const validated: TupleKey[] = [];
  const seenTuples = new Set<string>();

  for (const t of tuples) {
    if (!ALLOWED_CONTEXTUAL_RELATIONS.has(t.relation)) {
      throw new Error(`Unauthorized contextual relation: ${t.relation}`);
    }
    if (t.user === t.object) {
      throw new Error(`Cyclic self-reference rejected in contextual tuple: ${t.user}`);
    }

    const key = `${t.user}#${t.relation}@${t.object}`;
    if (seenTuples.has(key)) {
      continue; // Deduplicate
    }
    seenTuples.add(key);

    validated.push({
      user: t.user,
      relation: t.relation,
      object: t.object,
    });
  }

  return validated;
}

export async function authorizeRequest(
  user: string,
  relation: string,
  object: string,
  ephemeralGrants: EphemeralGrant[] = []
) {
  const boundedTuples = validateContextualSubtree(ephemeralGrants);
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);

  try {
    const checkPayload: ClientCheckRequest = {
      user,
      relation,
      object,
      contextualTuples: boundedTuples,
    };

    const response = await fga.check(checkPayload, { signal: controller.signal });
    return Boolean(response.allowed);
  } finally {
    clearTimeout(timer);
  }
}
```

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 In-Memory Subtrees for OpenFGA Contextual Tuple Authorization

Bounded In-Memory Subtrees for OpenFGA Contextual Tuple Authorization defines an industrial-grade behavioral standard for security engineering. Enforces strict structural bounds, cardinality limits, and relation allowlists on OpenFGA ephemeral contextual tuples during authorization evaluation. Injecting unconstrained or cyclic contextual tuples into in-memory resolution graphs triggers unbounded graph traversals and memory bloat, causing authorization denial-of-service (AuthDoS). 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 Arbitrary, Unbounded Ephemeral Tuples into OpenFGA Check Traversals 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 Arbitrary, Unbounded Ephemeral Tuples into OpenFGA Check TraversalsCritical
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 deterministic upper bound (hard cap <= 20 tuples) on contextual tuples injected into any OpenFGA check request.

Engineers MUST ALWAYS enforce a deterministic upper bound (hard cap <= 20 tuples) on contextual tuples injected into any OpenFGA check 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 allow contextual tuples to specify recursive or transitive relations (e.g., 'parent', 'ancestor', 'member') that trigger uncontrolled graph expansion.

Engineers MUST NOT allow contextual tuples to specify recursive or transitive relations (e.g., 'parent', 'ancestor', 'member') that trigger uncontrolled graph expansion.

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 restrict contextual tuples to non-hierarchical, direct leaf assignments (e.g., 'is_ip_whitelisted', 'has_temporary_grant', 'session_active').

Code SHOULD restrict contextual tuples to non-hierarchical, direct leaf assignments (e.g., 'is_ip_whitelisted', 'has_temporary_grant', 'session_active').

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 validate contextual tuples against an explicit schema (user type, relation, object type) and reject any cycle or wildcard projection before dispatching to the OpenFGA client.

Services MUST validate contextual tuples against an explicit schema (user type, relation, object type) and reject any cycle or wildcard projection before dispatching 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.
5

Components NEVER execute OpenFGA evaluations with ephemeral context without an explicit sub-second deadline context (e.g., AbortSignal bounded to <= 50ms).

Components NEVER execute OpenFGA evaluations with ephemeral context without an explicit sub-second deadline context (e.g., AbortSignal bounded to <= 50ms).

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 In-Memory Subtrees for OpenFGA Contextual Tuple Authorization critical for AI coding assistants?

Enforces strict structural bounds, cardinality limits, and relation allowlists on OpenFGA ephemeral contextual tuples during authorization evaluation. Injecting unconstrained or cyclic contextual tuples into in-memory resolution graphs triggers unbounded graph traversals and memory bloat, causing authorization denial-of-service (AuthDoS). 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 Arbitrary, Unbounded Ephemeral Tuples into OpenFGA Check Traversals) 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