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

OpenFGA 1.8 ReBAC Ephemeral Contextual Tuple Guardrail

Enforces deterministic, zero-leakage relationship-based access control (ReBAC) across distributed microservice meshes using OpenFGA 1.8. Mandates that dynamic request attributes and transient authorization relations are supplied strictly via contextual tuples and CEL condition contexts rather than persistent database writes. Guarantees sub-millisecond check latency while preventing stale privilege escalation across service boundaries.

Prohibited Anti-Pattern: Persisting Ephemeral Request State as Storage Tuples Causing Permission Bleed and Latency Spikes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA 1.8 ReBAC Ephemeral Contextual Tuple Guardrail - Enforces deterministic, zero-leakage relationship-based access control (ReBAC) across distributed microservice meshes using OpenFGA 1.8. Mandates that dynamic request attributes and transient authorization relations are supplied strictly via contextual tuples and CEL condition contexts rather than persistent database writes. Guarantees sub-millisecond check latency while preventing stale privilege escalation across service boundaries.
globs: src/**/auth/**/*.{ts,js,go,py}, src/**/middleware/**/*.{ts,js,go,py}, src/**/guards/**/*.{ts,js,go,py}, src/**/*authorizer*.{ts,js,go,py}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-rebac-contextual-tuple-authorization-standard"
---

# OpenFGA 1.8 ReBAC Ephemeral Contextual Tuple Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Persisting Ephemeral Request State as Storage Tuples Causing Permission Bleed and Latency Spikes

## System Constraints
You are a Principal Security Architect enforcing the OpenFGA 1.8 ReBAC Contextual Tuple Authorization Standard. You must reject any implementation that writes ephemeral request-scoped states (e.g., temporary tenant context, session scopes, step-up elevation, dynamic team membership) into persistent OpenFGA storage. Mandate the use of OpenFGA runtime `contextual_tuples` and CEL `context` parameters during `check` and `batchCheck` operations. Enforce strict timeout bounds, connection re-use via gRPC, and fail-closed evaluation paradigms to eliminate cross-request authorization leakage.

## Strict Guidelines
- Engineers MUST ALWAYS supply transient, request-scoped, or dynamic relationship data via OpenFGA runtime `contextual_tuples` instead of issuing persistent `write` calls.
- Engineers MUST NOT execute mutating OpenFGA write transactions within synchronous HTTP/gRPC request-response paths to represent temporary or session-bound permissions.
- Code MUST pass CEL-evaluated dynamic parameters (e.g., IP address, request timestamp, MFA verification status) using the OpenFGA 1.8 `context` payload in the `check` request.
- Services MUST configure OpenFGA SDK clients with HTTP/2 or gRPC keep-alive and strict deadline timeouts (<= 15ms) to guarantee mesh-level latency budgets.
- Components NEVER fall back to permissive default allowances on authorization check errors or network timeouts; all authorization evaluation MUST fail closed.

## Bad vs Good Implementations
### Contextual Tuple & CEL Evaluation vs. Leaky Persistent Writes

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Synchronously writing and deleting ephemeral tuples in persistent storage introduces distributed race conditions, severe latency degradation, and privilege escalation vulnerabilities when deletes fail.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

