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

OpenFGA Conditional Relationship Tuple Evaluation Boundary Standard

Enforces strict deadline propagation, circuit breaker boundaries, and deterministic context serialization when evaluating OpenFGA conditional relationship tuples. Unbounded evaluation of dynamic ABAC conditions allows authorization bypass via resource exhaustion, request hanging, and fail-open edge-case degradation under adversarial payload loads. All check evaluations must enforce immutable context validation, strict timeouts, and fail-closed security defaults.

Prohibited Anti-Pattern: Unbounded or Fail-Open OpenFGA Check Execution with Dynamic Contextual Tuples

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Conditional Relationship Tuple Evaluation Boundary Standard - Enforces strict deadline propagation, circuit breaker boundaries, and deterministic context serialization when evaluating OpenFGA conditional relationship tuples. Unbounded evaluation of dynamic ABAC conditions allows authorization bypass via resource exhaustion, request hanging, and fail-open edge-case degradation under adversarial payload loads. All check evaluations must enforce immutable context validation, strict timeouts, and fail-closed security defaults.
globs: src/auth/**/*.{ts,js}, src/security/**/*.{ts,js}, src/middleware/**/*.{ts,js}, src/services/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-conditional-tuple-evaluation-boundary"
---

# OpenFGA Conditional Relationship Tuple Evaluation Boundary Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded or Fail-Open OpenFGA Check Execution with Dynamic Contextual Tuples

## System Constraints
You are a Principal Security Architect enforcing strictly bounded execution, fail-closed semantics, and context validation for OpenFGA conditional relationship tuples and dynamic ABAC checks. Mandate that every authorization decision carries explicit deadline timeouts, non-bypassable contextual schema checks, and defensive fallback postures to prevent Denial of Service (DoS) and authorization bypasses.

## Strict Guidelines
- Engineers MUST ALWAYS pass a bounded AbortSignal or context timeout (maximum 50-100ms) to every OpenFGA check request containing contextual tuples or conditions.
- Engineers MUST ALWAYS enforce strict fail-closed (access denied) behavior on client timeouts, network drops, or CEL evaluation errors from OpenFGA.
- Engineers MUST validate and sanitize contextual tuple values using a deterministic runtime schema (e.g., Zod) before supplying them to OpenFGA to prevent nested payload exploitation.
- Engineers MUST NOT fallback to granting access when an OpenFGA evaluation times out or encounters a 5xx/evaluation error.
- Services MUST enforce circuit breakers on repeated OpenFGA timeout errors to prevent cascade exhaustion across the downstream application tier.
- Components NEVER execute unbounded dynamic CEL script evaluations or deep recursive graph traversals without an explicit call-level deadline.

## Bad vs Good Implementations
### OpenFGA Check with Contextual Tuples and Timeout Enforcement

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The check lacks execution deadlines (enabling thread/socket exhaustion via complex CEL conditions), accepts arbitrary context objects without schema constraints, and dangerously fails open by returning true upon failure.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

