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

OpenFGA Request-Scoped Contextual Tuple Memory and Cardinality Sandboxing

Enforces strict cardinality bounding, payload memory budgets, and timeout sandboxing on request-scoped contextual tuples during OpenFGA check operations. Failure to sandbox ephemeral tuples exposes authorization nodes to heap exhaustion, algorithmic complexity attacks, and denial of service via recursive graph traversals.

Prohibited Anti-Pattern: Unbounded Dynamic Contextual Tuple Ingestion Causing Authorization Cluster Exhaustion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Request-Scoped Contextual Tuple Memory and Cardinality Sandboxing - Enforces strict cardinality bounding, payload memory budgets, and timeout sandboxing on request-scoped contextual tuples during OpenFGA check operations. Failure to sandbox ephemeral tuples exposes authorization nodes to heap exhaustion, algorithmic complexity attacks, and denial of service via recursive graph traversals.
globs: src/auth/**/*.ts, src/services/fga/**/*.ts, src/middleware/authz/**/*.ts, src/lib/openfga/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuple-memory-sandboxing"
---

# OpenFGA Request-Scoped Contextual Tuple Memory and Cardinality Sandboxing

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded Dynamic Contextual Tuple Ingestion Causing Authorization Cluster Exhaustion

## System Constraints
You are a Principal Engineer enforcing security and reliability guardrails around OpenFGA contextual tuple management. You must ensure all request-scoped contextual authorization tuples are strictly validated, deduplicated, bounded by a hard cardinality limit (<= 25 tuples), constrained to a maximum memory budget (<= 8KB payload), and guarded by deterministic execution timeouts.

## Strict Guidelines
- Engineers MUST ALWAYS enforce strict cardinality caps (default max: 25) on contextual tuples passed to OpenFGA check or batch-check operations.
- Engineers MUST ALWAYS validate total contextual tuple memory size before dispatch, rejecting any request exceeding the allocated memory budget (max: 8192 bytes).
- Engineers MUST NOT accept untyped or unvalidated client payloads directly into the contextualTuples array; all entries must pass strict type, schema, and regex format assertions.
- Services MUST enforce an explicit AbortSignal timeout (max 2000ms) on OpenFGA API calls to mitigate deep graph recursion latency traps triggered by contextual relationships.
- Components NEVER pass circular or self-referential contextual tuples (where user equals object and relation indicates equivalence) without cycle detection.

## Bad vs Good Implementations
### Unbounded Contextual Tuple Ingestion vs. Memory-Sandboxed Validator

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly passing untrusted, unconstrained request arrays into contextualTuples introduces memory exhaustion (OOM), serialization stalls, and algorithmic denial of service via arbitrarily deep or cyclic graph extensions.
```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-supplied contextual tuples
export async function evaluateAccess(req: { body: { user: string; relation: string; object: string; dynamicContext: any[] } }) {
  // VULNERABILITY: No length limit, no memory check, no timeout, no schema validation.
  // An attacker can pass 10,000 contextual tuples, exhausting memory or causing FGA engine timeout.
  const { user, relation, object, dynamicContext } = req.body;

  return await fgaClient.check({
    user,
    relation,
    object,
    contextualTuples: dynamicContext,
  });
}
```

#### Production Standard (Correct)
> **Standard**: Validates schema with Zod, bounds cardinality to 25 items, enforces an 8KB memory ceiling, deduplicates tuple identities to prevent redundant branch calculations, and attaches an AbortSignal timeout to isolate engine execution.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';
import { z } from 'zod';

const MAX_CONTEXTUAL_TUPLES = 25;
const MAX_CONTEXT_BYTES = 8192;
const FGA_TIMEOUT_MS = 1500;

