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

OpenFGA Contextual Tuple Canonicalization and Depth-Budget Guardrail

Enforces pre-evaluation canonicalization, cycle detection, and strict depth-budget limits on user-supplied OpenFGA contextual tuples. Prevents algorithmic complexity Denial-of-Service (DoS) and infinite graph traversal attacks in Relationship-Based Access Control (ReBAC) engines by rejecting non-canonical identifiers and contextual relationship loops before invoking the authorization engine.

Prohibited Anti-Pattern: Passing unvalidated, cyclic, or unbounded user-supplied contextual tuples directly to OpenFGA Check or ListObjects APIs.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Contextual Tuple Canonicalization and Depth-Budget Guardrail - Enforces pre-evaluation canonicalization, cycle detection, and strict depth-budget limits on user-supplied OpenFGA contextual tuples. Prevents algorithmic complexity Denial-of-Service (DoS) and infinite graph traversal attacks in Relationship-Based Access Control (ReBAC) engines by rejecting non-canonical identifiers and contextual relationship loops before invoking the authorization engine.
globs: src/**/authz/**/*.ts, src/**/security/**/*.ts, src/**/services/fga*.ts, src/**/guards/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuple-canonicalization-depth-budget"
---

# OpenFGA Contextual Tuple Canonicalization and Depth-Budget Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Passing unvalidated, cyclic, or unbounded user-supplied contextual tuples directly to OpenFGA Check or ListObjects APIs.

## System Constraints
You are a Principal Security Engineer enforcing OpenFGA contextual tuple safety. You must mandate strict canonicalization of entity identifiers, enforce deterministic depth/tuple bounds, and run pre-evaluation cycle detection over contextual tuples before passing them to the OpenFGA client.

## Strict Guidelines
- Engineers MUST ALWAYS validate and canonicalize object IDs and user IDs against strict regex invariants (e.g., lowercase type-prefix matching `^[a-z0-9_-]+:[a-zA-Z0-9_-]+$`) prior to tuple construction.
- Engineers MUST NOT forward raw, unvalidated contextual tuples received from API request payloads directly into `fgaClient.check()` or `fgaClient.listObjects()`.
- Services MUST enforce an explicit hard cap on the total count of contextual tuples per evaluation request (default ceiling <= 25 tuples).
- Services MUST construct an in-memory directed graph of the supplied contextual tuples and execute cycle detection (e.g., Kahn's algorithm or DFS back-edge detection) to reject cyclical delegations before dispatching to OpenFGA.
- Components NEVER accept self-referential tuples where `user === object` and relation implies direct or indirect transitive self-containment.

## Bad vs Good Implementations
### Adversarial Contextual Tuple Injection vs. Pre-Validated Canonical Guardrail

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly forwards unvalidated client-supplied tuples to OpenFGA. An adversary can pass hundreds of nested or cyclic contextual tuples (e.g., A member of B, B member of A), triggering exponential subgraph evaluation or DoS in the authorization layer.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

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

// ANTI-PATTERN: Blindly accepting user-provided contextual tuples.
// Adversaries can supply cyclic graphs (A parent of B, B parent of A) or hundreds of
// recursive relations, triggering high CPU consumption and ReBAC traversal exhaustion.
export async function checkAccessUnsafe(
  userId: string,
  objectId: string,
  relation: string,
  rawContextualTuples: Array<{ user: string; relation: string; object: string }>
): Promise<boolean> {
  const payload: ClientCheckRequest = {
    user: userId,
    relation,
    object: objectId,
    contextualTuples: rawContextualTuples,
  };

  const response = await fgaClient.check(payload);
  return Boolean(response.allowed);
}
```

#### Production Standard (Correct)
> **Standard**: Validates entity and relation syntax against strict schemas, enforces a strict tuple count ceiling (20), rejects self-referential relations, and executes cycle detection via DFS to prevent algorithmic traversal exhaustion before calling the OpenFGA service.
```typescript
import { OpenFgaClient, ClientCheckRequest, ClientTupleKey } from '@openfga/sdk';

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

const MAX_CONTEXTUAL_TUPLES = 20;
const ENTITY_REGEX = /^[a-z0-9_]{2,32}:[a-zA-Z0-9_#-]{1,64}$/;
const RELATION_REGEX = /^[a-z_]{2,32}$/;

export class TupleValidationError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'TupleValidationError';
  }
}

function validateAndCanonicalizeTuple(t: ClientTupleKey): ClientTupleKey {
  const user = t.user.trim();
  const relation = t.relation.trim();
  const object = t.object.trim();

  if (!ENTITY_REGEX.test(user) || !ENTITY_REGEX.test(object) || !RELATION_REGEX.test(relation)) {
    throw new TupleValidationError(`Malformed tuple identifier: ${user}#${relation}@${object}`);
  }
  if (user === object) {
    throw new TupleValidationError(`Self-referential tuple rejected: ${user}`);
  }
  return { user, relation, object };
}

