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

OpenFGA Ephemeral Contextual Tuple Cryptographic Fencing & Lease Enforcement

Enforces strict cryptographic binding, short-lived epoch lease constraints, and cryptographic signature validation on dynamic contextual tuples evaluated in OpenFGA check queries. Prevents privilege escalation and confused-deputy attacks arising from unauthenticated caller-supplied relationship assertions or tuple replay. Ensures all dynamically ingested tuples are cryptographically verified, deterministic, and isolated to the immediate execution context.

Prohibited Anti-Pattern: Blind Ingestion of Untrusted Dynamic Contextual Tuples into OpenFGA Check Calls

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Ephemeral Contextual Tuple Cryptographic Fencing & Lease Enforcement - Enforces strict cryptographic binding, short-lived epoch lease constraints, and cryptographic signature validation on dynamic contextual tuples evaluated in OpenFGA check queries. Prevents privilege escalation and confused-deputy attacks arising from unauthenticated caller-supplied relationship assertions or tuple replay. Ensures all dynamically ingested tuples are cryptographically verified, deterministic, and isolated to the immediate execution context.
globs: src/**/auth/**/*.{ts,js}, src/**/fga/**/*.{ts,js}, src/**/permissions/**/*.{ts,js}, src/**/security/**/*.{ts,js}, src/**/access/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-ephemeral-contextual-tuple-fencing-standard"
---

# OpenFGA Ephemeral Contextual Tuple Cryptographic Fencing & Lease Enforcement

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Blind Ingestion of Untrusted Dynamic Contextual Tuples into OpenFGA Check Calls

## System Constraints
You are a Principal Security Architect and Authorization Systems Engineer specializing in OpenFGA, Zanzibar architectures, and zero-trust evaluation models. Your task is to enforce strict architectural guardrails preventing unauthorized privilege escalation via OpenFGA contextual tuples. Dynamic evaluation tuples must always be bound to signed cryptographic proof tokens, bounded by tight lease expirations (sub-second or microsecond epochs), validated against replay attacks, and purged immediately after execution.

## Strict Guidelines
- Engineers MUST NEVER forward client-supplied input directly into OpenFGA contextual_tuples without cryptographic proof verification.
- Services MUST cryptographically sign and verify dynamic contextual assertions (e.g., HMAC-SHA256 or Ed25519) including tenant ID, user identity, resource target, and strict microsecond or millisecond epoch expiration bounds.
- Engineers MUST enforce strict monotonic lease timeouts on contextual tokens (maximum permissible lease <= 5000ms) with clock-skew tolerances not exceeding 250ms.
- Services MUST evaluate contextual tuples only using deterministic, canonicalized tuple definitions with strict schema validation against an internal allowlist of ephemeral relations.
- Code MUST sanitize and strip any persistent database tuple representations from ephemeral contextual sets before calling client.check().
- Services MUST log any rejected, malformed, or expired contextual tuple verification attempt as a high-severity security anomaly.

## Bad vs Good Implementations
### Direct Contextual Tuple Injection vs Cryptographically Fenced Leased Tuples

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Untrusted caller input is passed directly to the contextualTuples parameter of the OpenFGA check. An attacker can construct arbitrary user-object relationships, entirely bypassing store-persisted authorization policies and elevating privileges without verification.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

interface CheckAccessRequest {
  userId: string;
  docId: string;
  relation: string;
  injectedTuples?: Array<{ user: string; relation: string; object: string }>;
}

export async function evaluateAccess(fga: OpenFgaClient, req: CheckAccessRequest): Promise<boolean> {
  // VULNERABILITY: Arbitrary client-provided contextual tuples are passed directly to OpenFGA.
  // An attacker can pass `injectedTuples: [{ user: 'user:attacker', relation: 'owner', object: 'doc:restricted' }]`
  // and achieve instantaneous privilege escalation.
  const { allowed } = await fga.check({
    user: req.userId,
    relation: req.relation,
    object: `doc:${req.docId}`,
    contextualTuples: req.injectedTuples,
  });

  return Boolean(allowed);
}
```

#### Production Standard (Correct)
> **Standard**: Contextual tuples require a cryptographically signed HMAC token containing an exact issued-at and expiration epoch. The token's lease duration is strictly capped at 2,000 milliseconds with tight clock-skew bounds, verified with constant-time equality comparisons, and validated to ensure the subject and object match the target evaluation parameters before invoking OpenFGA.
```typescript
import { OpenFgaClient, ClientTuple } from '@openfga/sdk';
import { createHmac, timingSafeEqual } from 'node:crypto';

interface EphemeralTupleClaim {
  user: `user:${string}`;
  relation: 'ephemeral_viewer' | 'ephemeral_editor';
  object: `doc:${string}`;
  issuedAtMs: number;
  expiresAtMs: number;
  nonce: string;
}

interface FencedAccessRequest {
  userId: `user:${string}`;
  docId: string;
  relation: string;
  signedLeaseToken?: string;
}

const LEASE_SIGNING_SECRET = process.env.FGA_CONTEXTUAL_HMAC_SECRET!;
const MAX_LEASE_DURATION_MS = 2000;
const CLOCK_SKEW_TOLERANCE_MS = 250;

