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

Mandatory Real-Time OpenFGA Contextual Tuple Graph Resolution at Gateway

Enforces real-time Relationship-Based Access Control (ReBAC) authorization checks via OpenFGA at the API gateway layer to eliminate stale JWT claims and privilege escalation windows. Mandates the dynamic injection of ephemeral request attributes as contextual tuples into OpenFGA check evaluations rather than relying on cached, static token scopes or mutable client state.

Prohibited Anti-Pattern: Authorizing mutations using stale JWT scopes or local database lookups instead of real-time OpenFGA contextual graph evaluation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Mandatory Real-Time OpenFGA Contextual Tuple Graph Resolution at Gateway - Enforces real-time Relationship-Based Access Control (ReBAC) authorization checks via OpenFGA at the API gateway layer to eliminate stale JWT claims and privilege escalation windows. Mandates the dynamic injection of ephemeral request attributes as contextual tuples into OpenFGA check evaluations rather than relying on cached, static token scopes or mutable client state.
globs: src/gateway/**/*.{ts,js}, src/middleware/**/*.{ts,js}, src/auth/**/*.{ts,js}, src/plugins/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-real-time-contextual-rebac-validation"
---

# Mandatory Real-Time OpenFGA Contextual Tuple Graph Resolution at Gateway

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Authorizing mutations using stale JWT scopes or local database lookups instead of real-time OpenFGA contextual graph evaluation

## System Constraints
You are a Principal Security Architect enforcing zero-trust OpenFGA ReBAC authorization. You must ensure all authorization gates perform atomic, sub-millisecond graph checks using OpenFGA with dynamic contextual tuples. Prohibit reliance on static JWT role claims, prohibit bypass of gateway validation, and ensure fail-closed execution on OpenFGA client errors.

## Strict Guidelines
- Engineers MUST ALWAYS invoke OpenFGA `check` with exact object-relation-user tuples (`user:${userId}`, relation, `resource:${resourceId}`) at the gateway layer before routing requests to downstream microservices.
- Engineers MUST inject transient environment and request metadata (e.g., IP address, device trust, dynamic tenancy) as ephemeral `contextualTuples` or OpenFGA context objects during `check` calls without writing transient tuples to the persistent store.
- Engineers MUST NOT rely on static JWT claim arrays (such as `roles`, `permissions`, or `groups`) to grant access to tenant-scoped or hierarchical resources.
- Services MUST implement a strict fail-closed policy (`allow: false`) with structured audit logging if the OpenFGA evaluation times out or encounters network degradation.
- Components NEVER execute mutations or query database records before an explicit OpenFGA `allowed: true` response is verified.

## Bad vs Good Implementations
### Gateway Authorization Middleware

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Bypasses the centralized authorization model by inspecting unverified, stale token claims. Revocations, updated relationship graphs (e.g., inherited folder permissions), and contextual constraints (e.g., IP restrictions) are completely ignored.
```typescript
import { Request, Response, NextFunction } from 'express';

export function authorizeDocumentEdit(req: Request, res: Response, next: NextFunction) {
  // VULNERABLE: Relies on static, potentially revoked JWT claims
  // Stale permissions persist until token expiration (Time-of-Check to Time-of-Use flaw)
  const userClaims = req.user;
  const documentId = req.params.docId;

  if (userClaims.roles?.includes('editor') && userClaims.tenantId === req.headers['x-tenant-id']) {
    return next();
  }

  return res.status(403).json({ error: 'Forbidden' });
}
```

