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

Mandatory Cryptographic Verification for Ephemeral OpenFGA Contextual Tuples

Enforces asymmetric Ed25519 or HMAC-SHA256 signature verification on all client-provided contextual tuples before passing them to OpenFGA check evaluations. Unsigned or arbitrary contextual claims allow untrusted clients to synthesize ad-hoc relationship assertions (e.g., dynamic roles, tenant elevation) and bypass fine-grained access control boundaries.

Prohibited Anti-Pattern: Injecting Untrusted Client-Supplied Contextual Tuples Directly into OpenFGA Check Calls

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Mandatory Cryptographic Verification for Ephemeral OpenFGA Contextual Tuples - Enforces asymmetric Ed25519 or HMAC-SHA256 signature verification on all client-provided contextual tuples before passing them to OpenFGA check evaluations. Unsigned or arbitrary contextual claims allow untrusted clients to synthesize ad-hoc relationship assertions (e.g., dynamic roles, tenant elevation) and bypass fine-grained access control boundaries.
globs: src/auth/**/*.ts, src/middleware/**/*.ts, src/services/fga/**/*.ts, src/guards/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-signed-contextual-tuples-invariant"
---

# Mandatory Cryptographic Verification for Ephemeral OpenFGA Contextual Tuples

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Injecting Untrusted Client-Supplied Contextual Tuples Directly into OpenFGA Check Calls

## System Constraints
You are a Principal Security Architect enforcing the OpenFGA Cryptographically Signed Contextual Tuple Invariant. Mandate that any dynamic, ephemeral, or request-scoped tuple submitted to an OpenFGA Check evaluation is cryptographically authenticated via an asymmetric public key (Ed25519) or trusted identity broker HMAC signature before reaching the OpenFGA client SDK. Reject all unauthenticated client-provided claims immediately.

## Strict Guidelines
- Services MUST NEVER accept arbitrary tuple primitives (`user`, `relation`, `object`) directly from untrusted HTTP headers, query parameters, or request bodies into OpenFGA `check({ contextual_tuples })`.
- Engineers MUST encapsulate dynamic context into cryptographically signed claims tokens (e.g., PASETO v4.public, Ed25519-signed JWTs, or HMAC-SHA256 envelopes) minted strictly by authoritative upstream services.
- Services MUST verify the cryptographic signature, expiration timestamp (`exp`), audience (`aud`), and nonce of the contextual tuple payload before constructing the `ClientContextualTupleKeys` array.
- Engineers MUST enforce strict schema allowlists on the relation and object namespaces allowed within contextual claims, preventing unexpected cross-namespace permission escalations.
- Components NEVER execute fallback mechanisms that strip signatures or ignore expired ephemeral tuple proofs during network partitions or verification errors.

## Bad vs Good Implementations
### Unvalidated Contextual Tuples vs. Cryptographically Verified Context Envelope

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly mapping arbitrary client-supplied JSON objects to contextual_tuples enables privilege escalation. A malicious caller can declare themselves an owner, editor, or bypasser of any resource without server-side validation or origin proof.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { Request, Response } from 'express';

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

export async function authorizeDocumentAccess(req: Request, res: Response) {
  const { documentId } = req.params;
  // CRITICAL VULNERABILITY: Client passes raw contextual tuples from the request body.
  // An attacker can inject: { user: 'user:attacker', relation: 'owner', object: `doc:${documentId}` }
  const { ephemeralTuples } = req.body;

  const { allowed } = await fgaClient.check({
    user: `user:${req.user.id}`,
    relation: 'can_view',
    object: `doc:${documentId}`,
    contextual_tuples: ephemeralTuples,
  });

  if (!allowed) {
    return res.status(403).json({ error: 'Forbidden' });
  }
  return res.json({ status: 'ok' });
}
```

#### Production Standard (Correct)
> **Standard**: Validates the authenticity and integrity of contextual tuples using Ed25519 asymmetric signature checks. Asserts expiry windows, confines relations to a strict allowlist, and guarantees that claims match the exact target entity.
```typescript
import { OpenFgaClient, ClientTupleKey } from '@openfga/sdk';
import { Request, Response } from 'express';
import * as crypto from 'node:crypto';

interface SignedTupleClaim {
  tuples: ClientTupleKey[];
  exp: number;
  aud: string;
  nonce: string;
}

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

const TRUSTED_AUTH_PUBLIC_KEY = crypto.createPublicKey(process.env.EPHEMERAL_ISSUER_PUBLIC_KEY!);

