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

OpenFGA Ephemeral Contextual Tuple Horizon Enforcement

Enforces zero-staleness dynamic authorization decisions by restricting high-churn, transient attributes (such as break-glass elevation, device posture, and session-scoped geo/IP conditions) to in-memory contextual tuples during OpenFGA Check operations. Prohibits persisting ephemeral authorization state to durable tuple storage, preventing tuple store bloat, cross-region replication lag, and window-of-exposure race conditions.

Prohibited Anti-Pattern: Persisting Volatile Session and Environmental State into Durable OpenFGA Tuples Instead of Contextual Check Tuples

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Ephemeral Contextual Tuple Horizon Enforcement - Enforces zero-staleness dynamic authorization decisions by restricting high-churn, transient attributes (such as break-glass elevation, device posture, and session-scoped geo/IP conditions) to in-memory contextual tuples during OpenFGA Check operations. Prohibits persisting ephemeral authorization state to durable tuple storage, preventing tuple store bloat, cross-region replication lag, and window-of-exposure race conditions.
globs: src/auth/**/*.{ts,js}, src/services/**/*.{ts,js}, src/middleware/**/*.{ts,js}, lib/auth/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-ephemeral-contextual-tuple-horizon"
---

# OpenFGA Ephemeral Contextual Tuple Horizon Enforcement

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Persisting Volatile Session and Environmental State into Durable OpenFGA Tuples Instead of Contextual Check Tuples

## System Constraints
You are a Principal Security Architect and Rules Author enforcing Zanzibar/OpenFGA authorization invariants. Volatile, temporal, or request-specific authorization context (e.g., device compliance, IP range verification, break-glass emergency access, step-up MFA, time-bound session scopes) must never be committed to persistent OpenFGA tuple storage via `write` operations. You must mandate that ephemeral authorization data is strictly injected via the `contextual_tuples` parameter on `client.check()` or `client.batchCheck()` calls, ensuring sub-millisecond evaluation, zero replication staleness, and zero leftover privileges.

## Strict Guidelines
- Engineers MUST ALWAYS supply transient, high-churn state (e.g., IP boundary validations, device compliance flags, active break-glass tokens) via `contextual_tuples` directly in the OpenFGA `check` or `batchCheck` request.
- Engineers MUST NOT write ephemeral, session-bound, or short-lived relationship tuples to persistent OpenFGA storage using `writeTuples` or transactional tuple writes.
- Services MUST cryptographically verify and validate incoming ephemeral session attributes (signatures, timestamps, issuer) at the API edge prior to materializing them as contextual tuples.
- Code SHOULD enforce strict structural schema validation on contextual tuples before dispatching the authorization query to prevent malformed tuple injection.
- Components NEVER rely on out-of-band asynchronous cleanup jobs, database TTLs, or `try...finally` write/delete blocks to manage volatile relationship lifecycles in OpenFGA.

## Bad vs Good Implementations
### Ephemeral Break-Glass Access Evaluation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Writing transient authorization tuples to persistent storage induces database replication lag, creates write contention, and introduces severe security leak vulnerabilities when process failures or network errors skip the cleanup block.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

export async function evaluateAccessWithBreakGlass(
  fgaClient: OpenFgaClient,
  userId: string,
  documentId: string,
  breakGlassToken: { active: boolean; justification: string }
): Promise<boolean> {
  // ANTI-PATTERN: Writing ephemeral, short-lived session states to durable storage.
  // This causes high write churn, replication lag vulnerabilities, and potential security leaks if delete fails.
  if (breakGlassToken.active) {
    await fgaClient.write({
      writes: [
        {
          user: `user:${userId}`,
          relation: 'emergency_responder',
          object: `document:${documentId}`
        }
      ]
    });
  }

  try {
    const response = await fgaClient.check({
      user: `user:${userId}`,
      relation: 'can_view',
      object: `document:${documentId}`
    });
    return response.allowed ?? false;
  } finally {
    if (breakGlassToken.active) {
      // Cleanup is error-prone: unhandled crashes, network partitions, or process kills leave permissions dangling
      await fgaClient.write({
        deletes: [
          {
            user: `user:${userId}`,
            relation: 'emergency_responder',
            object: `document:${documentId}`
          }
        ]
      });
    }
  }
}
```

#### Production Standard (Correct)
> **Standard**: Supplies transient state strictly via OpenFGA's contextualTuples array. The relationship tuple exists solely within the memory of the evaluation engine for that request, guaranteeing zero persistence and preventing dangling privileges.
```typescript
import { OpenFgaClient, ClientCheckRequest, TupleKey } from '@openfga/sdk';

