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

OpenFGA Ephemeral Contextual Tuple Verification and Ingestion Guardrail

Enforces strict authorization boundaries in OpenFGA by mandating that dynamic, transient attributes (such as IP bounds, active session scopes, step-up MFA claims, and break-glass tokens) are passed strictly as validated, short-lived contextual tuples rather than persisted in the relationship store. Prevents privilege elevation and stale grants by requiring cryptographic verification and TTL validation before contextual tuple construction.

Prohibited Anti-Pattern: Persisting Transient Authorization States into the Global FGA Tuplestore or Trusting Unverified Contextual Tuples

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Ephemeral Contextual Tuple Verification and Ingestion Guardrail - Enforces strict authorization boundaries in OpenFGA by mandating that dynamic, transient attributes (such as IP bounds, active session scopes, step-up MFA claims, and break-glass tokens) are passed strictly as validated, short-lived contextual tuples rather than persisted in the relationship store. Prevents privilege elevation and stale grants by requiring cryptographic verification and TTL validation before contextual tuple construction.
globs: src/auth/**/*.{ts,js}, src/services/authz/**/*.{ts,js}, src/middleware/**/*.{ts,js}, src/lib/openfga/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuple-ephemeral-boundary"
---

# OpenFGA Ephemeral Contextual Tuple Verification and Ingestion Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Persisting Transient Authorization States into the Global FGA Tuplestore or Trusting Unverified Contextual Tuples

## System Constraints
You are a Principal Security Architect specializing in Fine-Grained Authorization (FGA) and Zero-Trust Architectures. Your objective is to enforce architectural invariants on OpenFGA authorization checks. Never allow temporal, location-based, or session-bound roles to be written to persistent storage via writeTuples(). Mandate that all contextual tuples injected into fgaClient.check() originate from cryptographically verified claims, possess a strictly enforced TTL (under 300 seconds), and fail closed upon missing or expired proof.

## Strict Guidelines
- Engineers MUST ALWAYS supply transient security context (e.g., active break-glass roles, IP subnet boundaries, verified MFA status) via the `contextualTuples` property during `fgaClient.check()` or `fgaClient.batchCheck()`.
- Engineers MUST NOT write ephemeral or time-sensitive grant tuples into the OpenFGA persistent datastore via `fgaClient.write()` or `fgaClient.writeTuples()`.
- Engineers MUST verify the cryptographic signature and ensure `exp` does not exceed 300 seconds before converting JWT claims or security tokens into contextual tuples.
- Services MUST sanitize, canonicalize, and validate the format of user, relation, and object strings (e.g., matching the regex `^[a-zA-Z0-9_:-]+$`) before appending them to contextual tuple arrays.
- Components NEVER accept contextual tuple definitions directly from untrusted client-side payloads without server-side verification and schema validation.

## Bad vs Good Implementations
### Stale Privilege Persistence vs. Signed Ephemeral Contextual Tuples

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Persisting transient permissions into the database creates stale privilege elevation. If a network partition, unhandled error, or race condition occurs before revocation, the user retains emergency access permanently.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

const fgaClient = new OpenFgaClient({
  apiUrl: process.env.FGA_API_URL!,
  storeId: process.env.FGA_STORE_ID!,
});