export async function authorizeDocumentAccessBad(
  fgaClient: OpenFgaClient,
  userId: string,
  documentId: string,
  ephemeralDepartmentId: string
): Promise<boolean> {
  // ANTI-PATTERN: Writing transient request state directly to the persistent datastore
  // Causes cross-tenant data leakage if cleanup fails, incurs DB write latency (50-200ms),
  // and violates sub-millisecond mesh invariants.
  await fgaClient.write({
    writes: [
      {
        user: `user:${userId}`,
        relation: 'temporary_member',
        object: `department:${ephemeralDepartmentId}`,
      },
    ],
  });

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

  // Cleanup can fail on process crash or network partition, leaving orphaned permissions
  await fgaClient.write({
    deletes: [
      {
        user: `user:${userId}`,
        relation: 'temporary_member',
        object: `department:${ephemeralDepartmentId}`,
      },
    ],
  });

  return allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: Supplies transient state solely in-memory via contextualTuples and context attributes. Eliminates database I/O, prevents state leakage across concurrent requests, and fails closed under network errors.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

export async function authorizeDocumentAccessGood(
  fgaClient: OpenFgaClient,
  userId: string,
  documentId: string,
  ephemeralDepartmentId: string,
  clientIp: string
): Promise<boolean> {
  // PRODUCTION INVARIANT: Inject transient relationships via contextual_tuples
  // and pass dynamic attributes via the context object for OpenFGA 1.8 CEL conditions.
  const checkPayload: ClientCheckRequest = {
    user: `user:${userId}`,
    relation: 'viewer',
    object: `document:${documentId}`,
    contextualTuples: [
      {
        user: `user:${userId}`,
        relation: 'temporary_member',
        object: `department:${ephemeralDepartmentId}`,
      },
    ],
    context: {
      current_time: new Date().toISOString(),
      source_ip: clientIp,
    },
  };

  try {
    const response = await fgaClient.check(checkPayload);
    return response.allowed === true;
  } catch (error) {
    // Fail closed on evaluation failure, network timeout, or schema mismatches
    return false;
  }
}
```

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 ReBAC Ephemeral Contextual Tuple Guardrail

OpenFGA 1.8 ReBAC Ephemeral Contextual Tuple Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces deterministic, zero-leakage relationship-based access control (ReBAC) across distributed microservice meshes using OpenFGA 1.8. Mandates that dynamic request attributes and transient authorization relations are supplied strictly via contextual tuples and CEL condition contexts rather than persistent database writes. Guarantees sub-millisecond check latency while preventing stale privilege escalation across service 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: Persisting Ephemeral Request State as Storage Tuples Causing Permission Bleed and Latency Spikes 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 DriftPersisting Ephemeral Request State as Storage Tuples Causing Permission Bleed and Latency SpikesCritical
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 supply transient, request-scoped, or dynamic relationship data via OpenFGA runtime `contextual_tuples` instead of issuing persistent `write` calls.

Engineers MUST ALWAYS supply transient, request-scoped, or dynamic relationship data via OpenFGA runtime `contextual_tuples` instead of issuing persistent `write` 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

Engineers MUST NOT execute mutating OpenFGA write transactions within synchronous HTTP/gRPC request-response paths to represent temporary or session-bound permissions.

Engineers MUST NOT execute mutating OpenFGA write transactions within synchronous HTTP/gRPC request-response paths to represent temporary or session-bound permissions.

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

Code MUST pass CEL-evaluated dynamic parameters (e.g., IP address, request timestamp, MFA verification status) using the OpenFGA 1.8 `context` payload in the `check` request.

Code MUST pass CEL-evaluated dynamic parameters (e.g., IP address, request timestamp, MFA verification status) using the OpenFGA 1.8 `context` payload in the `check` 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.
4

Services MUST configure OpenFGA SDK clients with HTTP/2 or gRPC keep-alive and strict deadline timeouts (<= 15ms) to guarantee mesh-level latency budgets.

Services MUST configure OpenFGA SDK clients with HTTP/2 or gRPC keep-alive and strict deadline timeouts (<= 15ms) to guarantee mesh-level latency budgets.

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 fall back to permissive default allowances on authorization check errors or network timeouts

Components NEVER fall back to permissive default allowances on authorization check errors or network timeouts; all authorization evaluation MUST fail closed.

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 ReBAC Ephemeral Contextual Tuple Guardrail critical for AI coding assistants?

Enforces deterministic, zero-leakage relationship-based access control (ReBAC) across distributed microservice meshes using OpenFGA 1.8. Mandates that dynamic request attributes and transient authorization relations are supplied strictly via contextual tuples and CEL condition contexts rather than persistent database writes. Guarantees sub-millisecond check latency while preventing stale privilege escalation across service 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 (Persisting Ephemeral Request State as Storage Tuples Causing Permission Bleed and Latency Spikes) 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