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

OpenFGA Ephemeral Contextual Tuples Anti-Pollution Guardrail

Enforces that temporal, session-bound, and dynamic authorization assertions are supplied strictly as contextual tuples during OpenFGA evaluation queries rather than persisted to the tuple store. This prevents high-velocity database bloat, changelog table exhaustion, and critical privilege-retention vulnerabilities caused by orphaned revocation writes.

Prohibited Anti-Pattern: Persisting Transient Grants to the Tuple Store Instead of Utilizing Ephemeral Contextual Tuples

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Ephemeral Contextual Tuples Anti-Pollution Guardrail - Enforces that temporal, session-bound, and dynamic authorization assertions are supplied strictly as contextual tuples during OpenFGA evaluation queries rather than persisted to the tuple store. This prevents high-velocity database bloat, changelog table exhaustion, and critical privilege-retention vulnerabilities caused by orphaned revocation writes.
globs: src/**/*.{ts,tsx}, services/**/*.{ts,tsx}, lib/auth/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-dynamic-contextual-tuples-anti-pollution-invariant"
---

# OpenFGA Ephemeral Contextual Tuples Anti-Pollution Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Persisting Transient Grants to the Tuple Store Instead of Utilizing Ephemeral Contextual Tuples

## System Constraints
You are a Principal Security Architect enforcing the OpenFGA Dynamic Contextual Tuples Anti-Pollution Invariant. Under no circumstances may code persist transient, time-limited, step-up authentication, or request-scoped access relationships directly into persistent OpenFGA storage stores. Ensure all temporal grants, location verification, or short-lived operational states are modeled as dynamic contextualTuples passed alongside Check/Expand/ListObjects invocations.

## Strict Guidelines
- Engineers MUST NEVER invoke `fgaClient.write()` to record temporal, step-up (MFA), break-glass, or session-scoped authorization grants.
- Engineers MUST supply ephemeral access assertions exclusively via the `contextualTuples` array in `fgaClient.check()`, `fgaClient.listObjects()`, or `fgaClient.expand()` payloads.
- Code MUST validate transient claims (e.g., JWT signatures, step-up MFA validity, break-glass session expirations) in the application or API gateway layer prior to injecting them into contextual tuples.
- Services MUST treat the OpenFGA persistent relational store as immutable with respect to high-velocity transient request telemetry, avoiding audit log and changelog exhaustion.
- Components NEVER rely on background cleanup workers, Redis TTL synchronization, or scheduled deletes to clean up temporary access grants written to OpenFGA persistence stores.

## Bad vs Good Implementations
### Handling Temporary Break-Glass Support Access in OpenFGA

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Writing transient permissions directly to the storage store pollutes changelogs, triggers unnecessary database I/O, and introduces critical security vulnerabilities if asynchronous deletion hooks fail or crash.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

export async function grantTemporarySupportAccess(
  fgaClient: OpenFgaClient,
  userId: string,
  tenantId: string,
  durationMs: number
): Promise<boolean> {
  // ANTI-PATTERN: Persisting transient grant directly to OpenFGA store.
  // Generates permanent write changelogs, database index bloat, and runs the risk
  // of permanent privilege creep if the node crashes before the deletion timeout fires.
  await fgaClient.write({
    writes: [{
      user: `user:${userId}`,
      relation: 'support_operator',
      object: `tenant:${tenantId}`
    }]
  });

  setTimeout(async () => {
    try {
      await fgaClient.write({
        deletes: [{
          user: `user:${userId}`,
          relation: 'support_operator',
          object: `tenant:${tenantId}`
        }]
      });
    } catch (err) {
      console.error('Failed to revoke temporal privilege! User retained elevated access.', err);
    }
  }, durationMs);

  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'viewer',
    object: `tenant:${tenantId}`
  });

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

#### Production Standard (Correct)
> **Standard**: Transient access is verified against the application session state and passed purely as an evaluation-time contextual tuple. The persistent OpenFGA store remains unpolluted, deterministic, and free of dangling privilege risks.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

interface VerifiedSupportSession {
  userId: string;
  tenantId: string;
  expiresAtEpochMs: number;
}

export async function checkSupportAccessWithContext(
  fgaClient: OpenFgaClient,
  session: VerifiedSupportSession
): Promise<boolean> {
  const now = Date.now();
  const isSessionValid = session.expiresAtEpochMs > now;

  // INVARIANT: Temporal authorization assertions remain ephemeral and are passed
  // exclusively via contextualTuples during evaluation. Zero persistence footprint.
  const contextualTuples = isSessionValid
    ? [
        {
          user: `user:${session.userId}`,
          relation: 'support_operator',
          object: `tenant:${session.tenantId}`
        }
      ]
    : [];

  const checkPayload: ClientCheckRequest = {
    user: `user:${session.userId}`,
    relation: 'viewer',
    object: `tenant:${session.tenantId}`,
    contextualTuples
  };

  const response = await fgaClient.check(checkPayload);
  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 Contextual Tuples Anti-Pollution Guardrail

OpenFGA Ephemeral Contextual Tuples Anti-Pollution Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces that temporal, session-bound, and dynamic authorization assertions are supplied strictly as contextual tuples during OpenFGA evaluation queries rather than persisted to the tuple store. This prevents high-velocity database bloat, changelog table exhaustion, and critical privilege-retention vulnerabilities caused by orphaned revocation writes. 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 Transient Grants to the Tuple Store Instead of Utilizing Ephemeral Contextual Tuples 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 Transient Grants to the Tuple Store Instead of Utilizing Ephemeral Contextual TuplesCritical
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 NEVER invoke `fgaClient.write()` to record temporal, step-up (MFA), break-glass, or session-scoped authorization grants.

Engineers MUST NEVER invoke `fgaClient.write()` to record temporal, step-up (MFA), break-glass, or session-scoped authorization 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.
2

Engineers MUST supply ephemeral access assertions exclusively via the `contextualTuples` array in `fgaClient.check()`, `fgaClient.listObjects()`, or `fgaClient.expand()` payloads.

Engineers MUST supply ephemeral access assertions exclusively via the `contextualTuples` array in `fgaClient.check()`, `fgaClient.listObjects()`, or `fgaClient.expand()` payloads.

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 validate transient claims (e.g., JWT signatures, step-up MFA validity, break-glass session expirations) in the application or API gateway layer prior to injecting them into contextual tuples.

Code MUST validate transient claims (e.g., JWT signatures, step-up MFA validity, break-glass session expirations) in the application or API gateway layer prior to injecting them into contextual 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.
4

Services MUST treat the OpenFGA persistent relational store as immutable with respect to high-velocity transient request telemetry, avoiding audit log and changelog exhaustion.

Services MUST treat the OpenFGA persistent relational store as immutable with respect to high-velocity transient request telemetry, avoiding audit log and changelog exhaustion.

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 background cleanup workers, Redis TTL synchronization, or scheduled deletes to clean up temporary access grants written to OpenFGA persistence stores.

Components NEVER rely on background cleanup workers, Redis TTL synchronization, or scheduled deletes to clean up temporary access grants written to OpenFGA persistence stores.

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 Contextual Tuples Anti-Pollution Guardrail critical for AI coding assistants?

Enforces that temporal, session-bound, and dynamic authorization assertions are supplied strictly as contextual tuples during OpenFGA evaluation queries rather than persisted to the tuple store. This prevents high-velocity database bloat, changelog table exhaustion, and critical privilege-retention vulnerabilities caused by orphaned revocation writes. 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 Transient Grants to the Tuple Store Instead of Utilizing Ephemeral Contextual Tuples) 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