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

OpenFGA Ephemeral Tuples with Bounded TTL & Deterministic Pruning Invariant

Standardizes time-decaying authorization tuples for Just-In-Time (JIT) access to prevent privilege accumulation and eliminate graph traversal degradation over time. Enforces bounded Time-To-Live (TTL) conditions on transient relationship writes and mandates contextual timestamp evaluation during authorization checks.

Prohibited Anti-Pattern: Unbounded JIT Tuple Writes Without Condition Context or Expiration Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Ephemeral Tuples with Bounded TTL & Deterministic Pruning Invariant - Standardizes time-decaying authorization tuples for Just-In-Time (JIT) access to prevent privilege accumulation and eliminate graph traversal degradation over time. Enforces bounded Time-To-Live (TTL) conditions on transient relationship writes and mandates contextual timestamp evaluation during authorization checks.
globs: src/**/auth/**/*.{ts,js,go,py}, src/**/access/**/*.{ts,js,go,py}, src/**/openfga/**/*.{ts,js,go,py}, src/**/permissions/**/*.{ts,js,go,py}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-ephemeral-tuples-bounded-ttl-guardrail"
---

# OpenFGA Ephemeral Tuples with Bounded TTL & Deterministic Pruning Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded JIT Tuple Writes Without Condition Context or Expiration Boundaries

## System Constraints
You are a Principal Software Architect enforcing OpenFGA authorization invariants. All ephemeral and Just-In-Time (JIT) permissions MUST use bounded conditions evaluating temporal validity. Never allow naked, persistent relationship writes for temporary elevation. Ensure every transient tuple contains a validated condition schema matching a maximum upper-bound TTL and runtime check calls supply contextual current timestamps.

## Strict Guidelines
- Engineers MUST ALWAYS attach an OpenFGA condition (e.g., `non_expired_grant`) evaluating `current_time < expires_at` when writing ephemeral authorization tuples.
- Engineers MUST NOT permit arbitrary or unbounded TTL intervals; transient grants MUST strictly enforce an application-level MAX_TTL invariant (e.g., 4 to 8 hours max).
- Code MUST pass `current_time` as ISO 8601 UTC inside the authorization `check` contextual payload when evaluating relations bound to temporal conditions.
- Services MUST implement deterministic, asynchronous tombstoning/pruning jobs to physically delete expired conditional tuples and prevent OpenFGA sub-graph traversal latency degradation.
- Components NEVER rely on application-level delayed queues or manual cleanup scripts to revoke temporary privileges without backing conditional tuple constraints.

## Bad vs Good Implementations
### JIT Grant Tuple Injection and Contextual Check

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Writing an unconditional relationship tuple for transient elevation creates severe security exposure. If the host restarts or crashes before the timeout triggers, the user retains administrative access permanently. Furthermore, accumulated dead tuples degrade graph traversal performance during check evaluations.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

export async function grantBreakglassAccess(
  fga: OpenFgaClient,
  userId: string,
  systemId: string
): Promise<void> {
  // VULNERABILITY: Static tuple written without condition or bounded TTL.
  // Relies on a best-effort async timeout that will fail if the process terminates,
  // leading to permanent privilege escalation and graph bloat.
  await fga.write({
    writes: [{
      user: `user:${userId}`,
      relation: 'breakglass_operator',
      object: `system:${systemId}`
    }]
  });

  setTimeout(async () => {
    await fga.write({
      deletes: [{
        user: `user:${userId}`,
        relation: 'breakglass_operator',
        object: `system:${systemId}`
      }]
    });
  }, 4 * 60 * 60 * 1000); // Unsafe in-memory timer
}
```

#### Production Standard (Correct)
> **Standard**: Attaches a validated OpenFGA condition containing a strictly bounded expiration timestamp. Authorization checks pass the runtime `current_time` in the evaluation context, immediately invalidating expired grants cryptographically across all distributed nodes regardless of whether a background deletion job has completed.
```typescript
import { OpenFgaClient, ClientWriteRequest } from '@openfga/sdk';

