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

OpenFGA Dynamic Contextual Tuple Ingestion Boundary Validation & Anti-Escalation Guardrail

Restricts ephemeral, request-time contextual authorization tuples to strictly typed, allowlisted, non-escalatable claim schemas. Ingesting untrusted or weakly validated client claims directly into OpenFGA contextual tuples allows adversaries to inject arbitrary relation edges (such as owner or admin) and bypass zero-trust access boundaries.

Prohibited Anti-Pattern: Unvalidated Contextual Tuple Injection Permitting Dynamic Privilege Escalation in OpenFGA Check Calls

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Dynamic Contextual Tuple Ingestion Boundary Validation & Anti-Escalation Guardrail - Restricts ephemeral, request-time contextual authorization tuples to strictly typed, allowlisted, non-escalatable claim schemas. Ingesting untrusted or weakly validated client claims directly into OpenFGA contextual tuples allows adversaries to inject arbitrary relation edges (such as owner or admin) and bypass zero-trust access boundaries.
globs: src/**/authz/**/*.ts, src/**/authorization/**/*.ts, src/**/fga/**/*.ts, src/**/guards/**/*.ts, src/**/policies/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuple-boundary-validation"
---

# OpenFGA Dynamic Contextual Tuple Ingestion Boundary Validation & Anti-Escalation Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unvalidated Contextual Tuple Injection Permitting Dynamic Privilege Escalation in OpenFGA Check Calls

## System Constraints
You are a Principal Security Architect enforcing boundary validation on OpenFGA dynamic contextual tuples. Mandate strict schema validation, cryptographic claim extraction, and hard relation allowlisting to prevent client-controlled privilege elevation.

## Strict Guidelines
- Engineers MUST ALWAYS validate ephemeral claims through a strict runtime schema (e.g., Zod) before compiling OpenFGA contextual tuples.
- Engineers MUST NOT allow client-controlled request bodies or unverified query parameters to dictate tuple `relation` or `object` targets directly.
- Services MUST restrict contextual tuple relations to an explicit allowlist of ephemeral, transient predicates (e.g., `is_mfa_authenticated`, `within_ip_fencing`, `has_valid_device_claim`).
- Services MUST NEVER permit structural or hierarchical relations (e.g., `owner`, `admin`, `member`, `editor`, `parent`) to be satisfied via dynamic contextual tuples.
- Code SHOULD extract tuple `user` identifiers exclusively from cryptographically verified authentication state (e.g., verified JWT claims or authenticated session context), never from raw payload input.

## Bad vs Good Implementations
### Unsanitized Contextual Tuple Ingestion (Vulnerable) vs. Typed Allowlisted Boundary Compiler (Secure)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Contextual tuples are accepted directly from an untrusted client payload without schema verification or relation allowlisting. An attacker can inject relation edges such as 'owner' or 'editor' on the target resource, causing the OpenFGA graph traversal to resolve to true regardless of persistent access state.
```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!,
});

// VULNERABLE: Client controls contextual tuples directly
export async function authorizeDocumentAccess(req: Request, res: Response) {
  const { documentId } = req.params;
  const userId = req.headers['x-user-id'] as string; // Untrusted header
  const clientTuples = req.body.contextualTuples || []; // Attacker passes [{ user: 'user:attacker', relation: 'owner', object: 'doc:123' }]

  const { allowed } = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'can_read',
    object: `document:${documentId}`,
    contextualTuples: clientTuples,
  });

  if (!allowed) {
    return res.status(403).json({ error: 'Access denied' });
  }
  return res.status(200).json({ status: 'authorized' });
}
```