#### Production Standard (Correct)
> **Standard**: Performs dynamic, real-time graph traversal against the centralized OpenFGA instance. Dynamically supplies session tenant binding as an ephemeral contextual tuple without persistent storage pollution, and defaults to a secure fail-closed posture on error.
```typescript
import { Request, Response, NextFunction } from 'express';
import { OpenFgaClient } from '@openfga/sdk';

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

export async function authorizeDocumentEdit(req: Request, res: Response, next: NextFunction): Promise<void> {
  const userId = req.user?.sub;
  const { docId } = req.params;
  const tenantId = req.headers['x-tenant-id'] as string;

  if (!userId || !docId || !tenantId) {
    res.status(401).json({ error: 'Unauthorized: Missing required identity context' });
    return;
  }

  try {
    // Fail-closed real-time graph evaluation with ephemeral contextual tuple
    const { allowed } = await fgaClient.check({
      user: `user:${userId}`,
      relation: 'can_edit',
      object: `document:${docId}`,
      contextualTuples: [
        {
          user: `user:${userId}`,
          relation: 'active_session_tenant',
          object: `tenant:${tenantId}`,
        },
      ],
    });

    if (!allowed) {
      res.status(403).json({ error: 'AccessDenied: Insufficient ReBAC permissions' });
      return;
    }

    next();
  } catch (error) {
    // Fail-closed invariant
    req.log?.error({ err: error, docId, userId }, 'OpenFGA authorization check failed');
    res.status(503).json({ error: 'Authorization Service Unavailable' });
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Mandatory Real-Time OpenFGA Contextual Tuple Graph Resolution at Gateway

Mandatory Real-Time OpenFGA Contextual Tuple Graph Resolution at Gateway defines an industrial-grade behavioral standard for security engineering. Enforces real-time Relationship-Based Access Control (ReBAC) authorization checks via OpenFGA at the API gateway layer to eliminate stale JWT claims and privilege escalation windows. Mandates the dynamic injection of ephemeral request attributes as contextual tuples into OpenFGA check evaluations rather than relying on cached, static token scopes or mutable client state. 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: Authorizing mutations using stale JWT scopes or local database lookups instead of real-time OpenFGA contextual graph evaluation 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 DriftAuthorizing mutations using stale JWT scopes or local database lookups instead of real-time OpenFGA contextual graph evaluationCritical
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 invoke OpenFGA `check` with exact object-relation-user tuples (`user

Engineers MUST ALWAYS invoke OpenFGA `check` with exact object-relation-user tuples (`user:${userId}`, relation, `resource:${resourceId}`) at the gateway layer before routing requests to downstream microservices.

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 inject transient environment and request metadata (e.g., IP address, device trust, dynamic tenancy) as ephemeral `contextualTuples` or OpenFGA context objects during `check` calls without writing transient tuples to the persistent store.

Engineers MUST inject transient environment and request metadata (e.g., IP address, device trust, dynamic tenancy) as ephemeral `contextualTuples` or OpenFGA context objects during `check` calls without writing transient tuples to the persistent store.

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 NOT rely on static JWT claim arrays (such as `roles`, `permissions`, or `groups`) to grant access to tenant-scoped or hierarchical resources.

Engineers MUST NOT rely on static JWT claim arrays (such as `roles`, `permissions`, or `groups`) to grant access to tenant-scoped or hierarchical resources.

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 implement a strict fail-closed policy (`allow

Services MUST implement a strict fail-closed policy (`allow: false`) with structured audit logging if the OpenFGA evaluation times out or encounters network degradation.

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 execute mutations or query database records before an explicit OpenFGA `allowed

Components NEVER execute mutations or query database records before an explicit OpenFGA `allowed: true` response is verified.

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 Mandatory Real-Time OpenFGA Contextual Tuple Graph Resolution at Gateway critical for AI coding assistants?

Enforces real-time Relationship-Based Access Control (ReBAC) authorization checks via OpenFGA at the API gateway layer to eliminate stale JWT claims and privilege escalation windows. Mandates the dynamic injection of ephemeral request attributes as contextual tuples into OpenFGA check evaluations rather than relying on cached, static token scopes or mutable client state. 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 (Authorizing mutations using stale JWT scopes or local database lookups instead of real-time OpenFGA contextual graph evaluation) 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

Mandatory