This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: openfga-ephemeral-contextual-tuples-evaluation-guardrail

OpenFGA Ephemeral Contextual Tuples Evaluation Guardrail

Mandates that dynamic runtime attributes and transient environmental conditions are passed exclusively as evaluated contextual tuples or condition context during OpenFGA check evaluations. Strictly prohibits writing transient, request-bound authorization state to persistent tuple databases to eliminate privilege leaks, race conditions, and tuple store pollution.

Prohibited Anti-Pattern: Persisting Transient Transaction State to OpenFGA Storage Instead of Passing In-Memory Contextual Tuples

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Ephemeral Contextual Tuples Evaluation Guardrail - Mandates that dynamic runtime attributes and transient environmental conditions are passed exclusively as evaluated contextual tuples or condition context during OpenFGA check evaluations. Strictly prohibits writing transient, request-bound authorization state to persistent tuple databases to eliminate privilege leaks, race conditions, and tuple store pollution.
globs: src/**/*.{ts,tsx}, lib/**/*.{ts,tsx}, services/**/*.{ts,tsx}, auth/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-ephemeral-contextual-tuples-evaluation-guardrail"
---

# OpenFGA Ephemeral Contextual Tuples Evaluation Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Persisting Transient Transaction State to OpenFGA Storage Instead of Passing In-Memory Contextual Tuples

## System Constraints
You are a Principal Software Architect enforcing OpenFGA Ephemeral Contextual Tuples Evaluation Guardrail. Mandate that transient authorization factors (MFA satisfaction, time windows, IP CIDRs, device posture, and single-use approvals) are evaluated exclusively via OpenFGA in-memory contextual tuples or evaluation context. Never allow temporary tuple persistence (`write` followed by `delete`) in the backing Zanzibar store.

## Strict Guidelines
- Engineers MUST ALWAYS validate runtime attributes (e.g., via Zod schemas) before injecting them into OpenFGA contextual tuples or condition context.
- Engineers MUST NOT persist ephemeral, request-scoped access grants to persistent tuple storage via `fgaClient.writeTuples()` or transactional database mutations.
- Code MUST supply ephemeral relationship assertions directly inside the `contextualTuples` field of `fgaClient.check()` requests.
- Services MUST pass dynamic boundary values (e.g., `client_ip`, `current_time`, `transaction_amount`) inside the `context` parameter for condition evaluation in OpenFGA DSL 1.2+ models.
- Components NEVER rely on a 'write-check-delete' pattern for short-lived authorizations, as partial failures leave persistent zombie permissions active.

## Bad vs Good Implementations
### Ephemeral Dynamic Factor Authorization Check

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Writing transient state (MFA verification) into the persistent tuple store creates severe security vulnerabilities: concurrent requests by the same user gain unintended privileges, and failures or timeouts before deletion cause permanent privilege escalation (zombie tuples).
```typescript
import { OpenFgaClient } from '@openfga/sdk';

export async function verifyTransferAccess(
  fgaClient: OpenFgaClient,
  userId: string,
  accountId: string,
  mfaValidated: boolean
): Promise<boolean> {
  // VULNERABLE: Persisting ephemeral state to the persistent tuple store
  if (mfaValidated) {
    await fgaClient.write({
      writes: [{
        user: `user:${userId}`,
        relation: 'mfa_authenticated',
        object: `account:${accountId}`
      }]
    });
  }

  const { allowed } = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'can_transfer',
    object: `account:${accountId}`
  });

  // Flawed cleanup: Server crashes, timeouts, or unhandled exceptions leak the tuple
  if (mfaValidated) {
    await fgaClient.write({
      deletes: [{
        user: `user:${userId}`,
        relation: 'mfa_authenticated',
        object: `account:${accountId}`
      }]
    });
  }

  return allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: Dynamic environmental attributes and transient claims are validated and passed using native `contextualTuples` and `context` parameters during `fgaClient.check()`. No state is persisted to the database, ensuring zero residual privilege leaks, atomic request isolation, and zero-trust consistency.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { z } from 'zod';

const RuntimeContextSchema = z.object({
  userId: z.string().uuid(),
  accountId: z.string().uuid(),
  mfaValidated: z.boolean(),
  clientIp: z.string().ip(),
  requestTimestamp: z.string().datetime()
});

export async function verifyTransferAccess(
  fgaClient: OpenFgaClient,
  rawContext: unknown
): Promise<boolean> {
  const context = RuntimeContextSchema.parse(rawContext);

  // SECURE: Contextual tuples exist only for the lifecycle of the evaluation
  const contextualTuples = context.mfaValidated
    ? [{
        user: `user:${context.userId}`,
        relation: 'mfa_authenticated',
        object: `account:${context.accountId}`
      }]
    : [];

  const { allowed } = await fgaClient.check({
    user: `user:${context.userId}`,
    relation: 'can_transfer',
    object: `account:${context.accountId}`,
    contextualTuples,
    context: {
      current_time: context.requestTimestamp,
      source_ip: context.clientIp
    }
  });

  return allowed ?? false;
}
```

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 Ephemeral Contextual Tuples Evaluation Guardrail

OpenFGA Ephemeral Contextual Tuples Evaluation Guardrail defines an industrial-grade behavioral standard for security engineering. Mandates that dynamic runtime attributes and transient environmental conditions are passed exclusively as evaluated contextual tuples or condition context during OpenFGA check evaluations. Strictly prohibits writing transient, request-bound authorization state to persistent tuple databases to eliminate privilege leaks, race conditions, and tuple store pollution. 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 Transient Transaction State to OpenFGA Storage Instead of Passing In-Memory 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 DriftPersisting Transient Transaction State to OpenFGA Storage Instead of Passing In-Memory 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 validate runtime attributes (e.g., via Zod schemas) before injecting them into OpenFGA contextual tuples or condition context.

Engineers MUST ALWAYS validate runtime attributes (e.g., via Zod schemas) before injecting them into OpenFGA contextual tuples or condition context.

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 persist ephemeral, request-scoped access grants to persistent tuple storage via `fgaClient.writeTuples()` or transactional database mutations.

Engineers MUST NOT persist ephemeral, request-scoped access grants to persistent tuple storage via `fgaClient.writeTuples()` or transactional database mutations.

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 supply ephemeral relationship assertions directly inside the `contextualTuples` field of `fgaClient.check()` requests.

Code MUST supply ephemeral relationship assertions directly inside the `contextualTuples` field of `fgaClient.check()` requests.

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 pass dynamic boundary values (e.g., `client_ip`, `current_time`, `transaction_amount`) inside the `context` parameter for condition evaluation in OpenFGA DSL 1.2+ models.

Services MUST pass dynamic boundary values (e.g., `client_ip`, `current_time`, `transaction_amount`) inside the `context` parameter for condition evaluation in OpenFGA DSL 1.2+ models.

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 rely on a 'write-check-delete' pattern for short-lived authorizations, as partial failures leave persistent zombie permissions active.

Components NEVER rely on a 'write-check-delete' pattern for short-lived authorizations, as partial failures leave persistent zombie permissions active.

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

Mandates that dynamic runtime attributes and transient environmental conditions are passed exclusively as evaluated contextual tuples or condition context during OpenFGA check evaluations. Strictly prohibits writing transient, request-bound authorization state to persistent tuple databases to eliminate privilege leaks, race conditions, and tuple store pollution. 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 Transient Transaction State to OpenFGA Storage Instead of Passing In-Memory 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