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

Depth-Bounded Cycle-Safe ReBAC Contextual Tuple Graph Resolution

Enforces bounded graph evaluation and input sanitization for Zanzibar-style ReBAC systems when resolving contextual authorization tuples. Prevents algorithmic complexity denial-of-service (ReDoS/Graph DoS) and evaluation deadlocks caused by unbounded recursion, user-injected cyclic dependencies, and missing traversal deadlines.

Prohibited Anti-Pattern: Injecting Unsanitized Contextual Tuples Permitting Circular Traversal and Algorithmic DoS

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Depth-Bounded Cycle-Safe ReBAC Contextual Tuple Graph Resolution - Enforces bounded graph evaluation and input sanitization for Zanzibar-style ReBAC systems when resolving contextual authorization tuples. Prevents algorithmic complexity denial-of-service (ReDoS/Graph DoS) and evaluation deadlocks caused by unbounded recursion, user-injected cyclic dependencies, and missing traversal deadlines.
globs: src/auth/**/*.{ts,js}, src/security/**/*.{ts,js}, src/services/fga/**/*.{ts,js}, src/middleware/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuple-depth-bounded-resolution"
---

# Depth-Bounded Cycle-Safe ReBAC Contextual Tuple Graph Resolution

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Injecting Unsanitized Contextual Tuples Permitting Circular Traversal and Algorithmic DoS

## System Constraints
You are a Principal Security Architect enforcing OpenFGA ReBAC Contextual Tuple Depth-Bounded Graph Resolution. Mandate invariants that eliminate graph expansion denial-of-service and cycle-induced deadlocks in Zanzibar-based authorization paths.

## Strict Guidelines
- Engineers MUST ALWAYS validate and enforce a strict upper bound on the cardinality of contextual tuples passed to OpenFGA check and list-objects calls (maximum 20 tuples recommended per request).
- Engineers MUST NEVER accept contextual tuples directly from unauthenticated or unvalidated client payloads without verifying subject-relation-object integrity and structural acyclicity.
- Engineers MUST ALWAYS attach an explicit, depth-bounded timeout via AbortSignal (maximum 250ms for OLTP authorization paths) to every OpenFGA evaluation call.
- Services MUST ensure that the OpenFGA authorization model configures finite resolve-check limits and explicitly forbids transitive cycles in contextual self-referential relations.
- Code MUST sanitize contextual tuples by asserting that subject and object identifiers do not form immediate self-referential loops (e.g., user:X related to user:X) prior to client invocation.
- Components NEVER execute unbounded recursive relation checks without client-side or gateway-level circuit breakers guarding downstream OpenFGA cluster memory.

## Bad vs Good Implementations
### Contextual Tuple Graph Resolution Guardrail

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Contextual tuples are passed directly without boundary constraints, cycle validation, or evaluation timeouts. Malicious or malformed inputs can form dependency loops or massive traversal DAGs, exhausting authorization engine compute resources.
```typescript
import { OpenFgaClient, type ClientCheckRequest } from '@openfga/sdk';

export async function authorizeAccess(
  fgaClient: OpenFgaClient,
  user: string,
  relation: string,
  object: string,
  dynamicContextTuples: Array<{ user: string; relation: string; object: string }>
): Promise<boolean> {
  // VULNERABLE: Direct pass-through of unbounded, unvalidated contextual tuples.
  // An attacker can supply circular edges (e.g., group:A -> group:B -> group:A)
  // or hundreds of transient edges, triggering algorithmic complexity DoS, high CPU,
  // and cascading timeout failures in OpenFGA graph resolution.
  const checkRequest: ClientCheckRequest = {
    user,
    relation,
    object,
    contextualTuples: dynamicContextTuples
  };

  const response = await fgaClient.check(checkRequest);
  return !!response.allowed;
}
```

#### Production Standard (Correct)
> **Standard**: Implements defensive bounds on tuple cardinality, rejects direct self-referencing loops and duplicate edges, and bounds execution time with an AbortSignal timeout to neutralize graph-traversal denial-of-service.
```typescript
import { OpenFgaClient, type ClientCheckRequest, type ClientTupleKey } from '@openfga/sdk';

const MAX_ALLOWED_CONTEXT_TUPLES = 10;
const AUTHZ_TIMEOUT_MS = 250;

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

function validateAndSanitizeTuples(tuples: ClientTupleKey[]): ClientTupleKey[] {
  if (tuples.length > MAX_ALLOWED_CONTEXT_TUPLES) {
    throw new TupleResolutionSecurityError(
      `Contextual tuple count (${tuples.length}) exceeds hard limit (${MAX_ALLOWED_CONTEXT_TUPLES})`
    );
  }

  const seenEdges = new Set<string>();

  for (const tuple of tuples) {
    // Reject trivial self-referential cycles
    if (tuple.user === tuple.object) {
      throw new TupleResolutionSecurityError(
        `Self-referential loop detected in contextual tuple: ${tuple.user} -> ${tuple.object}`
      );
    }

    const edgeKey = `${tuple.user}#${tuple.relation}@${tuple.object}`;
    if (seenEdges.has(edgeKey)) {
      throw new TupleResolutionSecurityError(`Duplicate contextual tuple: ${edgeKey}`);
    }
    seenEdges.add(edgeKey);
  }

  return tuples;
}

