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

OpenFGA Ephemeral Grant Fencing via Dynamic Contextual Tuples

Prohibits static persistent relation writes for short-lived or time-bounded authorizations in OpenFGA storage engines. Mandates that transient, emergency, or session-scoped grants are validated just-in-time (JIT) using cryptographically signed claims and injected dynamically as ephemeral contextual tuples during check evaluation.

Prohibited Anti-Pattern: Persisting Short-Lived Access Grants into OpenFGA Stores with Async TTL-Based Deletions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Ephemeral Grant Fencing via Dynamic Contextual Tuples - Prohibits static persistent relation writes for short-lived or time-bounded authorizations in OpenFGA storage engines. Mandates that transient, emergency, or session-scoped grants are validated just-in-time (JIT) using cryptographically signed claims and injected dynamically as ephemeral contextual tuples during check evaluation.
globs: src/auth/**/*.{ts,tsx}, src/security/**/*.{ts,tsx}, src/services/**/*.{ts,tsx}, src/middleware/**/*.{ts,tsx}, lib/authorization/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-ephemeral-grant-contextual-tuple-fencing"
---

# OpenFGA Ephemeral Grant Fencing via Dynamic Contextual Tuples

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Persisting Short-Lived Access Grants into OpenFGA Stores with Async TTL-Based Deletions

## System Constraints
You are a Principal Security Architect enforcing the OpenFGA Contextual Tuple Ephemeral Grant Fencing Standard. Mandate that temporary grants (break-glass, time-bounded privileges, stepped-up MFA authorizations) NEVER write static tuples to OpenFGA persistence stores. Enforce JIT contextual tuple injection validated against cryptographically signed assertions.

## Strict Guidelines
- Engineers MUST NEVER execute OpenFGA `write` or `writeTuples` operations to persist temporary, break-glass, session-bound, or time-decaying authorization relations.
- Engineers MUST ALWAYS supply transient grants just-in-time via the `contextualTuples` array parameter inside `fgaClient.check()` or `fgaClient.listObjects()` calls.
- Services MUST cryptographically verify the signature, issuer, audience, and absolute expiration (`exp`) timestamp of the ephemeral access token (JWT/PASETO) prior to generating contextual tuples.
- Code MUST strictly map verified token claims (such as verified subject ID and target resource identifier) to the contextual tuple's `user`, `relation`, and `object` fields without accepting arbitrary client-supplied parameter overrides.
- Components NEVER rely on cron workers, background queues, or delayed database cleanups to revoke temporary access stored in the OpenFGA database.

## Bad vs Good Implementations
### Handling Break-Glass Access: Persistent Tuple Write vs. Ephemeral Contextual Tuple Injection

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Persisting transient grants directly to OpenFGA tuple storage creates severe authorization leakage. If the application crashes, restarts, or Redis queue jobs fail, the elevated relation ('emergency_admin') remains in the database permanently, violating zero-trust and least-privilege principles.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

interface BreakGlassRequest {
  userId: string;
  resourceId: string;
  ttlSeconds: number;
}

