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

OpenFGA Ephemeral Contextual Tuple Cryptographic Signature Attestation

Enforces that all ephemeral contextual tuples passed into real-time OpenFGA check evaluations carry verifiable asymmetric cryptographic signatures or tamper-evident claims issued by authorized upstream identity providers or trusted internal token brokers. Prevents caller-side privilege escalation and permission spoofing caused by unvalidated client-supplied tuples dynamically injected into evaluation trees.

Prohibited Anti-Pattern: Trusting raw, unverified client-supplied contextual tuples directly in OpenFGA check queries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Ephemeral Contextual Tuple Cryptographic Signature Attestation - Enforces that all ephemeral contextual tuples passed into real-time OpenFGA check evaluations carry verifiable asymmetric cryptographic signatures or tamper-evident claims issued by authorized upstream identity providers or trusted internal token brokers. Prevents caller-side privilege escalation and permission spoofing caused by unvalidated client-supplied tuples dynamically injected into evaluation trees.
globs: src/**/authz/**/*.ts, src/**/security/**/*.ts, src/**/openfga/**/*.ts, src/**/middleware/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuple-cryptographic-attestation-standard"
---

# OpenFGA Ephemeral Contextual Tuple Cryptographic Signature Attestation

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Trusting raw, unverified client-supplied contextual tuples directly in OpenFGA check queries

## System Constraints
You are a Principal Security Architect enforcing the OpenFGA Contextual Tuple Cryptographic Signature Attestation Standard. Contextual tuples augment the OpenFGA stored relationship model with ephemeral facts at evaluation time. You must prevent caller-side privilege escalation by ensuring that no contextual tuple is forwarded to an OpenFGA Check or BatchCheck API without first validating its cryptographic signature, issuer authenticity, payload digest, and freshness against an authoritative public-key infrastructure (PKI) or trusted assertion service.

## Strict Guidelines
- Engineers MUST ALWAYS verify the asymmetric signature (e.g., Ed25519, ES256) of ephemeral contextual tuple assertions before appending them to OpenFGA Check requests.
- Engineers MUST NOT map raw, untrusted HTTP request parameters, client headers, or unverified JWT claims directly into OpenFGA contextual tuple user, relation, or object fields.
- Code SHOULD enforce strict expiration (exp) and not-before (nbf) validation windows on contextual tuple assertion tokens, restricting TTL to under 60 seconds.
- Services MUST validate that the attested subject inside the cryptographic claim strictly matches the authenticated caller identity and requested resource boundary.
- Components NEVER accept contextual tuples containing wildcard definitions ('*') or unvetted roles ('admin', 'owner') from externally originated attestation payloads.

## Bad vs Good Implementations
### Unsigned Contextual Tuple Injection vs. Cryptographically Attested Contextual Tuple Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Client-supplied parameters are mapped directly into OpenFGA contextual tuples without integrity or origin validation, allowing callers to grant themselves arbitrary relationships and bypass authorization models.
```typescript
import { OpenFgaClient, type ClientCheckRequest } from '@openfga/sdk';
import type { Request, Response } from 'express';

export async function authorizeDocumentAccess(fgaClient: OpenFgaClient, req: Request, res: Response) {
  const { documentId, requestedRelation, ephemeralRole } = req.body;
  const userId = req.user.id;

  // CRITICAL VULNERABILITY: Blindly accepting ephemeral contextual tuples from the client request payload.
  // An attacker can inject { ephemeralRole: 'editor' } or arbitrary tuples to spoof permissions.
  const checkPayload: ClientCheckRequest = {
    user: `user:${userId}`,
    relation: requestedRelation,
    object: `document:${documentId}`,
    contextualTuples: ephemeralRole ? [
      {
        user: `user:${userId}`,
        relation: ephemeralRole,
        object: `document:${documentId}`,
      },
    ] : [],
  };

  const { allowed } = await fgaClient.check(checkPayload);
  return res.json({ allowed });
}
```

