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

OpenFGA Ephemeral Contextual Tuple Cryptographic TTL and Replay Guardrail

Mandates that all contextual tuples injected into OpenFGA Check and ListObjects queries originate from cryptographically verified ephemeral grants with strict time-to-live (TTL) bounds and replay verification. Prevents privilege escalation and persistent authorization bypasses caused by passing arbitrary, stale, or replayed dynamic authorization tuples directly into OpenFGA evaluation pipelines.

Prohibited Anti-Pattern: Unvalidated Pass-Through of Arbitrary or Stale Contextual Tuples to OpenFGA Check APIs

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Ephemeral Contextual Tuple Cryptographic TTL and Replay Guardrail - Mandates that all contextual tuples injected into OpenFGA Check and ListObjects queries originate from cryptographically verified ephemeral grants with strict time-to-live (TTL) bounds and replay verification. Prevents privilege escalation and persistent authorization bypasses caused by passing arbitrary, stale, or replayed dynamic authorization tuples directly into OpenFGA evaluation pipelines.
globs: src/**/authz/**/*.{ts,js}, src/**/fga/**/*.{ts,js}, src/**/guards/**/*.{ts,js}, src/**/middleware/**/*.{ts,js}, src/**/services/auth*/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-ephemeral-contextual-tuple-ttl-validation"
---

# OpenFGA Ephemeral Contextual Tuple Cryptographic TTL and Replay Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unvalidated Pass-Through of Arbitrary or Stale Contextual Tuples to OpenFGA Check APIs

## System Constraints
You are a Principal Software Architect and Rules Author enforcing strict temporal security on OpenFGA authorization checks. You must mandate that ephemeral contextual tuples provided during Check API requests are cryptographically verified, strictly bound by a deterministic TTL (maximum 300 seconds), and validated against replay before execution. Reject any architecture that proxies raw, unverified client input into OpenFGA contextual tuple arrays.

## Strict Guidelines
- Engineers MUST ALWAYS verify the digital signature (e.g., Ed25519 or RS256) of ephemeral contextual tuple envelopes before unwrapping them for OpenFGA evaluation.
- Engineers MUST NOT allow client applications to supply arbitrary user-relation-object tuples directly to OpenFGA Check or ListObjects API calls.
- Services MUST reject contextual tuple assertions whose temporal lifetime exceeds a hard maximum threshold (e.g., 300 seconds) or whose 'exp' timestamp is in the past, accounting for a maximum clock skew of 5 seconds.
- Code SHOULD enforce deterministic nonce or JTI tracking on one-time ephemeral privilege grants (such as break-glass or step-up MFA access) to prevent authorization replay attacks within the validity window.
- Components NEVER bridge raw HTTP headers, query parameters, or unparsed JSON payloads directly into the OpenFGA client's `contextualTuples` argument without schema assertion and temporal cryptographic validation.

## Bad vs Good Implementations
### Direct Injection of Client Contextual Tuples vs. Cryptographically Verified Ephemeral Gate

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The endpoint blindly trusts contextual tuples supplied by the caller in the request body. An attacker can construct arbitrary tuple sets (e.g., declaring themselves as an 'editor' or 'admin') and pass them to OpenFGA, bypassing standard access control without any cryptographic proof or temporal expiration.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';
import { Request, Response } from 'express';

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

// VULNERABLE: Direct forward of untrusted client contextual tuples without
// signature verification, TTL enforcement, or replay mitigation.
export async function authorizeDocumentAccess(req: Request, res: Response) {
  const { documentId } = req.params;
  const { ephemeralTuples } = req.body; // e.g., [{ user: 'user:123', relation: 'editor', object: 'doc:456' }]

  const checkPayload: ClientCheckRequest = {
    user: `user:${req.user.id}`,
    relation: 'can_write',
    object: `document:${documentId}`,
    contextualTuples: ephemeralTuples // CRITICAL SECURITY FLAW: Client asserts arbitrary access!
  };

  const result = await fgaClient.check(checkPayload);
  if (!result.allowed) {
    return res.status(403).json({ error: 'Forbidden' });
  }

  res.json({ status: 'Access granted' });
}
```

#### Production Standard (Correct)
> **Standard**: The contextual tuples are encapsulated inside a cryptographically signed token (JWT). The gate cryptographically verifies the token signature against a trusted JWKS, asserts strict TTL constraints (max 300 seconds), guards against subject spoofing, and validates that the contextual tuples only apply to the intended subject and object target before forwarding to OpenFGA.
```typescript
import { OpenFgaClient, ClientCheckRequest, TupleKey } from '@openfga/sdk';
import { Request, Response } from 'express';
import { createRemoteJWKSet, jwtVerify } from 'jose';

const fgaClient = new OpenFgaClient({ apiUrl: process.env.FGA_API_URL! });
const JWKS = createRemoteJWKSet(new URL(process.env.AUTH_JWKS_URI!));
const MAX_EPHEMERAL_TTL_SECONDS = 300;
const CLOCK_TOLERANCE_SECONDS = 5;

