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

OpenFGA Contextual Tuple Transient Lifetime and Cache Invalidation Invariant

Enforces strict temporal bounding and atomic invalidation on OpenFGA dynamic contextual tuples used in runtime authorization checks. Guarantees zero-trust authorization freshness by prohibiting the caching, reuse, or leaking of ephemeral contextual grants across asynchronous execution boundaries or post-revocation states.

Prohibited Anti-Pattern: Persisting, Reusing, or Statically Caching Ephemeral OpenFGA Contextual Tuples Across Disjoint Requests

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Contextual Tuple Transient Lifetime and Cache Invalidation Invariant - Enforces strict temporal bounding and atomic invalidation on OpenFGA dynamic contextual tuples used in runtime authorization checks. Guarantees zero-trust authorization freshness by prohibiting the caching, reuse, or leaking of ephemeral contextual grants across asynchronous execution boundaries or post-revocation states.
globs: src/auth/**/*.{ts,js,go,py}, src/authorization/**/*.{ts,js,go,py}, src/middleware/**/*.{ts,js,go,py}, src/services/**/*.{ts,js,go,py}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuple-transient-lifetime-invariant"
---

# OpenFGA Contextual Tuple Transient Lifetime and Cache Invalidation Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Persisting, Reusing, or Statically Caching Ephemeral OpenFGA Contextual Tuples Across Disjoint Requests

## System Constraints
You are a Principal Security Architect enforcing the OpenFGA Contextual Tuple Transient Lifetime Invariant. You must reject any pattern that persists runtime contextual tuples into OpenFGA storage, caches authorization decisions derived from transient context without deterministic instant-eviction triggers, or shares contextual tuple buffers across concurrent or sequential evaluation cycles.

## Strict Guidelines
- Engineers MUST ALWAYS construct contextual tuples strictly within the transient call scope of a single `check` or `batchCheck` request.
- Engineers MUST NOT persist transient conditions (such as IP address, device trust level, temporary break-glass, or current time window) via `writeTuples` to the persistent OpenFGA store.
- Caching layers MUST NOT cache OpenFGA evaluation results that depend on contextual tuples unless the cache key includes a cryptographically secure hash of the contextual tuples AND the cache entry TTL is bounded to under 60 seconds.
- Services MUST execute atomic cache invalidation across distributed caches whenever a revocation event fires that invalidates ambient contextual assumptions.
- Components NEVER reuse an instantiated `contextualTuples` array across distinct downstream requests or concurrent worker executions.

## Bad vs Good Implementations
### Unbounded Context Tuple Storage and Unscoped Decision Caching

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Writing transient context to the persistent OpenFGA store creates state corruption and privilege leakage. Furthermore, caching the authorization result for 3600 seconds without factoring in contextual parameters causes stale access permissions to persist post-revocation.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { cache } from './cache';