#### Production Standard (Correct)
> **Standard**: Contextual tuples require a verifiable cryptographic token signed by an internal authorization broker. The claim's signature, issuer, audience, subject equality, object boundary, and allowed ephemeral relations are strictly asserted before constructing the OpenFGA check request.
```typescript
import { OpenFgaClient, type ClientCheckRequest, type ClientContextualTupleKey } from '@openfga/sdk';
import { importSPKI, jwtVerify } from 'jose';
import type { Request, Response } from 'express';

interface AttestedTupleClaim {
  user: `user:${string}`;
  relation: string;
  object: `document:${string}`;
  nonce: string;
}

const TRUSTED_ISSUER = 'https://authz-broker.internal.domain';
const ALLOWED_EPHEMERAL_RELATIONS = new Set(['viewer_delegate', 'temporary_collaborator']);

export async function authorizeDocumentAccess(fgaClient: OpenFgaClient, req: Request, res: Response) {
  const { documentId, requestedRelation, attestationToken } = req.body;
  const authenticatedUserId = req.user.id;
  const verifiedTuples: ClientContextualTupleKey[] = [];

  if (attestationToken) {
    const publicKey = await importSPKI(process.env.ATTESTATION_PUBLIC_KEY_PEM!, 'ES256');
    const { payload } = await jwtVerify(attestationToken, publicKey, {
      issuer: TRUSTED_ISSUER,
      audience: 'openfga-enforcer',
      clockTolerance: 5,
    });

    const claim = payload as unknown as AttestedTupleClaim;

    if (claim.user !== `user:${authenticatedUserId}`) {
      return res.status(403).json({ error: 'Contextual tuple user mismatch' });
    }
    if (claim.object !== `document:${documentId}`) {
      return res.status(403).json({ error: 'Contextual tuple target resource mismatch' });
    }
    if (!ALLOWED_EPHEMERAL_RELATIONS.has(claim.relation)) {
      return res.status(403).json({ error: 'Disallowed contextual relation specified' });
    }

    verifiedTuples.push({
      user: claim.user,
      relation: claim.relation,
      object: claim.object,
    });
  }

  const checkPayload: ClientCheckRequest = {
    user: `user:${authenticatedUserId}`,
    relation: requestedRelation,
    object: `document:${documentId}`,
    contextualTuples: verifiedTuples,
  };

  const { allowed } = await fgaClient.check(checkPayload);
  return res.json({ allowed: Boolean(allowed) });
}
```

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 Signature Attestation

OpenFGA Ephemeral Contextual Tuple Cryptographic Signature Attestation defines an industrial-grade behavioral standard for security engineering. Enforces that all ephemeral contextual tuples passed into real-time OpenFGA check evaluations carry verifiable asymmetric cryptographic signatures or tamper-evident claims issued by authorized upstream identity providers or trusted internal token brokers. Prevents caller-side privilege escalation and permission spoofing caused by unvalidated client-supplied tuples dynamically injected into evaluation trees. 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: Trusting raw, unverified client-supplied contextual tuples directly in OpenFGA check queries 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 DriftTrusting raw, unverified client-supplied contextual tuples directly in OpenFGA check queriesCritical
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 asymmetric signature (e.g., Ed25519, ES256) of ephemeral contextual tuple assertions before appending them to OpenFGA Check requests.

Engineers MUST ALWAYS verify the asymmetric signature (e.g., Ed25519, ES256) of ephemeral contextual tuple assertions before appending them to OpenFGA Check requests.

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 map raw, untrusted HTTP request parameters, client headers, or unverified JWT claims directly into OpenFGA contextual tuple user, relation, or object fields.

Engineers MUST NOT map raw, untrusted HTTP request parameters, client headers, or unverified JWT claims directly into OpenFGA contextual tuple user, relation, or object fields.

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 enforce strict expiration (exp) and not-before (nbf) validation windows on contextual tuple assertion tokens, restricting TTL to under 60 seconds.

Code SHOULD enforce strict expiration (exp) and not-before (nbf) validation windows on contextual tuple assertion tokens, restricting TTL to under 60 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

Services MUST validate that the attested subject inside the cryptographic claim strictly matches the authenticated caller identity and requested resource boundary.

Services MUST validate that the attested subject inside the cryptographic claim strictly matches the authenticated caller identity and requested resource boundary.

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 accept contextual tuples containing wildcard definitions ('*') or unvetted roles ('admin', 'owner') from externally originated attestation payloads.

Components NEVER accept contextual tuples containing wildcard definitions ('*') or unvetted roles ('admin', 'owner') from externally originated attestation payloads.

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 Signature Attestation critical for AI coding assistants?

Enforces that all ephemeral contextual tuples passed into real-time OpenFGA check evaluations carry verifiable asymmetric cryptographic signatures or tamper-evident claims issued by authorized upstream identity providers or trusted internal token brokers. Prevents caller-side privilege escalation and permission spoofing caused by unvalidated client-supplied tuples dynamically injected into evaluation trees. 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 (Trusting raw, unverified client-supplied contextual tuples directly in OpenFGA check queries) 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