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-fencing

OpenFGA Ephemeral Contextual Tuple Deterministic TTL Enforcement

Enforces strict cryptographic fencing and deterministic monotonic TTL validation for volatile contextual tuples injected into OpenFGA authorization checks. Prevents authorization cache poisoning and cross-request tuple bleed by cryptographically binding ephemeral contextual claims to unique request nonces and enforcing sub-millisecond evaluation deadlines. Guarantees that stale environmental assertions (such as step-up authentication, geo-velocity fences, and ephemeral break-glass roles) cannot be cached or replayed across evaluation boundaries.

Prohibited Anti-Pattern: Injecting Ephemeral Contextual Tuples Without Cryptographic Nonce Fencing or Monotonic TTL Enforcement Allowing Cache Poisoning

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Ephemeral Contextual Tuple Deterministic TTL Enforcement - Enforces strict cryptographic fencing and deterministic monotonic TTL validation for volatile contextual tuples injected into OpenFGA authorization checks. Prevents authorization cache poisoning and cross-request tuple bleed by cryptographically binding ephemeral contextual claims to unique request nonces and enforcing sub-millisecond evaluation deadlines. Guarantees that stale environmental assertions (such as step-up authentication, geo-velocity fences, and ephemeral break-glass roles) cannot be cached or replayed across evaluation boundaries.
globs: src/auth/**/*.ts, src/services/auth/**/*.ts, src/lib/fga/**/*.ts, src/security/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-ephemeral-contextual-tuple-ttl-fencing"
---

# OpenFGA Ephemeral Contextual Tuple Deterministic TTL Enforcement

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Injecting Ephemeral Contextual Tuples Without Cryptographic Nonce Fencing or Monotonic TTL Enforcement Allowing Cache Poisoning

## System Constraints
You are a Principal Security Architect specializing in Fine-Grained Authorization (OpenFGA) and Zero-Trust systems. Your task is to enforce uncompromising cryptographic fencing and deterministic sub-millisecond TTL validation on all volatile contextual tuples. Never permit raw, un-fenced contextual claims to be passed to OpenFGA Check or ListObjects APIs. Mandate that all contextual tuples carry monotonic validation bounds, derive a deterministic claim digest, and bypass or invalidate downstream evaluation caches when volatile predicates are evaluated.

## Strict Guidelines
- Engineers MUST ALWAYS sign and seal ephemeral contextual claims using an HMAC or asymmetric key before transforming them into OpenFGA contextual tuples.
- Engineers MUST NOT reuse contextual tuples across multiple OpenFGA evaluation requests or attach contextual tuples to global request contexts.
- Code SHOULD verify the claim's monotonic timestamp window (not-before and not-after) immediately prior to client dispatch, discarding expired tuples deterministically.
- Services MUST incorporate a SHA-256 digest of the contextual tuple payload and unique evaluation nonce into any client-side or intermediate authorization memoization keys.
- Components NEVER evaluate contextual tuples against persistent OpenFGA storage models or bypass check-level deadlining.

## Bad vs Good Implementations
### Cryptographically Fenced Contextual Tuple Verification and Dispatch

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Contextual assertions are injected as raw, unbounded tuples without time bounds (TTL), replay fencing, or cryptographic verification. If an intermediate cache or memoized check layer caches the evaluation based merely on user and document ID, subsequent checks might falsely succeed after device compliance lapses.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

// VULNERABLE: Unsigned contextual tuple without TTL or deterministic nonce fencing.
// Vulnerable to replay attacks, cache poisoning across async context boundaries,
// and stale device posture reuse.
export async function authorizeAccess(
  fgaClient: OpenFgaClient,
  userId: string,
  documentId: string,
  deviceCompliant: boolean
): Promise<boolean> {
  const contextualTuples = deviceCompliant
    ? [{ user: `user:${userId}`, relation: 'device_compliant', object: `document:${documentId}` }]
    : [];

  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'viewer',
    object: `document:${documentId}`,
    contextual_tuples: contextualTuples
  });

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

#### Production Standard (Correct)
> **Standard**: Contextual assertions are sealed with an HMAC, carrying strict monotonic expiration timestamps and single-use nonces. Tuples are cryptographically validated at dispatch time with constant-time equality checks, strictly preventing forged or stale contextual claim injection into the authorization graph.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';
import { createHmac, timingSafeEqual } from 'node:crypto';

export interface EphemeralClaim {
  readonly userId: string;
  readonly relation: string;
  readonly objectId: string;
  readonly nonce: string;
  readonly expiresAtEpochMs: number;
  readonly signature: string;
}

export class FgaSecurityFence {
  constructor(private readonly hmacSecret: Buffer) {}

