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

OpenFGA Ephemeral Access Leasing with Cryptographically Verified Contextual Tuples

Enforces that transient, just-in-time authorization evaluations must inject strictly bounded contextual tuples verified via cryptographically signed lease tokens. Contextual tuples must be validated against sub-minute timestamps and bounded nonces directly prior to authorization evaluations, avoiding persistent storage of temporal privileges within the OpenFGA tuple store.

Prohibited Anti-Pattern: Persisting Short-Lived Access Tuples in OpenFGA or Trusting Client-Supplied Contextual Tuples Without Cryptographic Lease Verification

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Ephemeral Access Leasing with Cryptographically Verified Contextual Tuples - Enforces that transient, just-in-time authorization evaluations must inject strictly bounded contextual tuples verified via cryptographically signed lease tokens. Contextual tuples must be validated against sub-minute timestamps and bounded nonces directly prior to authorization evaluations, avoiding persistent storage of temporal privileges within the OpenFGA tuple store.
globs: src/auth/**/*.ts, src/security/**/*.ts, src/services/authz/**/*.ts, src/middleware/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuple-ephemeral-access-leasing"
---

# OpenFGA Ephemeral Access Leasing with Cryptographically Verified Contextual Tuples

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Persisting Short-Lived Access Tuples in OpenFGA or Trusting Client-Supplied Contextual Tuples Without Cryptographic Lease Verification

## System Constraints
You are a Principal Security Architect enforcing the OpenFGA Contextual Tuple Ephemeral Access Leasing Standard. You must ensure that just-in-time access grants never commit temporary tuples directly into the OpenFGA storage engine. Instead, all transient privileges must be passed as contextual tuples inside OpenFGA Check/Expand API calls, generated only from cryptographically validated lease tokens with strict, sub-minute TTLs and monotonic drift protection.

## Strict Guidelines
- Engineers MUST ALWAYS supply transient privileges exclusively via the contextual_tuples property in OpenFGA Check requests rather than persisting tuples via Write API.
- Engineers MUST NOT accept raw contextual tuple arrays directly from untrusted client requests or upstream payloads without cryptographically verifying a signed ephemeral lease token (e.g., HMAC-SHA256 or Ed25519 payload).
- Lease tokens MUST enforce an explicit, sub-minute time-to-live (TTL <= 60 seconds) validated with zero or strict maximum 2-second clock skew tolerance before tuple injection.
- Services MUST validate that the contextual tuple user, relation, and object match the cryptographic claim invariants precisely before executing an OpenFGA Check call.
- Components NEVER store ephemeral lease states in OpenFGA database backends; revocation must occur via lease signing key rotation, bloom filters, or centralized nonce invalidation.

## Bad vs Good Implementations
### Ephemeral Contextual Tuple Verification and OpenFGA Check Injection

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Contextual tuples are constructed directly from unverified caller input without verifying digital signatures, monotonic timestamps, or expiration windows. Any caller can spoof arbitrary contextual permissions.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

interface JustInTimeRequest {
  userId: string;
  documentId: string;
  role: string;
}

