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

OpenFGA 1.8 Contextual Tuple Gateway Boundary & Schema Invariants

Enforces strict API gateway boundary validation, cryptographic signing, and relation allowlisting on transient contextual tuples passed to OpenFGA Check calls. Unsanitized contextual tuples allow untrusted clients to inject arbitrary graph relationships (e.g., claiming 'admin' relation or overriding resource tenancy) into low-latency evaluation queries, causing direct privilege escalation. All contextual tuples must be synthesized exclusively by trusted internal boundary services or verified against strict schema and scope constraints.

Prohibited Anti-Pattern: Blind Passthrough of Untrusted Client Contextual Tuples Directly into OpenFGA Check Queries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA 1.8 Contextual Tuple Gateway Boundary & Schema Invariants - Enforces strict API gateway boundary validation, cryptographic signing, and relation allowlisting on transient contextual tuples passed to OpenFGA Check calls. Unsanitized contextual tuples allow untrusted clients to inject arbitrary graph relationships (e.g., claiming 'admin' relation or overriding resource tenancy) into low-latency evaluation queries, causing direct privilege escalation. All contextual tuples must be synthesized exclusively by trusted internal boundary services or verified against strict schema and scope constraints.
globs: src/auth/**/*.ts, src/middleware/**/*.ts, src/gateways/**/*.ts, src/services/authz/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuple-gateway-invariant"
---

# OpenFGA 1.8 Contextual Tuple Gateway Boundary & Schema Invariants

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Blind Passthrough of Untrusted Client Contextual Tuples Directly into OpenFGA Check Queries

## System Constraints
You are a Principal Security Architect enforcing the OpenFGA 1.8 Contextual Tuple Gateway Invariant. You must reject any code where contextual tuples originate directly from untrusted client payloads without server-side schema validation, strict relation allowlisting, tenant isolation enforcement, and cryptographically verified context derivation. Ensure all transient authorization context is bounded and immune to privilege injection.

## Strict Guidelines
- Services MUST NEVER forward raw client-provided tuple keys (user, relation, object) directly into the `contextual_tuples` parameter of OpenFGA Check or ListObjects API calls.
- Boundary gateways MUST enforce an explicit allowlist of permissible relations for contextual assertions (e.g., temporal or ephemeral claims like `current_ip_trusted`, `mfa_verified`), strictly forbidding persistence-defining relations like `owner`, `admin`, or `parent_folder`.
- Contextual tuple generation MUST validate that the `user` identifier strictly matches the authenticated, cryptographically verified session subject (`sub`), preventing spoofing of other users or service accounts.
- Contextual tuple objects MUST strictly enforce tenant boundary prefixes (e.g., `tenant:<tenant_id>#...`) to prevent cross-tenant object state injection.
- Engineers MUST apply schema validation (via Zod, TypeBox, or JSON Schema) before assembling transient tuples, rejecting payloads with unexpected fields, wildcards (`*`), or malformed type namespaces.

## Bad vs Good Implementations
### Untrusted Contextual Tuple Passthrough vs. Gateway-Derived Ephemeral Context

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly feeding client-supplied tuples into OpenFGA contextualTuples allows users to spoof structural relations like 'owner' or 'editor' on the target or related resources, completely bypassing database RBAC/ReBAC boundaries.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { Request, Response } from 'express';

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

// ANTI-PATTERN: Client sends contextual_tuples directly in request body
export async function authorizeUserAction(req: Request, res: Response) {
  const { contextualTuples } = req.body;
  const userId = req.headers['x-user-id'] as string;

  // VULNERABILITY: An attacker can pass [{ user: 'user:attacker', relation: 'owner', object: 'organization:target' }]
  // granting themselves arbitrary ephemeral permissions during the evaluation phase.
  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'can_delete',
    object: `document:${req.params.docId}`,
    contextualTuples: contextualTuples,
  });

  return res.json({ allowed: response.allowed });
}
```

#### Production Standard (Correct)
> **Standard**: Contextual tuples are synthesized exclusively from verified cryptographic session claims (e.g., MFA status) and constrained to an explicit relation allowlist. Tenant scoping is strictly bound to the authenticated subject's organization, preventing cross-tenant and arbitrary relationship injection.
```typescript
import { OpenFgaClient, ClientTupleKey } from '@openfga/sdk';
import { Request, Response } from 'express';
import { z } from 'zod';

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

// STRICT ALLOWLIST: Only ephemeral, session-bound relations derived server-side
const ALLOWED_EPHEMERAL_RELATIONS = ['mfa_verified', 'ip_allowlisted'] as const;
type EphemeralRelation = typeof ALLOWED_EPHEMERAL_RELATIONS[number];

