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

OpenFGA 1.6 Contextual Tuple Temporal Invariant and Ephemeral Attribute Enforcement

Enforces that short-lived permissions, time-bound delegations, and dynamic environment context are evaluated ephemerally via OpenFGA 1.6 contextual tuples and CEL-conditioned context objects. Eliminates authorization staleness, race conditions, and tuple pollution caused by persisting ephemeral state directly into durable ReBAC storage.

Prohibited Anti-Pattern: Persisting Ephemeral Temporal State to Durable Tuple Storage or Omitting Temporal Context During Authorization Checks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA 1.6 Contextual Tuple Temporal Invariant and Ephemeral Attribute Enforcement - Enforces that short-lived permissions, time-bound delegations, and dynamic environment context are evaluated ephemerally via OpenFGA 1.6 contextual tuples and CEL-conditioned context objects. Eliminates authorization staleness, race conditions, and tuple pollution caused by persisting ephemeral state directly into durable ReBAC storage.
globs: src/**/auth*/**/*.{ts,tsx,js,jsx}, src/**/authorization/**/*.{ts,tsx,js,jsx}, src/**/*guard*.{ts,tsx}, src/**/*fga*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuple-temporal-invariant"
---

# OpenFGA 1.6 Contextual Tuple Temporal Invariant and Ephemeral Attribute Enforcement

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Persisting Ephemeral Temporal State to Durable Tuple Storage or Omitting Temporal Context During Authorization Checks

## System Constraints
You are a Principal Software Architect enforcing zero-trust authorization and strict ReBAC invariants using OpenFGA 1.6. You must mandate that dynamic, ephemeral, or temporal attributes (such as break-glass overrides, session expirations, IP CIDR constraints, and time-windowed delegations) are never persisted as static database tuples. Instead, they must be supplied at query time via `contextual_tuples` or injected through the `context` parameter for Google Common Expression Language (CEL) evaluation. Never allow durable writes for short-lived access lifecycles.

## Strict Guidelines
- Engineers MUST ALWAYS supply ephemeral permissions and break-glass grants as `contextual_tuples` in the OpenFGA `check` payload rather than writing to persistent storage.
- Engineers MUST NEVER write short-lived or time-sensitive tuples to persistent storage with scheduled asynchronous cleanup (e.g., cron jobs or TTL deletion workers), as this creates authorization staleness windows.
- Code MUST pass dynamic evaluation parameters (e.g., `current_time`, `user_ip`, `mfa_authenticated`) via the `context` argument to satisfy CEL conditions configured in the OpenFGA authorization model.
- Services MUST ensure contextual timestamps use a verified, authoritative system clock (ISO 8601 UTC) to prevent client-side time skew or replay attacks.
- Components NEVER execute OpenFGA checks on conditional relations without binding the mandatory context variables required by the model's CEL conditions.

## Bad vs Good Implementations
### Preventing Stale DB Tuples via Contextual Tuples and Temporal CEL Context

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Persisting temporary roles directly to persistent storage creates critical security vulnerabilities. If the process crashes or network partition occurs, the deletion tuple is never written, leaving the user with indefinite access. It also causes write-amplification and authorization staleness.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