function verifyAndExtractSignedTuples(
  signedPayload: string,
  signatureBase64: string,
  expectedTarget: string
): ClientTupleKey[] {
  const isVerified = crypto.verify(
    null,
    Buffer.from(signedPayload, 'utf-8'),
    TRUSTED_AUTH_PUBLIC_KEY,
    Buffer.from(signatureBase64, 'base64url')
  );

  if (!isVerified) {
    throw new Error('Contextual claim signature verification failed');
  }

  const claim = JSON.parse(signedPayload) as SignedTupleClaim;

  if (Date.now() >= claim.exp * 1000) {
    throw new Error('Contextual claim has expired');
  }

  for (const tuple of claim.tuples) {
    if (tuple.object !== expectedTarget) {
      throw new Error(`Contextual tuple object mismatch: expected ${expectedTarget}, got ${tuple.object}`);
    }
    if (!['temporary_reviewer', 'invited_guest'].includes(tuple.relation)) {
      throw new Error(`Disallowed relation in contextual claim: ${tuple.relation}`);
    }
  }

  return claim.tuples;
}

export async function authorizeDocumentAccess(req: Request, res: Response) {
  const { documentId } = req.params;
  const targetObject = `doc:${documentId}`;
  let verifiedTuples: ClientTupleKey[] = [];

  const claimPayload = req.headers['x-ephemeral-context-payload'];
  const claimSig = req.headers['x-ephemeral-context-signature'];

  if (claimPayload && claimSig) {
    try {
      verifiedTuples = verifyAndExtractSignedTuples(
        String(claimPayload),
        String(claimSig),
        targetObject
      );
    } catch (err) {
      return res.status(401).json({ error: 'Invalid or forged contextual claims' });
    }
  }

  const { allowed } = await fgaClient.check({
    user: `user:${req.user.id}`,
    relation: 'can_view',
    object: targetObject,
    contextual_tuples: verifiedTuples,
  });

  if (!allowed) {
    return res.status(403).json({ error: 'Forbidden' });
  }
  return res.json({ status: 'ok' });
}
```

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: Mandatory Cryptographic Verification for Ephemeral OpenFGA Contextual Tuples

Mandatory Cryptographic Verification for Ephemeral OpenFGA Contextual Tuples defines an industrial-grade behavioral standard for security engineering. Enforces asymmetric Ed25519 or HMAC-SHA256 signature verification on all client-provided contextual tuples before passing them to OpenFGA check evaluations. Unsigned or arbitrary contextual claims allow untrusted clients to synthesize ad-hoc relationship assertions (e.g., dynamic roles, tenant elevation) and bypass fine-grained access control 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 Untrusted Client-Supplied Contextual Tuples Directly 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 DriftInjecting Untrusted Client-Supplied Contextual Tuples Directly 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

Services MUST NEVER accept arbitrary tuple primitives (`user`, `relation`, `object`) directly from untrusted HTTP headers, query parameters, or request bodies into OpenFGA `check({ contextual_tuples })`.

Services MUST NEVER accept arbitrary tuple primitives (`user`, `relation`, `object`) directly from untrusted HTTP headers, query parameters, or request bodies into OpenFGA `check({ 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 encapsulate dynamic context into cryptographically signed claims tokens (e.g., PASETO v4.public, Ed25519-signed JWTs, or HMAC-SHA256 envelopes) minted strictly by authoritative upstream services.

Engineers MUST encapsulate dynamic context into cryptographically signed claims tokens (e.g., PASETO v4.public, Ed25519-signed JWTs, or HMAC-SHA256 envelopes) minted strictly by authoritative upstream services.

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 verify the cryptographic signature, expiration timestamp (`exp`), audience (`aud`), and nonce of the contextual tuple payload before constructing the `ClientContextualTupleKeys` array.

Services MUST verify the cryptographic signature, expiration timestamp (`exp`), audience (`aud`), and nonce of the contextual tuple payload before constructing the `ClientContextualTupleKeys` array.

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

Engineers MUST enforce strict schema allowlists on the relation and object namespaces allowed within contextual claims, preventing unexpected cross-namespace permission escalations.

Engineers MUST enforce strict schema allowlists on the relation and object namespaces allowed within contextual claims, preventing unexpected cross-namespace permission escalations.

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 execute fallback mechanisms that strip signatures or ignore expired ephemeral tuple proofs during network partitions or verification errors.

Components NEVER execute fallback mechanisms that strip signatures or ignore expired ephemeral tuple proofs during network partitions or verification errors.

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 Mandatory Cryptographic Verification for Ephemeral OpenFGA Contextual Tuples critical for AI coding assistants?

Enforces asymmetric Ed25519 or HMAC-SHA256 signature verification on all client-provided contextual tuples before passing them to OpenFGA check evaluations. Unsigned or arbitrary contextual claims allow untrusted clients to synthesize ad-hoc relationship assertions (e.g., dynamic roles, tenant elevation) and bypass fine-grained access control 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 Untrusted Client-Supplied Contextual Tuples Directly 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

Mandatory