export async function authorizeAccess(
  fgaClient: OpenFgaClient,
  user: string,
  relation: string,
  object: string,
  dynamicContextTuples: ClientTupleKey[]
): Promise<boolean> {
  const sanitizedTuples = validateAndSanitizeTuples(dynamicContextTuples);
  const abortController = new AbortController();
  const timeoutId = setTimeout(() => abortController.abort(), AUTHZ_TIMEOUT_MS);

  try {
    const checkRequest: ClientCheckRequest = {
      user,
      relation,
      object,
      contextualTuples: sanitizedTuples
    };

    const response = await fgaClient.check(checkRequest, {
      signal: abortController.signal
    });

    return Boolean(response.allowed);
  } catch (error: unknown) {
    if (error instanceof Error && error.name === 'AbortError') {
      throw new TupleResolutionSecurityError('OpenFGA graph traversal exceeded max latency budget');
    }
    throw error;
  } 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: Depth-Bounded Cycle-Safe ReBAC Contextual Tuple Graph Resolution

Depth-Bounded Cycle-Safe ReBAC Contextual Tuple Graph Resolution defines an industrial-grade behavioral standard for security engineering. Enforces bounded graph evaluation and input sanitization for Zanzibar-style ReBAC systems when resolving contextual authorization tuples. Prevents algorithmic complexity denial-of-service (ReDoS/Graph DoS) and evaluation deadlocks caused by unbounded recursion, user-injected cyclic dependencies, and missing traversal deadlines. 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 Contextual Tuples Permitting Circular Traversal and Algorithmic DoS 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 Contextual Tuples Permitting Circular Traversal and Algorithmic DoSCritical
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 enforce a strict upper bound on the cardinality of contextual tuples passed to OpenFGA check and list-objects calls (maximum 20 tuples recommended per request).

Engineers MUST ALWAYS validate and enforce a strict upper bound on the cardinality of contextual tuples passed to OpenFGA check and list-objects calls (maximum 20 tuples recommended per 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 NEVER accept contextual tuples directly from unauthenticated or unvalidated client payloads without verifying subject-relation-object integrity and structural acyclicity.

Engineers MUST NEVER accept contextual tuples directly from unauthenticated or unvalidated client payloads without verifying subject-relation-object integrity and structural acyclicity.

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 ALWAYS attach an explicit, depth-bounded timeout via AbortSignal (maximum 250ms for OLTP authorization paths) to every OpenFGA evaluation call.

Engineers MUST ALWAYS attach an explicit, depth-bounded timeout via AbortSignal (maximum 250ms for OLTP authorization paths) to every OpenFGA evaluation call.

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 ensure that the OpenFGA authorization model configures finite resolve-check limits and explicitly forbids transitive cycles in contextual self-referential relations.

Services MUST ensure that the OpenFGA authorization model configures finite resolve-check limits and explicitly forbids transitive cycles in contextual self-referential relations.

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

Code MUST sanitize contextual tuples by asserting that subject and object identifiers do not form immediate self-referential loops (e.g., user

Code MUST sanitize contextual tuples by asserting that subject and object identifiers do not form immediate self-referential loops (e.g., user:X related to user:X) prior to client invocation.

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.
6

Components NEVER execute unbounded recursive relation checks without client-side or gateway-level circuit breakers guarding downstream OpenFGA cluster memory.

Components NEVER execute unbounded recursive relation checks without client-side or gateway-level circuit breakers guarding downstream OpenFGA cluster memory.

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 Depth-Bounded Cycle-Safe ReBAC Contextual Tuple Graph Resolution critical for AI coding assistants?

Enforces bounded graph evaluation and input sanitization for Zanzibar-style ReBAC systems when resolving contextual authorization tuples. Prevents algorithmic complexity denial-of-service (ReDoS/Graph DoS) and evaluation deadlocks caused by unbounded recursion, user-injected cyclic dependencies, and missing traversal deadlines. 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 Contextual Tuples Permitting Circular Traversal and Algorithmic DoS) 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

Depth-Bounded