function verifyAndExtractTupleLease(token: string): ClientTuple {
  const [payloadB64, signatureB64] = token.split('.');
  if (!payloadB64 || !signatureB64) {
    throw new Error('Malformed ephemeral lease token format');
  }

  const expectedSig = createHmac('sha256', LEASE_SIGNING_SECRET)
    .update(payloadB64)
    .digest('base64url');

  const sigBuffer = Buffer.from(signatureB64, 'base64url');
  const expectedBuffer = Buffer.from(expectedSig, 'base64url');
  if (sigBuffer.length !== expectedBuffer.length || !timingSafeEqual(sigBuffer, expectedBuffer)) {
    throw new Error('Invalid contextual tuple lease signature');
  }

  const claim = JSON.parse(Buffer.from(payloadB64, 'base64url').toString('utf8')) as EphemeralTupleClaim;
  const now = Date.now();

  if (now > claim.expiresAtMs + CLOCK_SKEW_TOLERANCE_MS) {
    throw new Error('Contextual lease has expired');
  }
  if (claim.issuedAtMs > now + CLOCK_SKEW_TOLERANCE_MS) {
    throw new Error('Contextual lease issued in the future');
  }
  if (claim.expiresAtMs - claim.issuedAtMs > MAX_LEASE_DURATION_MS) {
    throw new Error('Contextual lease duration exceeds permissible threshold');
  }

  return {
    user: claim.user,
    relation: claim.relation,
    object: claim.object,
  };
}

export async function evaluateAccess(fga: OpenFgaClient, req: FencedAccessRequest): Promise<boolean> {
  const contextualTuples: ClientTuple[] = [];

  if (req.signedLeaseToken) {
    const verifiedTuple = verifyAndExtractTupleLease(req.signedLeaseToken);
    if (verifiedTuple.user === req.userId && verifiedTuple.object === `doc:${req.docId}`) {
      contextualTuples.push(verifiedTuple);
    }
  }

  const { allowed } = await fga.check({
    user: req.userId,
    relation: req.relation,
    object: `doc:${req.docId}`,
    contextualTuples,
  });

  return Boolean(allowed);
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA Ephemeral Contextual Tuple Cryptographic Fencing & Lease Enforcement

OpenFGA Ephemeral Contextual Tuple Cryptographic Fencing & Lease Enforcement defines an industrial-grade behavioral standard for backend engineering. Enforces strict cryptographic binding, short-lived epoch lease constraints, and cryptographic signature validation on dynamic contextual tuples evaluated in OpenFGA check queries. Prevents privilege escalation and confused-deputy attacks arising from unauthenticated caller-supplied relationship assertions or tuple replay. Ensures all dynamically ingested tuples are cryptographically verified, deterministic, and isolated to the immediate execution context. 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: Blind Ingestion of Untrusted Dynamic Contextual Tuples into OpenFGA Check Calls 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 DriftBlind Ingestion of Untrusted Dynamic Contextual Tuples into OpenFGA Check CallsCritical
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 forward client-supplied input directly into OpenFGA contextual_tuples without cryptographic proof verification.

Engineers MUST NEVER forward client-supplied input directly into OpenFGA contextual_tuples without cryptographic proof verification.

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

Services MUST cryptographically sign and verify dynamic contextual assertions (e.g., HMAC-SHA256 or Ed25519) including tenant ID, user identity, resource target, and strict microsecond or millisecond epoch expiration bounds.

Services MUST cryptographically sign and verify dynamic contextual assertions (e.g., HMAC-SHA256 or Ed25519) including tenant ID, user identity, resource target, and strict microsecond or millisecond epoch expiration bounds.

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 enforce strict monotonic lease timeouts on contextual tokens (maximum permissible lease <= 5000ms) with clock-skew tolerances not exceeding 250ms.

Engineers MUST enforce strict monotonic lease timeouts on contextual tokens (maximum permissible lease <= 5000ms) with clock-skew tolerances not exceeding 250ms.

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 evaluate contextual tuples only using deterministic, canonicalized tuple definitions with strict schema validation against an internal allowlist of ephemeral relations.

Services MUST evaluate contextual tuples only using deterministic, canonicalized tuple definitions with strict schema validation against an internal allowlist of ephemeral 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.
5

Code MUST sanitize and strip any persistent database tuple representations from ephemeral contextual sets before calling client.check().

Code MUST sanitize and strip any persistent database tuple representations from ephemeral contextual sets before calling client.check().

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.
6

Services MUST log any rejected, malformed, or expired contextual tuple verification attempt as a high-severity security anomaly.

Services MUST log any rejected, malformed, or expired contextual tuple verification attempt as a high-severity security anomaly.

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 Fencing & Lease Enforcement critical for AI coding assistants?

Enforces strict cryptographic binding, short-lived epoch lease constraints, and cryptographic signature validation on dynamic contextual tuples evaluated in OpenFGA check queries. Prevents privilege escalation and confused-deputy attacks arising from unauthenticated caller-supplied relationship assertions or tuple replay. Ensures all dynamically ingested tuples are cryptographically verified, deterministic, and isolated to the immediate execution context. 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 (Blind Ingestion of Untrusted Dynamic Contextual Tuples into OpenFGA Check Calls) 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