// ANTI-PATTERN: Persisting temporary elevation into the global database
// and checking without contextual validation.
export async function authorizeEmergencyAccess(userId: string, documentId: string, clientTokenPayload: any) {
  // Dangerously writing transient step-up state into persistent storage
  if (clientTokenPayload.isBreakGlass) {
    await fgaClient.write({
      writes: [
        { user: `user:${userId}`, relation: 'emergency_responder', object: `document:${documentId}` }
      ]
    });
  }

  const { allowed } = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'can_view',
    object: `document:${documentId}`,
  });

  return allowed;
}
```

#### Production Standard (Correct)
> **Standard**: The good implementation validates signed cryptographic tokens, enforces a strict TTL under 300 seconds, and passes permissions via ephemeral contextual tuples during evaluation. No state is persisted to the FGA store, guaranteeing zero stale privilege elevation.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';
import { createRemoteJWKSet, jwtVerify } from 'jose';

const fgaClient = new OpenFgaClient({
  apiUrl: process.env.FGA_API_URL!,
  storeId: process.env.FGA_STORE_ID!,
});

const JWKS = createRemoteJWKSet(new URL(process.env.INTERNAL_AUTH_JWKS_URL!));
const MAX_EPHEMERAL_TTL_SECONDS = 300;

interface EphemeralClaims {
  sub: string;
  breakGlassDocId?: string;
  exp: number;
  iat: number;
}

export async function authorizeEmergencyAccess(
  userId: string,
  documentId: string,
  signedProofToken: string
): Promise<boolean> {
  // 1. Cryptographically verify ephemeral proof
  const { payload } = await jwtVerify<EphemeralClaims>(signedProofToken, JWKS, {
    algorithms: ['EdDSA', 'ES256'],
    clockTolerance: 5,
  });

  const now = Math.floor(Date.now() / 1000);
  if (!payload.exp || (payload.exp - now) > MAX_EPHEMERAL_TTL_SECONDS) {
    throw new Error('Ephemeral token exceeds maximum allowable authorization TTL.');
  }

  // 2. Build verified contextual tuples strictly bounded to this evaluation
  const contextualTuples: ClientCheckRequest['contextualTuples'] = [];
  
  if (payload.sub === userId && payload.breakGlassDocId === documentId) {
    contextualTuples.push({
      user: `user:${encodeURIComponent(userId)}`,
      relation: 'emergency_responder',
      object: `document:${encodeURIComponent(documentId)}`,
    });
  }

  // 3. Ephemeral check: Zero persistent state, immune to stale elevation leaks
  const { allowed } = await fgaClient.check({
    user: `user:${encodeURIComponent(userId)}`,
    relation: 'can_view',
    object: `document:${encodeURIComponent(documentId)}`,
    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 Contextual Tuple Verification and Ingestion Guardrail

OpenFGA Ephemeral Contextual Tuple Verification and Ingestion Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces strict authorization boundaries in OpenFGA by mandating that dynamic, transient attributes (such as IP bounds, active session scopes, step-up MFA claims, and break-glass tokens) are passed strictly as validated, short-lived contextual tuples rather than persisted in the relationship store. Prevents privilege elevation and stale grants by requiring cryptographic verification and TTL validation before contextual tuple construction. 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 Authorization States into the Global FGA Tuplestore or Trusting Unverified 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 Authorization States into the Global FGA Tuplestore or Trusting Unverified 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 ALWAYS supply transient security context (e.g., active break-glass roles, IP subnet boundaries, verified MFA status) via the `contextualTuples` property during `fgaClient.check()` or `fgaClient.batchCheck()`.

Engineers MUST ALWAYS supply transient security context (e.g., active break-glass roles, IP subnet boundaries, verified MFA status) via the `contextualTuples` property during `fgaClient.check()` or `fgaClient.batchCheck()`.

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 write ephemeral or time-sensitive grant tuples into the OpenFGA persistent datastore via `fgaClient.write()` or `fgaClient.writeTuples()`.

Engineers MUST NOT write ephemeral or time-sensitive grant tuples into the OpenFGA persistent datastore via `fgaClient.write()` or `fgaClient.writeTuples()`.

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

Engineers MUST verify the cryptographic signature and ensure `exp` does not exceed 300 seconds before converting JWT claims or security tokens into contextual tuples.

Engineers MUST verify the cryptographic signature and ensure `exp` does not exceed 300 seconds before converting JWT claims or security tokens 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 sanitize, canonicalize, and validate the format of user, relation, and object strings (e.g., matching the regex `^[a-zA-Z0-9_

Services MUST sanitize, canonicalize, and validate the format of user, relation, and object strings (e.g., matching the regex `^[a-zA-Z0-9_:-]+$`) before appending them to contextual tuple arrays.

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 accept contextual tuple definitions directly from untrusted client-side payloads without server-side verification and schema validation.

Components NEVER accept contextual tuple definitions directly from untrusted client-side payloads without server-side verification and schema validation.

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 Tuple Verification and Ingestion Guardrail critical for AI coding assistants?

Enforces strict authorization boundaries in OpenFGA by mandating that dynamic, transient attributes (such as IP bounds, active session scopes, step-up MFA claims, and break-glass tokens) are passed strictly as validated, short-lived contextual tuples rather than persisted in the relationship store. Prevents privilege elevation and stale grants by requiring cryptographic verification and TTL validation before contextual tuple construction. 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 Authorization States into the Global FGA Tuplestore or Trusting Unverified 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