export async function evaluateAccess(
  fgaClient: OpenFgaClient,
  req: JustInTimeRequest
): Promise<boolean> {
  // ANTI-PATTERN: Client-provided contextual tuples are accepted without cryptographic verification
  // or, worse, written directly to the persistent tuple store with deferred cleanup.
  const { allowed } = await fgaClient.check({
    user: `user:${req.userId}`,
    relation: 'can_read',
    object: `document:${req.documentId}`,
    contextualTuples: [
      {
        user: `user:${req.userId}`,
        relation: req.role,
        object: `document:${req.documentId}`,
      },
    ],
  });

  return Boolean(allowed);
}
```

#### Production Standard (Correct)
> **Standard**: Validates the cryptographic HMAC-SHA256 signature and asserts sub-minute TTL constraints (<= 60s) with bounded clock skew before constructing the contextual tuple. The authorization engine receives tamper-proof contextual evidence without mutating the persistent tuple store.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';
import { createHmac, timingSafeEqual } from 'crypto';

interface EphemeralLeaseToken {
  user: string;
  relation: string;
  object: string;
  issuedAt: number;
  expiresAt: number;
  nonce: string;
}

const MAX_TTL_MS = 60_000; // Sub-minute lease constraint
const CLOCK_SKEW_TOLERANCE_MS = 2_000;

export function verifyAndExtractLease(
  rawToken: string,
  signature: string,
  secretKey: Buffer
): EphemeralLeaseToken {
  const expectedSig = createHmac('sha256', secretKey).update(rawToken).digest();
  const providedSig = Buffer.from(signature, 'hex');

  if (expectedSig.length !== providedSig.length || !timingSafeEqual(expectedSig, providedSig)) {
    throw new Error('Unauthorized: Invalid lease signature');
  }

  const lease = JSON.parse(rawToken) as EphemeralLeaseToken;
  const now = Date.now();

  if (lease.expiresAt - lease.issuedAt > MAX_TTL_MS) {
    throw new Error('Security Violation: Lease duration exceeds maximum permitted 60-second TTL');
  }
  if (now > lease.expiresAt + CLOCK_SKEW_TOLERANCE_MS || now < lease.issuedAt - CLOCK_SKEW_TOLERANCE_MS) {
    throw new Error('Unauthorized: Ephemeral lease expired or invalid timestamp');
  }

  return lease;
}

export async function evaluateAccessWithLease(
  fgaClient: OpenFgaClient,
  rawToken: string,
  signature: string,
  secretKey: Buffer,
  targetObject: string,
  action: string
): Promise<boolean> {
  const lease = verifyAndExtractLease(rawToken, signature, secretKey);

  if (lease.object !== targetObject) {
    throw new Error('Security Violation: Lease target mismatch');
  }

  const checkPayload: ClientCheckRequest = {
    user: lease.user,
    relation: action,
    object: targetObject,
    contextualTuples: [
      {
        user: lease.user,
        relation: lease.relation,
        object: lease.object,
      },
    ],
  };

  const response = await fgaClient.check(checkPayload);
  return Boolean(response.allowed);
}
```

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA Ephemeral Access Leasing with Cryptographically Verified Contextual Tuples

OpenFGA Ephemeral Access Leasing with Cryptographically Verified Contextual Tuples defines an industrial-grade behavioral standard for security engineering. Enforces that transient, just-in-time authorization evaluations must inject strictly bounded contextual tuples verified via cryptographically signed lease tokens. Contextual tuples must be validated against sub-minute timestamps and bounded nonces directly prior to authorization evaluations, avoiding persistent storage of temporal privileges within the OpenFGA tuple store. 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 Tuples in OpenFGA or Trusting Client-Supplied Contextual Tuples Without Cryptographic Lease Verification 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 Tuples in OpenFGA or Trusting Client-Supplied Contextual Tuples Without Cryptographic Lease VerificationCritical
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 privileges exclusively via the contextual_tuples property in OpenFGA Check requests rather than persisting tuples via Write API.

Engineers MUST ALWAYS supply transient privileges exclusively via the contextual_tuples property in OpenFGA Check requests rather than persisting tuples via Write API.

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 accept raw contextual tuple arrays directly from untrusted client requests or upstream payloads without cryptographically verifying a signed ephemeral lease token (e.g., HMAC-SHA256 or Ed25519 payload).

Engineers MUST NOT accept raw contextual tuple arrays directly from untrusted client requests or upstream payloads without cryptographically verifying a signed ephemeral lease token (e.g., HMAC-SHA256 or Ed25519 payload).

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

Lease tokens MUST enforce an explicit, sub-minute time-to-live (TTL <= 60 seconds) validated with zero or strict maximum 2-second clock skew tolerance before tuple injection.

Lease tokens MUST enforce an explicit, sub-minute time-to-live (TTL <= 60 seconds) validated with zero or strict maximum 2-second clock skew tolerance before tuple injection.

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 validate that the contextual tuple user, relation, and object match the cryptographic claim invariants precisely before executing an OpenFGA Check call.

Services MUST validate that the contextual tuple user, relation, and object match the cryptographic claim invariants precisely before executing an OpenFGA Check call.

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 store ephemeral lease states in OpenFGA database backends

Components NEVER store ephemeral lease states in OpenFGA database backends; revocation must occur via lease signing key rotation, bloom filters, or centralized nonce invalidation.

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 Access Leasing with Cryptographically Verified Contextual Tuples critical for AI coding assistants?

Enforces that transient, just-in-time authorization evaluations must inject strictly bounded contextual tuples verified via cryptographically signed lease tokens. Contextual tuples must be validated against sub-minute timestamps and bounded nonces directly prior to authorization evaluations, avoiding persistent storage of temporal privileges within the OpenFGA tuple store. 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 Tuples in OpenFGA or Trusting Client-Supplied Contextual Tuples Without Cryptographic Lease Verification) 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