export async function authorizeUser(userId: string, objectId: string, contextData: any): Promise<boolean> {
  try {
    // ANTI-PATTERN: No timeout, unsanitized context, and fail-open error handling
    const response = await fgaClient.check({
      user: `user:${userId}`,
      relation: 'viewer',
      object: `document:${objectId}`,
      context: contextData, // Potential ReDoS / memory exhaustion payload
    });
    return response.allowed ?? false;
  } catch (error) {
    // CRITICAL SECURITY FLAW: Failing open or treating errors as non-fatal fallback
    console.error('Authorization check failed, bypassing:', error);
    return true;
  }
}
```

#### Production Standard (Correct)
> **Standard**: Validates context data against a strict schema, implements a hard 75ms deadline via AbortController, and strictly fails closed by returning false on any evaluation failure or timeout.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';
import { z } from 'zod';

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

const ContextSchema = z.object({
  current_time: z.string().datetime(),
  ip_address: z.string().ip(),
  device_risk_score: z.number().min(0).max(100),
}).strict();

export type DynamicContext = z.infer<typeof ContextSchema>;

const EVALUATION_TIMEOUT_MS = 75;

export async function authorizeUser(
  userId: string,
  objectId: string,
  rawContext: unknown
): Promise<boolean> {
  // 1. Validate contextual boundary prior to FGA dispatch
  const parseResult = ContextSchema.safeParse(rawContext);
  if (!parseResult.success) {
    return false; // Fail-closed on invalid ABAC context
  }

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

  try {
    const payload: ClientCheckRequest = {
      user: `user:${userId}`,
      relation: 'viewer',
      object: `document:${objectId}`,
      context: parseResult.data,
    };

    const response = await fgaClient.check(payload, {
      signal: controller.signal,
    });

    return Boolean(response.allowed);
  } catch (error: unknown) {
    // Fail-closed invariant: Timeouts, aborts, and 5xx errors deny access
    return false;
  } 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: OpenFGA Conditional Relationship Tuple Evaluation Boundary Standard

OpenFGA Conditional Relationship Tuple Evaluation Boundary Standard defines an industrial-grade behavioral standard for security engineering. Enforces strict deadline propagation, circuit breaker boundaries, and deterministic context serialization when evaluating OpenFGA conditional relationship tuples. Unbounded evaluation of dynamic ABAC conditions allows authorization bypass via resource exhaustion, request hanging, and fail-open edge-case degradation under adversarial payload loads. All check evaluations must enforce immutable context validation, strict timeouts, and fail-closed security defaults. 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 or Fail-Open OpenFGA Check Execution with Dynamic Contextual Tuples 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 or Fail-Open OpenFGA Check Execution with Dynamic Contextual TuplesCritical
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 pass a bounded AbortSignal or context timeout (maximum 50-100ms) to every OpenFGA check request containing contextual tuples or conditions.

Engineers MUST ALWAYS pass a bounded AbortSignal or context timeout (maximum 50-100ms) to every OpenFGA check request containing contextual tuples or conditions.

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 enforce strict fail-closed (access denied) behavior on client timeouts, network drops, or CEL evaluation errors from OpenFGA.

Engineers MUST ALWAYS enforce strict fail-closed (access denied) behavior on client timeouts, network drops, or CEL evaluation errors from 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.
3

Engineers MUST validate and sanitize contextual tuple values using a deterministic runtime schema (e.g., Zod) before supplying them to OpenFGA to prevent nested payload exploitation.

Engineers MUST validate and sanitize contextual tuple values using a deterministic runtime schema (e.g., Zod) before supplying them to OpenFGA to prevent nested payload exploitation.

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

Engineers MUST NOT fallback to granting access when an OpenFGA evaluation times out or encounters a 5xx/evaluation error.

Engineers MUST NOT fallback to granting access when an OpenFGA evaluation times out or encounters a 5xx/evaluation error.

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

Services MUST enforce circuit breakers on repeated OpenFGA timeout errors to prevent cascade exhaustion across the downstream application tier.

Services MUST enforce circuit breakers on repeated OpenFGA timeout errors to prevent cascade exhaustion across the downstream application tier.

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 dynamic CEL script evaluations or deep recursive graph traversals without an explicit call-level deadline.

Components NEVER execute unbounded dynamic CEL script evaluations or deep recursive graph traversals without an explicit call-level deadline.

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 Conditional Relationship Tuple Evaluation Boundary Standard critical for AI coding assistants?

Enforces strict deadline propagation, circuit breaker boundaries, and deterministic context serialization when evaluating OpenFGA conditional relationship tuples. Unbounded evaluation of dynamic ABAC conditions allows authorization bypass via resource exhaustion, request hanging, and fail-open edge-case degradation under adversarial payload loads. All check evaluations must enforce immutable context validation, strict timeouts, and fail-closed security defaults. 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 or Fail-Open OpenFGA Check Execution with Dynamic Contextual Tuples) 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