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

OpenFGA Temporal Grant Lifecycle and Distributed ReBAC Eviction Guardrail

Guarantees deterministic authorization state synchronization across distributed OpenFGA check nodes during short-lived and temporal relationship evaluations. Mandates the use of CEL-based conditional tuples with server-enforced monotonic timestamps, dynamic contextual tuple evaluation, and Zanzibar consistency tokens to eliminate stale authorization hits post-expiration.

Prohibited Anti-Pattern: Relying on asynchronous database writes/deletions and default eventual consistency for short-lived access grants, causing distributed cache poisoning and authorization bypass.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Temporal Grant Lifecycle and Distributed ReBAC Eviction Guardrail - Guarantees deterministic authorization state synchronization across distributed OpenFGA check nodes during short-lived and temporal relationship evaluations. Mandates the use of CEL-based conditional tuples with server-enforced monotonic timestamps, dynamic contextual tuple evaluation, and Zanzibar consistency tokens to eliminate stale authorization hits post-expiration.
globs: src/auth/**/*.{ts,tsx}, src/security/**/*.{ts,tsx}, src/services/auth/**/*.{ts,tsx}, src/middleware/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-temporal-grant-rebac-eviction-standard"
---

# OpenFGA Temporal Grant Lifecycle and Distributed ReBAC Eviction Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Relying on asynchronous database writes/deletions and default eventual consistency for short-lived access grants, causing distributed cache poisoning and authorization bypass.

## System Constraints
You are a Principal Software Architect enforcing the OpenFGA Temporal Grant and ReBAC Eviction Standard. You must mandate that temporal and ephemeral permissions never rely on asynchronous store writes followed by scheduled deletions. Enforce strict OpenFGA schema 1.2 condition models (CEL), ensure timestamps are derived from synchronized monotonic time or contextual tuples, and mandate high-consistency tokens across distributed check nodes to prevent authorization state divergence.

## Strict Guidelines
- Engineers MUST ALWAYS model time-bounded access using OpenFGA conditional relationship tuples (schema 1.2 with CEL conditions such as `current_time < expires_at`) or via per-request `contextualTuples`, rather than persisting tuples and relying on async deletion cron jobs.
- Engineers MUST NOT evaluate authorization checks for temporal grants with default eventual consistency; `consistency: ConsistencyPreference.HIGHER_CONSISTENCY` MUST be specified when evaluating sensitive or short-lived grants.
- Services MUST supply a trusted, server-derived monotonic timestamp in the check context parameter (`context: { current_time: new Date().toISOString() }`) to eliminate client clock-skew exploits during CEL evaluation.
- Engineers MUST NEVER cache raw `fgaClient.check` positive results in local application-tier caches (e.g., Redis, in-memory Map) without binding the cache TTL to the exact remaining grant duration of the conditional tuple.
- Components NEVER treat stored tuple deletion as an atomic cache eviction event across distributed check nodes without invalidating the read-token/consistency barrier.

## Bad vs Good Implementations
### Unsynchronized Persisted Ephemeral Tuples with Eventual Consistency (Vulnerable to Stale Grants)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Persisting an unconditioned tuple into OpenFGA and scheduling an out-of-band deletion causes distributed check node caches to retain the affirmative decision past the intended TTL. Furthermore, the check evaluation does not mandate higher consistency or inject trusted evaluation timestamps.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

// ANTI-PATTERN: Writes an unconditioned tuple and relies on setTimeout/cron for eviction.
// Distributed check nodes cache the positive allow decision; deletion does not propagate instantly.
export async function grantBreakGlassAccess(userId: string, incidentId: string, ttlMs: number) {
  await fgaClient.write({
    writes: [{
      user: `user:${userId}`,
      relation: 'responder',
      object: `incident:${incidentId}`
    }]
  });

  setTimeout(async () => {
    // Async deletion leaves stale authorization cache across distributed FGA nodes
    await fgaClient.write({
      deletes: [{
        user: `user:${userId}`,
        relation: 'responder',
        object: `incident:${incidentId}`
      }]
    });
  }, ttlMs);
}

export async function checkAccess(userId: string, incidentId: string): Promise<boolean> {
  // Default eventual consistency serves stale cached 'true' responses post-TTL
  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'responder',
    object: `incident:${incidentId}`
  });
  return response.allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: Leverages OpenFGA 1.2 conditional tuples with CEL expressions. The authorization decision deterministically evicts expired grants on distributed check nodes by supplying a trusted server timestamp in the check context and requesting HigherConsistency.