export async function authorizeEmergencyAccess(
  fgaClient: OpenFgaClient,
  userId: string,
  documentId: string,
  validForMinutes: number
): Promise<boolean> {
  // VULNERABILITY: Writing ephemeral/time-bound state into durable database tuples.
  // This causes authorization staleness if cleanup jobs fail, crash, or lag.
  await fgaClient.write({
    writes: [
      {
        user: `user:${userId}`,
        relation: 'emergency_responder',
        object: `document:${documentId}`
      }
    ]
  });

  // Asynchronous cleanup is prone to race conditions and leaves windows of open access
  setTimeout(async () => {
    await fgaClient.write({
      deletes: [
        {
          user: `user:${userId}`,
          relation: 'emergency_responder',
          object: `document:${documentId}`
        }
      ]
    });
  }, validForMinutes * 60 * 1000);

  // Evaluation check fails to validate temporal bounds deterministically
  const { allowed } = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'can_view',
    object: `document:${documentId}`
  });

  return Boolean(allowed);
}
```

#### Production Standard (Correct)
> **Standard**: Leverages OpenFGA 1.6 contextual tuples and CEL conditions. The permission edge exists strictly in memory for the duration of the evaluation, guaranteed to expire immediately based on the temporal context without risk of database pollution or orphaned access.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

export async function authorizeEmergencyAccess(
  fgaClient: OpenFgaClient,
  userId: string,
  documentId: string,
  tokenExpiry: Date
): Promise<boolean> {
  const now = new Date();

  // INVARIANT: Ephemeral access is bound at evaluation time using contextual tuples
  // and dynamic CEL context. No state is written to the durable OpenFGA datastore.
  const { allowed } = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'can_view',
    object: `document:${documentId}`,
    // Ephemeral graph edges injected dynamically for this single query
    contextualTuples: [
      {
        user: `user:${userId}`,
        relation: 'temporary_viewer',
        object: `document:${documentId}`
      }
    ],
    // CEL context parameter evaluated against model condition (e.g. current_time < expires_at)
    context: {
      current_time: now.toISOString(),
      grant_expires_at: tokenExpiry.toISOString()
    }
  });

  return Boolean(allowed);
}
```

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 1.6 Contextual Tuple Temporal Invariant and Ephemeral Attribute Enforcement

OpenFGA 1.6 Contextual Tuple Temporal Invariant and Ephemeral Attribute Enforcement defines an industrial-grade behavioral standard for security engineering. Enforces that short-lived permissions, time-bound delegations, and dynamic environment context are evaluated ephemerally via OpenFGA 1.6 contextual tuples and CEL-conditioned context objects. Eliminates authorization staleness, race conditions, and tuple pollution caused by persisting ephemeral state directly into durable ReBAC storage. 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 Temporal State to Durable Tuple Storage or Omitting Temporal Context During Authorization Checks 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 Temporal State to Durable Tuple Storage or Omitting Temporal Context During Authorization ChecksCritical
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 ephemeral permissions and break-glass grants as `contextual_tuples` in the OpenFGA `check` payload rather than writing to persistent storage.

Engineers MUST ALWAYS supply ephemeral permissions and break-glass grants as `contextual_tuples` in the OpenFGA `check` payload rather than writing to persistent storage.

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 NEVER write short-lived or time-sensitive tuples to persistent storage with scheduled asynchronous cleanup (e.g., cron jobs or TTL deletion workers), as this creates authorization staleness windows.

Engineers MUST NEVER write short-lived or time-sensitive tuples to persistent storage with scheduled asynchronous cleanup (e.g., cron jobs or TTL deletion workers), as this creates authorization staleness windows.

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 dynamic evaluation parameters (e.g., `current_time`, `user_ip`, `mfa_authenticated`) via the `context` argument to satisfy CEL conditions configured in the OpenFGA authorization model.

Code MUST pass dynamic evaluation parameters (e.g., `current_time`, `user_ip`, `mfa_authenticated`) via the `context` argument to satisfy CEL conditions configured in the OpenFGA authorization model.

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 ensure contextual timestamps use a verified, authoritative system clock (ISO 8601 UTC) to prevent client-side time skew or replay attacks.

Services MUST ensure contextual timestamps use a verified, authoritative system clock (ISO 8601 UTC) to prevent client-side time skew or replay attacks.

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 OpenFGA checks on conditional relations without binding the mandatory context variables required by the model's CEL conditions.

Components NEVER execute OpenFGA checks on conditional relations without binding the mandatory context variables required by the model's CEL conditions.

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.6 Contextual Tuple Temporal Invariant and Ephemeral Attribute Enforcement critical for AI coding assistants?

Enforces that short-lived permissions, time-bound delegations, and dynamic environment context are evaluated ephemerally via OpenFGA 1.6 contextual tuples and CEL-conditioned context objects. Eliminates authorization staleness, race conditions, and tuple pollution caused by persisting ephemeral state directly into durable ReBAC storage. 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 Temporal State to Durable Tuple Storage or Omitting Temporal Context During Authorization Checks) 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