#### Production Standard (Correct)
> **Standard**: Subject and claims are derived strictly from cryptographically verified server-side session and token claims. Contextual tuples are mapped programmatically against an explicit allowlist of ephemeral relations; no external input can inject arbitrary relations or structural ownership edges.
```typescript
import { OpenFgaClient, ClientCheckRequest } 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!,
});

// SECURE: Strict allowlist of ephemeral dynamic relations
const ALLOWED_EPHEMERAL_RELATIONS = ['device_trusted', 'mfa_verified', 'ip_geofenced'] as const;
type EphemeralRelation = typeof ALLOWED_EPHEMERAL_RELATIONS[number];

const ContextualClaimSchema = z.object({
  deviceTrusted: z.boolean().default(false),
  mfaVerified: z.boolean().default(false),
  ipGeofenced: z.boolean().default(false),
});

export async function authorizeDocumentAccess(req: Request, res: Response) {
  const { documentId } = req.params;
  
  // Subject derived strictly from verified cryptographic session, not user input
  const sessionUser = req.user;
  if (!sessionUser?.id) {
    return res.status(401).json({ error: 'Unauthenticated' });
  }

  // Boundary validation against validated environment/token claims
  const claims = ContextualClaimSchema.parse({
    deviceTrusted: req.authClaims?.device_status === 'compliant',
    mfaVerified: req.authClaims?.amr?.includes('mfa') ?? false,
    ipGeofenced: req.authClaims?.is_corporate_ip ?? false,
  });

  const contextualTuples: ClientCheckRequest['contextualTuples'] = [];
  const userSubject = `user:${sessionUser.id}`;
  const targetObject = `document:${documentId}`;

  // Programmatically construct strictly allowlisted tuples
  if (claims.deviceTrusted) {
    contextualTuples.push({ user: userSubject, relation: 'device_trusted', object: targetObject });
  }
  if (claims.mfaVerified) {
    contextualTuples.push({ user: userSubject, relation: 'mfa_verified', object: targetObject });
  }
  if (claims.ipGeofenced) {
    contextualTuples.push({ user: userSubject, relation: 'ip_geofenced', object: targetObject });
  }

  const { allowed } = await fgaClient.check({
    user: userSubject,
    relation: 'can_read',
    object: targetObject,
    contextualTuples,
  });

  if (!allowed) {
    return res.status(403).json({ error: 'Access denied' });
  }
  return res.status(200).json({ status: 'authorized' });
}
```

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 Dynamic Contextual Tuple Ingestion Boundary Validation & Anti-Escalation Guardrail

OpenFGA Dynamic Contextual Tuple Ingestion Boundary Validation & Anti-Escalation Guardrail defines an industrial-grade behavioral standard for security engineering. Restricts ephemeral, request-time contextual authorization tuples to strictly typed, allowlisted, non-escalatable claim schemas. Ingesting untrusted or weakly validated client claims directly into OpenFGA contextual tuples allows adversaries to inject arbitrary relation edges (such as owner or admin) and bypass zero-trust access boundaries. 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: Unvalidated Contextual Tuple Injection Permitting Dynamic Privilege Escalation in OpenFGA Check Calls 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 DriftUnvalidated Contextual Tuple Injection Permitting Dynamic Privilege Escalation in OpenFGA Check CallsCritical
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 ephemeral claims through a strict runtime schema (e.g., Zod) before compiling OpenFGA contextual tuples.

Engineers MUST ALWAYS validate ephemeral claims through a strict runtime schema (e.g., Zod) before compiling OpenFGA contextual 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.
2

Engineers MUST NOT allow client-controlled request bodies or unverified query parameters to dictate tuple `relation` or `object` targets directly.

Engineers MUST NOT allow client-controlled request bodies or unverified query parameters to dictate tuple `relation` or `object` targets directly.

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 restrict contextual tuple relations to an explicit allowlist of ephemeral, transient predicates (e.g., `is_mfa_authenticated`, `within_ip_fencing`, `has_valid_device_claim`).

Services MUST restrict contextual tuple relations to an explicit allowlist of ephemeral, transient predicates (e.g., `is_mfa_authenticated`, `within_ip_fencing`, `has_valid_device_claim`).

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 NEVER permit structural or hierarchical relations (e.g., `owner`, `admin`, `member`, `editor`, `parent`) to be satisfied via dynamic contextual tuples.

Services MUST NEVER permit structural or hierarchical relations (e.g., `owner`, `admin`, `member`, `editor`, `parent`) to be satisfied via dynamic contextual 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.
5

Code SHOULD extract tuple `user` identifiers exclusively from cryptographically verified authentication state (e.g., verified JWT claims or authenticated session context), never from raw payload input.

Code SHOULD extract tuple `user` identifiers exclusively from cryptographically verified authentication state (e.g., verified JWT claims or authenticated session context), never from raw payload input.

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 Dynamic Contextual Tuple Ingestion Boundary Validation & Anti-Escalation Guardrail critical for AI coding assistants?

Restricts ephemeral, request-time contextual authorization tuples to strictly typed, allowlisted, non-escalatable claim schemas. Ingesting untrusted or weakly validated client claims directly into OpenFGA contextual tuples allows adversaries to inject arbitrary relation edges (such as owner or admin) and bypass zero-trust access boundaries. 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 (Unvalidated Contextual Tuple Injection Permitting Dynamic Privilege Escalation in OpenFGA Check Calls) 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