  public verifyAndExtractTuple(
    claim: EphemeralClaim,
    nowEpochMs: number = Date.now()
  ): { user: string; relation: string; object: string } {
    if (nowEpochMs >= claim.expiresAtEpochMs) {
      throw new Error(`Contextual claim expired at ${claim.expiresAtEpochMs}, now: ${nowEpochMs}`);
    }

    const canonicalPayload = `${claim.userId}:${claim.relation}:${claim.objectId}:${claim.nonce}:${claim.expiresAtEpochMs}`;
    const expectedHmac = createHmac('sha256', this.hmacSecret).update(canonicalPayload).digest();
    const providedHmac = Buffer.from(claim.signature, 'hex');

    if (expectedHmac.length !== providedHmac.length || !timingSafeEqual(expectedHmac, providedHmac)) {
      throw new Error('Cryptographic signature verification failed for ephemeral contextual claim');
    }

    return {
      user: `user:${claim.userId}`,
      relation: claim.relation,
      object: claim.objectId
    };
  }
}

export async function authorizeFencedAccess(
  fgaClient: OpenFgaClient,
  fence: FgaSecurityFence,
  userId: string,
  documentId: string,
  ephemeralClaim?: EphemeralClaim
): Promise<boolean> {
  const contextualTuples = ephemeralClaim
    ? [fence.verifyAndExtractTuple(ephemeralClaim)]
    : [];

  const request: ClientCheckRequest = {
    user: `user:${userId}`,
    relation: 'viewer',
    object: `document:${documentId}`,
    contextual_tuples: contextualTuples
  };

  // Disable or isolate cache by passing non-cacheable context headers if supported by upstream transport
  const response = await fgaClient.check(request);
  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 Tuple Deterministic TTL Enforcement

OpenFGA Ephemeral Contextual Tuple Deterministic TTL Enforcement defines an industrial-grade behavioral standard for security engineering. Enforces strict cryptographic fencing and deterministic monotonic TTL validation for volatile contextual tuples injected into OpenFGA authorization checks. Prevents authorization cache poisoning and cross-request tuple bleed by cryptographically binding ephemeral contextual claims to unique request nonces and enforcing sub-millisecond evaluation deadlines. Guarantees that stale environmental assertions (such as step-up authentication, geo-velocity fences, and ephemeral break-glass roles) cannot be cached or replayed across evaluation boundaries. 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: Injecting Ephemeral Contextual Tuples Without Cryptographic Nonce Fencing or Monotonic TTL Enforcement Allowing Cache Poisoning 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 DriftInjecting Ephemeral Contextual Tuples Without Cryptographic Nonce Fencing or Monotonic TTL Enforcement Allowing Cache PoisoningCritical
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 sign and seal ephemeral contextual claims using an HMAC or asymmetric key before transforming them into OpenFGA contextual tuples.

Engineers MUST ALWAYS sign and seal ephemeral contextual claims using an HMAC or asymmetric key before transforming them into OpenFGA 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.
2

Engineers MUST NOT reuse contextual tuples across multiple OpenFGA evaluation requests or attach contextual tuples to global request contexts.

Engineers MUST NOT reuse contextual tuples across multiple OpenFGA evaluation requests or attach contextual tuples to global request contexts.

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 SHOULD verify the claim's monotonic timestamp window (not-before and not-after) immediately prior to client dispatch, discarding expired tuples deterministically.

Code SHOULD verify the claim's monotonic timestamp window (not-before and not-after) immediately prior to client dispatch, discarding expired tuples deterministically.

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 incorporate a SHA-256 digest of the contextual tuple payload and unique evaluation nonce into any client-side or intermediate authorization memoization keys.

Services MUST incorporate a SHA-256 digest of the contextual tuple payload and unique evaluation nonce into any client-side or intermediate authorization memoization keys.

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 evaluate contextual tuples against persistent OpenFGA storage models or bypass check-level deadlining.

Components NEVER evaluate contextual tuples against persistent OpenFGA storage models or bypass check-level deadlining.

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 Deterministic TTL Enforcement critical for AI coding assistants?

Enforces strict cryptographic fencing and deterministic monotonic TTL validation for volatile contextual tuples injected into OpenFGA authorization checks. Prevents authorization cache poisoning and cross-request tuple bleed by cryptographically binding ephemeral contextual claims to unique request nonces and enforcing sub-millisecond evaluation deadlines. Guarantees that stale environmental assertions (such as step-up authentication, geo-velocity fences, and ephemeral break-glass roles) cannot be cached or replayed across evaluation boundaries. 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 (Injecting Ephemeral Contextual Tuples Without Cryptographic Nonce Fencing or Monotonic TTL Enforcement Allowing Cache Poisoning) 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