const ContextTupleSchema = z.object({
  user: z.string().min(1).max(256).regex(/^[a-zA-Z0-9_-]+:[a-zA-Z0-9_#-]+$/),
  relation: z.string().min(1).max(64).regex(/^[a-z_][a-z0-9_]*$/),
  object: z.string().min(1).max(256).regex(/^[a-zA-Z0-9_-]+:[a-zA-Z0-9_-]+$/),
});

export function sanitizeContextualTuples(rawTuples: unknown[]): Array<z.infer<typeof ContextTupleSchema>> {
  if (!Array.isArray(rawTuples)) {
    throw new Error('Contextual tuples must be an array');
  }
  if (rawTuples.length > MAX_CONTEXTUAL_TUPLES) {
    throw new Error(`Contextual tuple count exceeds maximum allowed limit of ${MAX_CONTEXTUAL_TUPLES}`);
  }

  const rawJson = JSON.stringify(rawTuples);
  if (Buffer.byteLength(rawJson, 'utf8') > MAX_CONTEXT_BYTES) {
    throw new Error(`Contextual tuple payload exceeds maximum memory budget of ${MAX_CONTEXT_BYTES} bytes`);
  }

  const validated = z.array(ContextTupleSchema).parse(rawTuples);
  const deduplicated = Array.from(
    new Map(validated.map(t => [`${t.user}#${t.relation}@${t.object}`, t])).values()
  );

  return deduplicated;
}

export async function evaluateAccessSecure(
  client: OpenFgaClient,
  params: { user: string; relation: string; object: string; dynamicContext?: unknown[] }
) {
  const contextualTuples = params.dynamicContext
    ? sanitizeContextualTuples(params.dynamicContext)
    : [];

  const checkRequest: ClientCheckRequest = {
    user: params.user,
    relation: params.relation,
    object: params.object,
    contextualTuples,
  };

  return await client.check(checkRequest, {
    signal: AbortSignal.timeout(FGA_TIMEOUT_MS),
  });
}
```

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: OpenFGA Request-Scoped Contextual Tuple Memory and Cardinality Sandboxing

OpenFGA Request-Scoped Contextual Tuple Memory and Cardinality Sandboxing defines an industrial-grade behavioral standard for security engineering. Enforces strict cardinality bounding, payload memory budgets, and timeout sandboxing on request-scoped contextual tuples during OpenFGA check operations. Failure to sandbox ephemeral tuples exposes authorization nodes to heap exhaustion, algorithmic complexity attacks, and denial of service via recursive graph traversals. 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 Dynamic Contextual Tuple Ingestion Causing Authorization Cluster Exhaustion 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 Dynamic Contextual Tuple Ingestion Causing Authorization Cluster ExhaustionCritical
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 (default max

Engineers MUST ALWAYS enforce strict cardinality caps (default max: 25) on contextual tuples passed to OpenFGA check or batch-check operations.

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 ALWAYS validate total contextual tuple memory size before dispatch, rejecting any request exceeding the allocated memory budget (max

Engineers MUST ALWAYS validate total contextual tuple memory size before dispatch, rejecting any request exceeding the allocated memory budget (max: 8192 bytes).

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 accept untyped or unvalidated client payloads directly into the contextualTuples array

Engineers MUST NOT accept untyped or unvalidated client payloads directly into the contextualTuples array; all entries must pass strict type, schema, and regex format assertions.

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 explicit AbortSignal timeout (max 2000ms) on OpenFGA API calls to mitigate deep graph recursion latency traps triggered by contextual relationships.

Services MUST enforce an explicit AbortSignal timeout (max 2000ms) on OpenFGA API calls to mitigate deep graph recursion latency traps triggered by contextual relationships.

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 circular or self-referential contextual tuples (where user equals object and relation indicates equivalence) without cycle detection.

Components NEVER pass circular or self-referential contextual tuples (where user equals object and relation indicates equivalence) without cycle detection.

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 Request-Scoped Contextual Tuple Memory and Cardinality Sandboxing critical for AI coding assistants?

Enforces strict cardinality bounding, payload memory budgets, and timeout sandboxing on request-scoped contextual tuples during OpenFGA check operations. Failure to sandbox ephemeral tuples exposes authorization nodes to heap exhaustion, algorithmic complexity attacks, and denial of service via recursive graph traversals. 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 Dynamic Contextual Tuple Ingestion Causing Authorization Cluster Exhaustion) 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