function assertAcyclicContext(tuples: ClientTupleKey[]): void {
  const adj = new Map<string, string[]>();
  for (const { user, object } of tuples) {
    if (!adj.has(user)) adj.set(user, []);
    adj.get(user)!.push(object);
  }

  const visited = new Set<string>();
  const inStack = new Set<string>();

  function dfs(node: string): boolean {
    visited.add(node);
    inStack.add(node);
    for (const neighbor of adj.get(node) || []) {
      if (!visited.has(neighbor) && dfs(neighbor)) return true;
      if (inStack.has(neighbor)) return true;
    }
    inStack.delete(node);
    return false;
  }

  for (const node of adj.keys()) {
    if (!visited.has(node) && dfs(node)) {
      throw new TupleValidationError('Cycle detected in contextual tuples graph');
    }
  }
}

export async function checkAccessSafe(
  userId: string,
  objectId: string,
  relation: string,
  rawContextualTuples: ClientTupleKey[] = []
): Promise<boolean> {
  if (rawContextualTuples.length > MAX_CONTEXTUAL_TUPLES) {
    throw new TupleValidationError(`Contextual tuples exceeded limit of ${MAX_CONTEXTUAL_TUPLES}`);
  }

  const canonicalTuples = rawContextualTuples.map(validateAndCanonicalizeTuple);
  assertAcyclicContext(canonicalTuples);

  const payload: ClientCheckRequest = {
    user: userId,
    relation,
    object: objectId,
    contextualTuples: canonicalTuples,
  };

  const response = await fgaClient.check(payload);
  return Boolean(response.allowed);
}
```

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA Contextual Tuple Canonicalization and Depth-Budget Guardrail

OpenFGA Contextual Tuple Canonicalization and Depth-Budget Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces pre-evaluation canonicalization, cycle detection, and strict depth-budget limits on user-supplied OpenFGA contextual tuples. Prevents algorithmic complexity Denial-of-Service (DoS) and infinite graph traversal attacks in Relationship-Based Access Control (ReBAC) engines by rejecting non-canonical identifiers and contextual relationship loops before invoking the authorization engine. 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: Passing unvalidated, cyclic, or unbounded user-supplied contextual tuples directly to OpenFGA Check or ListObjects APIs. 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 DriftPassing unvalidated, cyclic, or unbounded user-supplied contextual tuples directly to OpenFGA Check or ListObjects APIs.Critical
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 canonicalize object IDs and user IDs against strict regex invariants (e.g., lowercase type-prefix matching `^[a-z0-9_-]+

Engineers MUST ALWAYS validate and canonicalize object IDs and user IDs against strict regex invariants (e.g., lowercase type-prefix matching `^[a-z0-9_-]+:[a-zA-Z0-9_-]+$`) prior to tuple construction.

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 contextual tuples received from API request payloads directly into `fgaClient.check()` or `fgaClient.listObjects()`.

Engineers MUST NOT forward raw, unvalidated contextual tuples received from API request payloads directly into `fgaClient.check()` or `fgaClient.listObjects()`.

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

Services MUST enforce an explicit hard cap on the total count of contextual tuples per evaluation request (default ceiling <= 25 tuples).

Services MUST enforce an explicit hard cap on the total count of contextual tuples per evaluation request (default ceiling <= 25 tuples).

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 construct an in-memory directed graph of the supplied contextual tuples and execute cycle detection (e.g., Kahn's algorithm or DFS back-edge detection) to reject cyclical delegations before dispatching to OpenFGA.

Services MUST construct an in-memory directed graph of the supplied contextual tuples and execute cycle detection (e.g., Kahn's algorithm or DFS back-edge detection) to reject cyclical delegations before dispatching to OpenFGA.

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 self-referential tuples where `user === object` and relation implies direct or indirect transitive self-containment.

Components NEVER accept self-referential tuples where `user === object` and relation implies direct or indirect transitive self-containment.

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 Contextual Tuple Canonicalization and Depth-Budget Guardrail critical for AI coding assistants?

Enforces pre-evaluation canonicalization, cycle detection, and strict depth-budget limits on user-supplied OpenFGA contextual tuples. Prevents algorithmic complexity Denial-of-Service (DoS) and infinite graph traversal attacks in Relationship-Based Access Control (ReBAC) engines by rejecting non-canonical identifiers and contextual relationship loops before invoking the authorization engine. 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 (Passing unvalidated, cyclic, or unbounded user-supplied contextual tuples directly to OpenFGA Check or ListObjects APIs.) 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