interface VerifiedBreakGlassSession {
  userId: string;
  targetDocumentId: string;
  expiresAtMs: number;
  signatureValid: boolean;
}

export async function evaluateAccessWithBreakGlass(
  fgaClient: OpenFgaClient,
  session: VerifiedBreakGlassSession
): Promise<boolean> {
  // INVARIANT: Validate cryptographic proof and lifecycle horizon before injecting into memory
  const isSessionValid =
    session.signatureValid && session.expiresAtMs > Date.now();

  const contextualTuples: TupleKey[] = [];

  if (isSessionValid) {
    contextualTuples.push({
      user: `user:${session.userId}`,
      relation: 'emergency_responder',
      object: `document:${session.targetDocumentId}`
    });
  }

  // Ephemeral injection: evaluated strictly in-memory during this single Check query.
  // Zero persistence, zero replication delay, zero dangling privilege horizon.
  const checkPayload: ClientCheckRequest = {
    user: `user:${session.userId}`,
    relation: 'can_view',
    object: `document:${session.targetDocumentId}`,
    contextualTuples
  };

  const response = await fgaClient.check(checkPayload);
  return response.allowed ?? false;
}
```

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 Tuple Horizon Enforcement

OpenFGA Ephemeral Contextual Tuple Horizon Enforcement defines an industrial-grade behavioral standard for security engineering. Enforces zero-staleness dynamic authorization decisions by restricting high-churn, transient attributes (such as break-glass elevation, device posture, and session-scoped geo/IP conditions) to in-memory contextual tuples during OpenFGA Check operations. Prohibits persisting ephemeral authorization state to durable tuple storage, preventing tuple store bloat, cross-region replication lag, and window-of-exposure race conditions. 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 Volatile Session and Environmental State into Durable OpenFGA Tuples Instead of Contextual Check 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 Volatile Session and Environmental State into Durable OpenFGA Tuples Instead of Contextual Check 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 supply transient, high-churn state (e.g., IP boundary validations, device compliance flags, active break-glass tokens) via `contextual_tuples` directly in the OpenFGA `check` or `batchCheck` request.

Engineers MUST ALWAYS supply transient, high-churn state (e.g., IP boundary validations, device compliance flags, active break-glass tokens) via `contextual_tuples` directly in the OpenFGA `check` or `batchCheck` 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.
2

Engineers MUST NOT write ephemeral, session-bound, or short-lived relationship tuples to persistent OpenFGA storage using `writeTuples` or transactional tuple writes.

Engineers MUST NOT write ephemeral, session-bound, or short-lived relationship tuples to persistent OpenFGA storage using `writeTuples` or transactional tuple writes.

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 cryptographically verify and validate incoming ephemeral session attributes (signatures, timestamps, issuer) at the API edge prior to materializing them as contextual tuples.

Services MUST cryptographically verify and validate incoming ephemeral session attributes (signatures, timestamps, issuer) at the API edge prior to materializing them as 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.
4

Code SHOULD enforce strict structural schema validation on contextual tuples before dispatching the authorization query to prevent malformed tuple injection.

Code SHOULD enforce strict structural schema validation on contextual tuples before dispatching the authorization query to prevent malformed tuple 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

Components NEVER rely on out-of-band asynchronous cleanup jobs, database TTLs, or `try...finally` write/delete blocks to manage volatile relationship lifecycles in OpenFGA.

Components NEVER rely on out-of-band asynchronous cleanup jobs, database TTLs, or `try...finally` write/delete blocks to manage volatile relationship lifecycles in OpenFGA.

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 Tuple Horizon Enforcement critical for AI coding assistants?

Enforces zero-staleness dynamic authorization decisions by restricting high-churn, transient attributes (such as break-glass elevation, device posture, and session-scoped geo/IP conditions) to in-memory contextual tuples during OpenFGA Check operations. Prohibits persisting ephemeral authorization state to durable tuple storage, preventing tuple store bloat, cross-region replication lag, and window-of-exposure race conditions. 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 Volatile Session and Environmental State into Durable OpenFGA Tuples Instead of Contextual Check 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