interface EphemeralGrantClaim {
  sub: string;
  tuples: TupleKey[];
  exp: number;
  iat: number;
  jti: string;
}

export async function verifyAndResolveContextualTuples(
  token: string | undefined,
  expectedSubject: string,
  expectedObject: string
): Promise<TupleKey[]> {
  if (!token) return [];

  const { payload } = await jwtVerify<EphemeralGrantClaim>(token, JWKS, {
    clockTolerance: CLOCK_TOLERANCE_SECONDS,
  });

  const currentTime = Math.floor(Date.now() / 1000);
  if (!payload.exp || payload.exp - payload.iat > MAX_EPHEMERAL_TTL_SECONDS) {
    throw new Error('Ephemeral grant exceeds maximum allowable TTL of 300s');
  }

  if (payload.sub !== expectedSubject) {
    throw new Error('Subject mismatch in ephemeral authorization token');
  }

  // Strict validation: contextual tuples must strictly target expected object
  return payload.tuples.filter(t => {
    const isValidSubject = t.user === `user:${expectedSubject}`;
    const isValidObject = t.object === expectedObject;
    return isValidSubject && isValidObject;
  });
}

export async function authorizeDocumentAccess(req: Request, res: Response) {
  const { documentId } = req.params;
  const ephemeralGrantToken = req.headers['x-ephemeral-grant'] as string | undefined;
  const targetObject = `document:${documentId}`;

  try {
    const validatedTuples = await verifyAndResolveContextualTuples(
      ephemeralGrantToken,
      req.user.id,
      targetObject
    );

    const checkPayload: ClientCheckRequest = {
      user: `user:${req.user.id}`,
      relation: 'can_write',
      object: targetObject,
      contextualTuples: validatedTuples,
    };

    const result = await fgaClient.check(checkPayload);
    if (!result.allowed) {
      return res.status(403).json({ error: 'Forbidden' });
    }

    return res.json({ status: 'Access granted' });
  } catch (err) {
    return res.status(401).json({ error: 'Invalid or expired ephemeral authorization grant' });
  }
}
```

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 Cryptographic TTL and Replay Guardrail

OpenFGA Ephemeral Contextual Tuple Cryptographic TTL and Replay Guardrail defines an industrial-grade behavioral standard for security engineering. Mandates that all contextual tuples injected into OpenFGA Check and ListObjects queries originate from cryptographically verified ephemeral grants with strict time-to-live (TTL) bounds and replay verification. Prevents privilege escalation and persistent authorization bypasses caused by passing arbitrary, stale, or replayed dynamic authorization tuples directly into OpenFGA evaluation pipelines. 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: Unvalidated Pass-Through of Arbitrary or Stale Contextual Tuples to OpenFGA Check APIs 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 DriftUnvalidated Pass-Through of Arbitrary or Stale Contextual Tuples to OpenFGA Check APIsCritical
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 verify the digital signature (e.g., Ed25519 or RS256) of ephemeral contextual tuple envelopes before unwrapping them for OpenFGA evaluation.

Engineers MUST ALWAYS verify the digital signature (e.g., Ed25519 or RS256) of ephemeral contextual tuple envelopes before unwrapping them for OpenFGA evaluation.

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 allow client applications to supply arbitrary user-relation-object tuples directly to OpenFGA Check or ListObjects API calls.

Engineers MUST NOT allow client applications to supply arbitrary user-relation-object tuples directly to OpenFGA Check or ListObjects API 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 reject contextual tuple assertions whose temporal lifetime exceeds a hard maximum threshold (e.g., 300 seconds) or whose 'exp' timestamp is in the past, accounting for a maximum clock skew of 5 seconds.

Services MUST reject contextual tuple assertions whose temporal lifetime exceeds a hard maximum threshold (e.g., 300 seconds) or whose 'exp' timestamp is in the past, accounting for a maximum clock skew of 5 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

Code SHOULD enforce deterministic nonce or JTI tracking on one-time ephemeral privilege grants (such as break-glass or step-up MFA access) to prevent authorization replay attacks within the validity window.

Code SHOULD enforce deterministic nonce or JTI tracking on one-time ephemeral privilege grants (such as break-glass or step-up MFA access) to prevent authorization replay attacks within the validity window.

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 bridge raw HTTP headers, query parameters, or unparsed JSON payloads directly into the OpenFGA client's `contextualTuples` argument without schema assertion and temporal cryptographic validation.

Components NEVER bridge raw HTTP headers, query parameters, or unparsed JSON payloads directly into the OpenFGA client's `contextualTuples` argument without schema assertion and temporal cryptographic 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 Cryptographic TTL and Replay Guardrail critical for AI coding assistants?

Mandates that all contextual tuples injected into OpenFGA Check and ListObjects queries originate from cryptographically verified ephemeral grants with strict time-to-live (TTL) bounds and replay verification. Prevents privilege escalation and persistent authorization bypasses caused by passing arbitrary, stale, or replayed dynamic authorization tuples directly into OpenFGA evaluation pipelines. 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 (Unvalidated Pass-Through of Arbitrary or Stale Contextual Tuples to OpenFGA Check APIs) 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