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

OpenFGA Temporal Relationship Tuple Lifecycle and Eviction Invariant

Enforces strict CEL conditional time-to-live (TTL) validation and automated tombstone eviction on time-bound OpenFGA authorization tuples. Eliminates privilege creep and unbounded graph degradation by mandating server-authoritative context evaluation at check time alongside active background compaction.

Prohibited Anti-Pattern: Dangling Temporal Tuples and Context-Free Authorization Checks Enabling Privilege Creep

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Temporal Relationship Tuple Lifecycle and Eviction Invariant - Enforces strict CEL conditional time-to-live (TTL) validation and automated tombstone eviction on time-bound OpenFGA authorization tuples. Eliminates privilege creep and unbounded graph degradation by mandating server-authoritative context evaluation at check time alongside active background compaction.
globs: src/auth/**/*.{ts,tsx}, src/services/fga/**/*.{ts,tsx}, src/jobs/**/*.{ts,tsx}, src/lib/fga/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-temporal-tuple-lifecycle-guardrail"
---

# OpenFGA Temporal Relationship Tuple Lifecycle and Eviction Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Dangling Temporal Tuples and Context-Free Authorization Checks Enabling Privilege Creep

## System Constraints
You are a Principal Security Architect specializing in Fine-Grained Authorization (FGA) and Zanzibar-style ReBAC systems. Mandate strict temporal relationship tuple lifecycle invariants across all OpenFGA operations. Prohibit unconditional writes for ephemeral permissions, enforce server-authoritative contextual evaluations in check calls, and require deterministic tombstone pruning workers.

## Strict Guidelines
- Engineers MUST ALWAYS attach a CEL-backed conditional definition (e.g., `in_grant_window`) with explicit `grant_expires_at` parameters when creating temporary or time-bounded relationship tuples.
- Engineers MUST NOT issue OpenFGA `check` or `expand` calls on temporal relationship models without passing a validated, server-authoritative `current_time` ISO-8601 timestamp in the contextual payload.
- Code SHOULD enforce monotonic clock synchronization (UTC) for contextual payload evaluation to prevent race conditions during daylight savings or client-side NTP drift.
- Services MUST implement an automated background eviction engine that systematically paginates over conditional relationship tuples, evaluates expirations, and executes batched deletions (`writeTuples` with `deletes`).
- Components NEVER trust client-supplied expiration timestamps or assume OpenFGA natively purges expired conditional tuples from storage without explicit deletion transactions.

## Bad vs Good Implementations
### Temporal Tuple Creation and Contextual Check Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Tuples written without an OpenFGA condition persist indefinitely. Calling check without providing contextual timestamp parameters bypasses temporal boundary logic, allowing privilege creep if external background cleanup fails.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

export async function grantTemporaryAccess(
  fgaClient: OpenFgaClient,
  userId: string,
  role: string,
  targetResource: string,
  ttlHours: number
): Promise<void> {
  // VULNERABILITY: Writing unconditional tuple with external TTL metadata
  // OpenFGA graph retains this edge indefinitely unless manual deletion occurs.
  await fgaClient.writeTuples([{
    user: `user:${userId}`,
    relation: role,
    object: targetResource,
  }]);
}

export async function checkAccess(
  fgaClient: OpenFgaClient,
  userId: string,
  targetResource: string
): Promise<boolean> {
  // VULNERABILITY: Context-free check against a temporal graph
  // Returns true even after intended temporal grant expiration window.
  const { allowed } = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'viewer',
    object: targetResource,
  });
  return allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: Binds authorization grants to the `non_expired_grant` CEL condition and forces server-side UTC timestamp injection on every `check` call, ensuring expired grants immediately deny access even before compaction.
```typescript
import { OpenFgaClient, ClientWriteRequest } from '@openfga/sdk';

const TEMPORAL_CONDITION = 'non_expired_grant';

export async function grantTemporaryAccess(
  fgaClient: OpenFgaClient,
  userId: string,
  role: string,
  targetResource: string,
  ttlSeconds: number
): Promise<void> {
  const expiresAt = new Date(Date.now() + ttlSeconds * 1000).toISOString();

  // INVARIANT: Ephemeral tuples must be bound to a CEL-validated condition
  const writeRequest: ClientWriteRequest = {
    writes: [{
      user: `user:${userId}`,
      relation: role,
      object: targetResource,
      condition: {
        name: TEMPORAL_CONDITION,
        context: {
          grant_expires_at: expiresAt,
        },
      },
    }],
  };

  await fgaClient.write(writeRequest);
}

export async function checkAccess(
  fgaClient: OpenFgaClient,
  userId: string,
  targetResource: string
): Promise<boolean> {
  // INVARIANT: Server-authoritative UTC clock injected into contextual payload
  const serverTimeUtc = new Date().toISOString();

  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'viewer',
    object: targetResource,
    context: {
      current_time: serverTimeUtc,
    },
  });

  return response.allowed ?? false;
}
```