```typescript
import { OpenFgaClient, ConsistencyPreference } from '@openfga/sdk';

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

// PRODUCTION FIX: Persist conditional tuple bound to CEL condition 'is_not_expired'
// Evaluation requires server-controlled UTC monotonic timestamp and HIGHER_CONSISTENCY flag.
export async function grantBreakGlassAccess(userId: string, incidentId: string, durationMinutes: number) {
  const expiresAt = new Date(Date.now() + durationMinutes * 60 * 1000).toISOString();

  await fgaClient.write({
    writes: [{
      user: `user:${userId}`,
      relation: 'responder',
      object: `incident:${incidentId}`,
      condition: {
        name: 'is_not_expired',
        context: { expires_at: expiresAt }
      }
    }]
  });
}

export async function checkAccess(userId: string, incidentId: string): Promise<boolean> {
  const nowIso = new Date().toISOString();

  const response = await fgaClient.check(
    {
      user: `user:${userId}`,
      relation: 'responder',
      object: `incident:${incidentId}`,
      context: {
        current_time: nowIso
      }
    },
    {
      // Evicts stale node-level caches and guarantees deterministic temporal evaluation
      consistency: ConsistencyPreference.HigherConsistency
    }
  );

  return Boolean(response.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 Temporal Grant Lifecycle and Distributed ReBAC Eviction Guardrail

OpenFGA Temporal Grant Lifecycle and Distributed ReBAC Eviction Guardrail defines an industrial-grade behavioral standard for security engineering. Guarantees deterministic authorization state synchronization across distributed OpenFGA check nodes during short-lived and temporal relationship evaluations. Mandates the use of CEL-based conditional tuples with server-enforced monotonic timestamps, dynamic contextual tuple evaluation, and Zanzibar consistency tokens to eliminate stale authorization hits post-expiration. 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: Relying on asynchronous database writes/deletions and default eventual consistency for short-lived access grants, causing distributed cache poisoning and authorization bypass. 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 DriftRelying on asynchronous database writes/deletions and default eventual consistency for short-lived access grants, causing distributed cache poisoning and authorization bypass.Critical
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 model time-bounded access using OpenFGA conditional relationship tuples (schema 1.2 with CEL conditions such as `current_time < expires_at`) or via per-request `contextualTuples`, rather than persisting tuples and relying on async deletion cron jobs.

Engineers MUST ALWAYS model time-bounded access using OpenFGA conditional relationship tuples (schema 1.2 with CEL conditions such as `current_time < expires_at`) or via per-request `contextualTuples`, rather than persisting tuples and relying on async deletion cron jobs.

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 evaluate authorization checks for temporal grants with default eventual consistency

Engineers MUST NOT evaluate authorization checks for temporal grants with default eventual consistency; `consistency: ConsistencyPreference.HIGHER_CONSISTENCY` MUST be specified when evaluating sensitive or short-lived grants.

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 supply a trusted, server-derived monotonic timestamp in the check context parameter (`context

Services MUST supply a trusted, server-derived monotonic timestamp in the check context parameter (`context: { current_time: new Date().toISOString() }`) to eliminate client clock-skew exploits during CEL evaluation.

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

Engineers MUST NEVER cache raw `fgaClient.check` positive results in local application-tier caches (e.g., Redis, in-memory Map) without binding the cache TTL to the exact remaining grant duration of the conditional tuple.

Engineers MUST NEVER cache raw `fgaClient.check` positive results in local application-tier caches (e.g., Redis, in-memory Map) without binding the cache TTL to the exact remaining grant duration of the conditional tuple.

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 treat stored tuple deletion as an atomic cache eviction event across distributed check nodes without invalidating the read-token/consistency barrier.

Components NEVER treat stored tuple deletion as an atomic cache eviction event across distributed check nodes without invalidating the read-token/consistency barrier.

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 Temporal Grant Lifecycle and Distributed ReBAC Eviction Guardrail critical for AI coding assistants?

Guarantees deterministic authorization state synchronization across distributed OpenFGA check nodes during short-lived and temporal relationship evaluations. Mandates the use of CEL-based conditional tuples with server-enforced monotonic timestamps, dynamic contextual tuple evaluation, and Zanzibar consistency tokens to eliminate stale authorization hits post-expiration. 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 (Relying on asynchronous database writes/deletions and default eventual consistency for short-lived access grants, causing distributed cache poisoning and authorization bypass.) 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