export async function grantBreakGlassAccess(
  fgaClient: OpenFgaClient,
  req: BreakGlassRequest
): Promise<void> {
  // VULNERABILITY: Writing transient state to persistent storage.
  // If the background revocation worker fails or crashes, this access persists indefinitely.
  await fgaClient.write({
    writes: [{
      user: `user:${req.userId}`,
      relation: 'emergency_admin',
      object: `cluster:${req.resourceId}`,
    }],
  });

  // Unreliable asynchronous revocation
  setTimeout(async () => {
    await fgaClient.write({
      deletes: [{
        user: `user:${req.userId}`,
        relation: 'emergency_admin',
        object: `cluster:${req.resourceId}`,
      }],
    });
  }, req.ttlSeconds * 1000);
}
```

#### Production Standard (Correct)
> **Standard**: Temporary elevated privilege is validated through a cryptographically signed token and injected exclusively in-memory as an ephemeral contextual tuple during evaluation. Zero writes occur against the OpenFGA storage layer, eliminating leakage risk upon service failure.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { jwtVerify, JWTPayload } from 'jose';

interface BreakGlassTokenPayload extends JWTPayload {
  sub: string;
  scope: string;
  targetResource: string;
}

export async function evaluateAccessWithJitContext(
  fgaClient: OpenFgaClient,
  breakGlassToken: string | undefined,
  userId: string,
  resourceId: string,
  signingSecret: Uint8Array
): Promise<boolean> {
  const contextualTuples: Array<{ user: string; relation: string; object: string }> = [];

  if (breakGlassToken) {
    // Verify cryptographic signature and active temporal window
    const { payload } = await jwtVerify<BreakGlassTokenPayload>(
      breakGlassToken,
      signingSecret,
      {
        issuer: 'https://auth.internal.corp',
        audience: 'openfga-evaluator',
        currentDate: new Date(),
      }
    );

    // Invariant: Verify claim targets match the requested scope
    if (
      payload.sub === userId &&
      payload.targetResource === resourceId &&
      payload.scope === 'emergency_admin'
    ) {
      contextualTuples.push({
        user: `user:${payload.sub}`,
        relation: 'emergency_admin',
        object: `cluster:${payload.targetResource}`,
      });
    }
  }

  // Dynamic JIT check without polluting persistent state
  const { allowed } = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'administer',
    object: `cluster:${resourceId}`,
    contextualTuples,
  });

  return 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 Grant Fencing via Dynamic Contextual Tuples

OpenFGA Ephemeral Grant Fencing via Dynamic Contextual Tuples defines an industrial-grade behavioral standard for security engineering. Prohibits static persistent relation writes for short-lived or time-bounded authorizations in OpenFGA storage engines. Mandates that transient, emergency, or session-scoped grants are validated just-in-time (JIT) using cryptographically signed claims and injected dynamically as ephemeral contextual tuples during check evaluation. 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 Short-Lived Access Grants into OpenFGA Stores with Async TTL-Based Deletions 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 Short-Lived Access Grants into OpenFGA Stores with Async TTL-Based DeletionsCritical
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 execute OpenFGA `write` or `writeTuples` operations to persist temporary, break-glass, session-bound, or time-decaying authorization relations.

Engineers MUST NEVER execute OpenFGA `write` or `writeTuples` operations to persist temporary, break-glass, session-bound, or time-decaying authorization relations.

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 ALWAYS supply transient grants just-in-time via the `contextualTuples` array parameter inside `fgaClient.check()` or `fgaClient.listObjects()` calls.

Engineers MUST ALWAYS supply transient grants just-in-time via the `contextualTuples` array parameter inside `fgaClient.check()` or `fgaClient.listObjects()` calls.

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 cryptographically verify the signature, issuer, audience, and absolute expiration (`exp`) timestamp of the ephemeral access token (JWT/PASETO) prior to generating contextual tuples.

Services MUST cryptographically verify the signature, issuer, audience, and absolute expiration (`exp`) timestamp of the ephemeral access token (JWT/PASETO) prior to generating 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

Code MUST strictly map verified token claims (such as verified subject ID and target resource identifier) to the contextual tuple's `user`, `relation`, and `object` fields without accepting arbitrary client-supplied parameter overrides.

Code MUST strictly map verified token claims (such as verified subject ID and target resource identifier) to the contextual tuple's `user`, `relation`, and `object` fields without accepting arbitrary client-supplied parameter overrides.

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 cron workers, background queues, or delayed database cleanups to revoke temporary access stored in the OpenFGA database.

Components NEVER rely on cron workers, background queues, or delayed database cleanups to revoke temporary access stored in the OpenFGA database.

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 Grant Fencing via Dynamic Contextual Tuples critical for AI coding assistants?

Prohibits static persistent relation writes for short-lived or time-bounded authorizations in OpenFGA storage engines. Mandates that transient, emergency, or session-scoped grants are validated just-in-time (JIT) using cryptographically signed claims and injected dynamically as ephemeral contextual tuples during check evaluation. 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 Short-Lived Access Grants into OpenFGA Stores with Async TTL-Based Deletions) 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