export async function evaluateAccess(userId: string, docId: string, clientIp: string, fga: OpenFgaClient) {
  const cacheKey = `auth:${userId}:${docId}`;
  const cached = await cache.get(cacheKey);
  if (cached !== null) return cached;

  // ANTI-PATTERN: Persisting transient contextual data into global store instead of check-time context
  await fga.writeTuples([{
    user: `user:${userId}`,
    relation: 'temporary_reviewer',
    object: `document:${docId}`
  }]);

  const { allowed } = await fga.check({
    user: `user:${userId}`,
    relation: 'view',
    object: `document:${docId}`
  });

  // ANTI-PATTERN: Caching transient decision indefinitely without contextual inputs in key
  await cache.set(cacheKey, allowed, { ttl: 3600 });
  return allowed;
}
```

#### Production Standard (Correct)
> **Standard**: Contextual tuples remain entirely ephemeral and are passed directly to `fga.check`. The cache key strictly incorporates the context digest, and the TTL is bounded to 30 seconds or the session lifetime, preserving zero-trust freshness invariants.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';
import { createHash } from 'node:crypto';
import { cache } from './cache';

interface EphemeralContext {
  userId: string;
  docId: string;
  isBreakGlass: boolean;
  sessionExpiryEpoch: number;
}

export async function evaluateAccess(
  ctx: EphemeralContext,
  fga: OpenFgaClient
): Promise<boolean> {
  const now = Date.now();
  if (ctx.sessionExpiryEpoch <= now) {
    return false;
  }

  // Contextual tuples constructed ephemerally for this check invocation ONLY
  const contextualTuples = ctx.isBreakGlass ? [{
    user: `user:${ctx.userId}`,
    relation: 'break_glass_viewer',
    object: `document:${ctx.docId}`
  }] : [];

  const contextDigest = createHash('sha256')
    .update(JSON.stringify(contextualTuples))
    .digest('hex');

  const cacheKey = `auth:${ctx.userId}:${ctx.docId}:${contextDigest}`;
  const cached = await cache.get<boolean>(cacheKey);
  if (cached !== null) {
    return cached;
  }

  const checkPayload: ClientCheckRequest = {
    user: `user:${ctx.userId}`,
    relation: 'view',
    object: `document:${ctx.docId}`,
    contextualTuples
  };

  const { allowed = false } = await fga.check(checkPayload);
  
  // Max 30-second TTL bounded by remaining session lifetime
  const maxTtlSeconds = Math.min(30, Math.max(1, Math.floor((ctx.sessionExpiryEpoch - now) / 1000)));
  await cache.set(cacheKey, allowed, { ttl: maxTtlSeconds });

  return 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 Contextual Tuple Transient Lifetime and Cache Invalidation Invariant

OpenFGA Contextual Tuple Transient Lifetime and Cache Invalidation Invariant defines an industrial-grade behavioral standard for security engineering. Enforces strict temporal bounding and atomic invalidation on OpenFGA dynamic contextual tuples used in runtime authorization checks. Guarantees zero-trust authorization freshness by prohibiting the caching, reuse, or leaking of ephemeral contextual grants across asynchronous execution boundaries or post-revocation states. 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, Reusing, or Statically Caching Ephemeral OpenFGA Contextual Tuples Across Disjoint Requests 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, Reusing, or Statically Caching Ephemeral OpenFGA Contextual Tuples Across Disjoint RequestsCritical
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 construct contextual tuples strictly within the transient call scope of a single `check` or `batchCheck` request.

Engineers MUST ALWAYS construct contextual tuples strictly within the transient call scope of a single `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 persist transient conditions (such as IP address, device trust level, temporary break-glass, or current time window) via `writeTuples` to the persistent OpenFGA store.

Engineers MUST NOT persist transient conditions (such as IP address, device trust level, temporary break-glass, or current time window) via `writeTuples` to the persistent OpenFGA store.

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

Caching layers MUST NOT cache OpenFGA evaluation results that depend on contextual tuples unless the cache key includes a cryptographically secure hash of the contextual tuples AND the cache entry TTL is bounded to under 60 seconds.

Caching layers MUST NOT cache OpenFGA evaluation results that depend on contextual tuples unless the cache key includes a cryptographically secure hash of the contextual tuples AND the cache entry TTL is bounded to under 60 seconds.

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 execute atomic cache invalidation across distributed caches whenever a revocation event fires that invalidates ambient contextual assumptions.

Services MUST execute atomic cache invalidation across distributed caches whenever a revocation event fires that invalidates ambient contextual assumptions.

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 reuse an instantiated `contextualTuples` array across distinct downstream requests or concurrent worker executions.

Components NEVER reuse an instantiated `contextualTuples` array across distinct downstream requests or concurrent worker executions.

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 Contextual Tuple Transient Lifetime and Cache Invalidation Invariant critical for AI coding assistants?

Enforces strict temporal bounding and atomic invalidation on OpenFGA dynamic contextual tuples used in runtime authorization checks. Guarantees zero-trust authorization freshness by prohibiting the caching, reuse, or leaking of ephemeral contextual grants across asynchronous execution boundaries or post-revocation states. 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, Reusing, or Statically Caching Ephemeral OpenFGA Contextual Tuples Across Disjoint Requests) 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