const MAX_JIT_TTL_SECONDS = 4 * 60 * 60; // Invariant: Max 4 hours
const CONDITION_NAME = 'non_expired_grant';

export async function grantBreakglassAccess(
  fga: OpenFgaClient,
  userId: string,
  systemId: string,
  durationSeconds: number
): Promise<void> {
  if (durationSeconds <= 0 || durationSeconds > MAX_JIT_TTL_SECONDS) {
    throw new Error(`Duration exceeds maximum allowable TTL of ${MAX_JIT_TTL_SECONDS}s`);
  }

  const now = new Date();
  const expiresAt = new Date(now.getTime() + durationSeconds * 1000).toISOString();

  const request: ClientWriteRequest = {
    writes: [{
      user: `user:${userId}`,
      relation: 'breakglass_operator',
      object: `system:${systemId}`,
      condition: {
        name: CONDITION_NAME,
        context: { expires_at: expiresAt }
      }
    }]
  };

  await fga.write(request);
}

export async function verifyBreakglassAccess(
  fga: OpenFgaClient,
  userId: string,
  systemId: string
): Promise<boolean> {
  const response = await fga.check({
    user: `user:${userId}`,
    relation: 'breakglass_operator',
    object: `system:${systemId}`,
    context: {
      current_time: new Date().toISOString()
    }
  });

  return response.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 Tuples with Bounded TTL & Deterministic Pruning Invariant

OpenFGA Ephemeral Tuples with Bounded TTL & Deterministic Pruning Invariant defines an industrial-grade behavioral standard for security engineering. Standardizes time-decaying authorization tuples for Just-In-Time (JIT) access to prevent privilege accumulation and eliminate graph traversal degradation over time. Enforces bounded Time-To-Live (TTL) conditions on transient relationship writes and mandates contextual timestamp evaluation during authorization checks. 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: Unbounded JIT Tuple Writes Without Condition Context or Expiration Boundaries 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 DriftUnbounded JIT Tuple Writes Without Condition Context or Expiration BoundariesCritical
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 an OpenFGA condition (e.g., `non_expired_grant`) evaluating `current_time < expires_at` when writing ephemeral authorization tuples.

Engineers MUST ALWAYS attach an OpenFGA condition (e.g., `non_expired_grant`) evaluating `current_time < expires_at` when writing ephemeral authorization 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 permit arbitrary or unbounded TTL intervals

Engineers MUST NOT permit arbitrary or unbounded TTL intervals; transient grants MUST strictly enforce an application-level MAX_TTL invariant (e.g., 4 to 8 hours max).

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 `current_time` as ISO 8601 UTC inside the authorization `check` contextual payload when evaluating relations bound to temporal conditions.

Code MUST pass `current_time` as ISO 8601 UTC inside the authorization `check` contextual payload when evaluating relations bound to temporal 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.
4

Services MUST implement deterministic, asynchronous tombstoning/pruning jobs to physically delete expired conditional tuples and prevent OpenFGA sub-graph traversal latency degradation.

Services MUST implement deterministic, asynchronous tombstoning/pruning jobs to physically delete expired conditional tuples and prevent OpenFGA sub-graph traversal latency degradation.

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 application-level delayed queues or manual cleanup scripts to revoke temporary privileges without backing conditional tuple constraints.

Components NEVER rely on application-level delayed queues or manual cleanup scripts to revoke temporary privileges without backing conditional tuple constraints.

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 Tuples with Bounded TTL & Deterministic Pruning Invariant critical for AI coding assistants?

Standardizes time-decaying authorization tuples for Just-In-Time (JIT) access to prevent privilege accumulation and eliminate graph traversal degradation over time. Enforces bounded Time-To-Live (TTL) conditions on transient relationship writes and mandates contextual timestamp evaluation during authorization checks. 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 (Unbounded JIT Tuple Writes Without Condition Context or Expiration Boundaries) 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