export async function authorizeUserAction(req: Request, res: Response) {
  // 1. Extract verified claims from authenticated token context (never raw headers)
  const session = req.user; // Set by verified JWT/mTLS middleware
  if (!session?.tenantId || !session?.sub) {
    return res.status(401).json({ error: 'Unauthenticated context' });
  }

  // 2. Synthesize contextual tuples internally based on validated state
  const validatedContextualTuples: ClientTupleKey[] = [];
  
  if (session.amr?.includes('mfa')) {
    validatedContextualTuples.push({
      user: `user:${session.sub}`,
      relation: 'mfa_verified',
      object: `session:${session.sessionId}`,
    });
  }

  // 3. Bound tenant scope on the evaluated resource
  const docId = z.string().uuid().parse(req.params.docId);
  const tenantBoundObject = `organization:${session.tenantId}:doc:${docId}`;

  // 4. Execute check with securely formed, boundary-verified tuples
  const response = await fgaClient.check({
    user: `user:${session.sub}`,
    relation: 'can_delete',
    object: tenantBoundObject,
    contextualTuples: validatedContextualTuples,
  });

  return res.json({ allowed: Boolean(response.allowed) });
}
```

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 1.8 Contextual Tuple Gateway Boundary & Schema Invariants

OpenFGA 1.8 Contextual Tuple Gateway Boundary & Schema Invariants defines an industrial-grade behavioral standard for security engineering. Enforces strict API gateway boundary validation, cryptographic signing, and relation allowlisting on transient contextual tuples passed to OpenFGA Check calls. Unsanitized contextual tuples allow untrusted clients to inject arbitrary graph relationships (e.g., claiming 'admin' relation or overriding resource tenancy) into low-latency evaluation queries, causing direct privilege escalation. All contextual tuples must be synthesized exclusively by trusted internal boundary services or verified against strict schema and scope constraints. 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: Blind Passthrough of Untrusted Client Contextual Tuples Directly into OpenFGA Check Queries 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 DriftBlind Passthrough of Untrusted Client Contextual Tuples Directly into OpenFGA Check QueriesCritical
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

Services MUST NEVER forward raw client-provided tuple keys (user, relation, object) directly into the `contextual_tuples` parameter of OpenFGA Check or ListObjects API calls.

Services MUST NEVER forward raw client-provided tuple keys (user, relation, object) directly into the `contextual_tuples` parameter of OpenFGA Check or ListObjects API calls.

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

Boundary gateways MUST enforce an explicit allowlist of permissible relations for contextual assertions (e.g., temporal or ephemeral claims like `current_ip_trusted`, `mfa_verified`), strictly forbidding persistence-defining relations like `owner`, `admin`, or `parent_folder`.

Boundary gateways MUST enforce an explicit allowlist of permissible relations for contextual assertions (e.g., temporal or ephemeral claims like `current_ip_trusted`, `mfa_verified`), strictly forbidding persistence-defining relations like `owner`, `admin`, or `parent_folder`.

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

Contextual tuple generation MUST validate that the `user` identifier strictly matches the authenticated, cryptographically verified session subject (`sub`), preventing spoofing of other users or service accounts.

Contextual tuple generation MUST validate that the `user` identifier strictly matches the authenticated, cryptographically verified session subject (`sub`), preventing spoofing of other users or service accounts.

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

Contextual tuple objects MUST strictly enforce tenant boundary prefixes (e.g., `tenant

Contextual tuple objects MUST strictly enforce tenant boundary prefixes (e.g., `tenant:<tenant_id>#...`) to prevent cross-tenant object state injection.

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

Engineers MUST apply schema validation (via Zod, TypeBox, or JSON Schema) before assembling transient tuples, rejecting payloads with unexpected fields, wildcards (`*`), or malformed type namespaces.

Engineers MUST apply schema validation (via Zod, TypeBox, or JSON Schema) before assembling transient tuples, rejecting payloads with unexpected fields, wildcards (`*`), or malformed type namespaces.

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 1.8 Contextual Tuple Gateway Boundary & Schema Invariants critical for AI coding assistants?

Enforces strict API gateway boundary validation, cryptographic signing, and relation allowlisting on transient contextual tuples passed to OpenFGA Check calls. Unsanitized contextual tuples allow untrusted clients to inject arbitrary graph relationships (e.g., claiming 'admin' relation or overriding resource tenancy) into low-latency evaluation queries, causing direct privilege escalation. All contextual tuples must be synthesized exclusively by trusted internal boundary services or verified against strict schema and scope constraints. 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 (Blind Passthrough of Untrusted Client Contextual Tuples Directly into OpenFGA Check Queries) 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