### Deterministic Background Tombstone Eviction Worker

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Ignoring physical deletion of expired tuples creates unbounded database bloat, degrades graph resolution latency, and increases the attack surface if condition logic is accidentally mutated.
```typescript
// ANTI-PATTERN: Relying solely on CEL condition at check-time without database compaction.
// Graph stores millions of expired dead tuples, degrading traversal and index performance.
export async function runPruningJob(): Promise<void> {
  console.warn('CEL checks handle expiration; skipping tuple deletion.');
}
```

#### Production Standard (Correct)
> **Standard**: Scans and paginates through conditional tuples, compares condition context against current time, and issues atomic batch delete commands to compact storage and eliminate zombie graph nodes.
```typescript
import { OpenFgaClient, TupleKey } from '@openfga/sdk';

const BATCH_SIZE = 100;

export async function evictExpiredTuples(
  fgaClient: OpenFgaClient
): Promise<number> {
  const now = new Date();
  let continuationToken: string | undefined;
  let totalEvicted = 0;

  do {
    const response = await fgaClient.read({
      continuation_token: continuationToken,
      page_size: BATCH_SIZE,
    });

    continuationToken = response.continuation_token;
    const tuples = response.tuples ?? [];
    const expiredTuples: TupleKey[] = [];

    for (const tuple of tuples) {
      const condition = tuple.key.condition;
      if (condition?.name === 'non_expired_grant' && condition.context?.grant_expires_at) {
        const expiresAt = new Date(condition.context.grant_expires_at as string);
        if (now >= expiresAt) {
          expiredTuples.push({
            user: tuple.key.user,
            relation: tuple.key.relation,
            object: tuple.key.object,
          });
        }
      }
    }

    if (expiredTuples.length > 0) {
      await fgaClient.write({
        deletes: expiredTuples,
      });
      totalEvicted += expiredTuples.length;
    }
  } while (continuationToken);

  return totalEvicted;
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA Temporal Relationship Tuple Lifecycle and Eviction Invariant

OpenFGA Temporal Relationship Tuple Lifecycle and Eviction Invariant defines an industrial-grade behavioral standard for security engineering. Enforces strict CEL conditional time-to-live (TTL) validation and automated tombstone eviction on time-bound OpenFGA authorization tuples. Eliminates privilege creep and unbounded graph degradation by mandating server-authoritative context evaluation at check time alongside active background compaction. 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: Dangling Temporal Tuples and Context-Free Authorization Checks Enabling Privilege Creep 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 DriftDangling Temporal Tuples and Context-Free Authorization Checks Enabling Privilege CreepCritical
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 attach a CEL-backed conditional definition (e.g., `in_grant_window`) with explicit `grant_expires_at` parameters when creating temporary or time-bounded relationship tuples.

Engineers MUST ALWAYS attach a CEL-backed conditional definition (e.g., `in_grant_window`) with explicit `grant_expires_at` parameters when creating temporary or time-bounded relationship 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.
2

Engineers MUST NOT issue OpenFGA `check` or `expand` calls on temporal relationship models without passing a validated, server-authoritative `current_time` ISO-8601 timestamp in the contextual payload.

Engineers MUST NOT issue OpenFGA `check` or `expand` calls on temporal relationship models without passing a validated, server-authoritative `current_time` ISO-8601 timestamp in the contextual payload.

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 SHOULD enforce monotonic clock synchronization (UTC) for contextual payload evaluation to prevent race conditions during daylight savings or client-side NTP drift.

Code SHOULD enforce monotonic clock synchronization (UTC) for contextual payload evaluation to prevent race conditions during daylight savings or client-side NTP drift.

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 implement an automated background eviction engine that systematically paginates over conditional relationship tuples, evaluates expirations, and executes batched deletions (`writeTuples` with `deletes`).

Services MUST implement an automated background eviction engine that systematically paginates over conditional relationship tuples, evaluates expirations, and executes batched deletions (`writeTuples` with `deletes`).

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 trust client-supplied expiration timestamps or assume OpenFGA natively purges expired conditional tuples from storage without explicit deletion transactions.

Components NEVER trust client-supplied expiration timestamps or assume OpenFGA natively purges expired conditional tuples from storage without explicit deletion transactions.

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 Relationship Tuple Lifecycle and Eviction Invariant critical for AI coding assistants?

Enforces strict CEL conditional time-to-live (TTL) validation and automated tombstone eviction on time-bound OpenFGA authorization tuples. Eliminates privilege creep and unbounded graph degradation by mandating server-authoritative context evaluation at check time alongside active background compaction. 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 (Dangling Temporal Tuples and Context-Free Authorization Checks Enabling Privilege Creep) 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