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

OpenFGA Contextual Tuples Dynamic Evaluation Boundary

Mandates that ephemeral, request-scoped, and high-churn attributes are injected exclusively via contextual tuples during the OpenFGA check call rather than written to persistent relational Zanzibar storage. Persisting transient state induces severe write amplification, cache invalidation storms, and race conditions that breach sub-millisecond authorization SLOs. Enforces an immutable architectural boundary separating persistent relationship graphs from runtime dynamic context.

Prohibited Anti-Pattern: Persisting Ephemeral Request Context via WriteTuples Prior to Check Evaluation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Contextual Tuples Dynamic Evaluation Boundary - Mandates that ephemeral, request-scoped, and high-churn attributes are injected exclusively via contextual tuples during the OpenFGA check call rather than written to persistent relational Zanzibar storage. Persisting transient state induces severe write amplification, cache invalidation storms, and race conditions that breach sub-millisecond authorization SLOs. Enforces an immutable architectural boundary separating persistent relationship graphs from runtime dynamic context.
globs: src/**/*.ts, src/**/*.service.ts, src/**/authz/**/*.ts, src/**/guards/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuples-dynamic-boundary"
---

# OpenFGA Contextual Tuples Dynamic Evaluation Boundary

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Persisting Ephemeral Request Context via WriteTuples Prior to Check Evaluation

## System Constraints
You are a Principal Security Architect enforcing the OpenFGA Contextual Tuples Dynamic Evaluation Boundary. Mandate that ephemeral runtime conditions (e.g., temporary delegations, dynamic IP matches, ephemeral time bounds, one-time execution claims) are never persisted to the OpenFGA storage engine via write operations. Instead, enforce injection via contextual tuples directly into check requests, guaranteeing sub-millisecond evaluation without storage write latency, changelog pollution, or distributed race conditions.

## Strict Guidelines
- Engineers MUST ALWAYS pass dynamic, ephemeral, or high-frequency changing state using the `contextual_tuples` parameter or dynamic `context` attributes directly inside `client.check()`.
- Engineers MUST NOT execute a write-check-delete transaction lifecycle (persisting tuples to storage immediately before checking and deleting immediately after).
- Code SHOULD sanitize and strictly validate runtime claims (e.g., JWT signatures, step-up MFA proofs) before constructing contextual tuples for authorization evaluation.
- Services MUST ensure that only durable domain relationships (e.g., org membership, role assignments, document ownership) are written to persistent OpenFGA storage.
- Components NEVER leak client-controlled or unverified headers directly into contextual tuples without cryptographic verification at the boundary.

## Bad vs Good Implementations
### Dynamic Ephemeral Authorization: Anti-Pattern vs Contextual Tuples

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Writing transient context directly to OpenFGA storage introduces write latency, bloats the changelog, triggers global cache invalidation, and fails to handle cleanup when crashes occur between write and delete operations.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

interface DynamicAuthRequest {
  userId: string;
  resourceId: string;
  temporaryProjectId: string;
}

export async function evaluateAccessBad(
  fgaClient: OpenFgaClient,
  request: DynamicAuthRequest
): Promise<boolean> {
  const tempTuple = {
    user: `user:${request.userId}`,
    relation: 'temporary_member',
    object: `project:${request.temporaryProjectId}`,
  };

  // ANTI-PATTERN: Writing high-churn ephemeral tuple directly to the persistent store
  await fgaClient.write({
    writes: [tempTuple],
  });

  try {
    const response = await fgaClient.check({
      user: `user:${request.userId}`,
      relation: 'can_read',
      object: `document:${request.resourceId}`,
    });
    return response.allowed ?? false;
  } finally {
    // Cleanup creates write-amplification, race conditions, and cache thrashing
    await fgaClient.write({
      deletes: [tempTuple],
    });
  }
}
```

#### Production Standard (Correct)
> **Standard**: Contextual tuples are evaluated strictly in-memory during the query graph traversal without writing to disk or the relational database. This preserves sub-millisecond evaluation latency, prevents cache invalidation storms, and avoids orphan tuples.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

interface DynamicAuthRequest {
  userId: string;
  resourceId: string;
  temporaryProjectId: string;
  verifiedClaimExpiry: number;
}

export async function evaluateAccessGood(
  fgaClient: OpenFgaClient,
  request: DynamicAuthRequest
): Promise<boolean> {
  const nowEpoch = Math.floor(Date.now() / 1000);
  if (request.verifiedClaimExpiry < nowEpoch) {
    return false;
  }

  // PRODUCTION INVARIANT: Inject ephemeral runtime state via contextual tuples directly in memory
  const response = await fgaClient.check({
    user: `user:${request.userId}`,
    relation: 'can_read',
    object: `document:${request.resourceId}`,
    contextualTuples: [
      {
        user: `user:${request.userId}`,
        relation: 'temporary_member',
        object: `project:${request.temporaryProjectId}`,
      },
    ],
    context: {
      current_time: new Date().toISOString(),
    },
  });

  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 Contextual Tuples Dynamic Evaluation Boundary

OpenFGA Contextual Tuples Dynamic Evaluation Boundary defines an industrial-grade behavioral standard for security engineering. Mandates that ephemeral, request-scoped, and high-churn attributes are injected exclusively via contextual tuples during the OpenFGA check call rather than written to persistent relational Zanzibar storage. Persisting transient state induces severe write amplification, cache invalidation storms, and race conditions that breach sub-millisecond authorization SLOs. Enforces an immutable architectural boundary separating persistent relationship graphs from runtime dynamic 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: Persisting Ephemeral Request Context via WriteTuples Prior to Check Evaluation 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 Ephemeral Request Context via WriteTuples Prior to Check EvaluationCritical
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 pass dynamic, ephemeral, or high-frequency changing state using the `contextual_tuples` parameter or dynamic `context` attributes directly inside `client.check()`.

Engineers MUST ALWAYS pass dynamic, ephemeral, or high-frequency changing state using the `contextual_tuples` parameter or dynamic `context` attributes directly inside `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.
2

Engineers MUST NOT execute a write-check-delete transaction lifecycle (persisting tuples to storage immediately before checking and deleting immediately after).

Engineers MUST NOT execute a write-check-delete transaction lifecycle (persisting tuples to storage immediately before checking and deleting immediately after).

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 sanitize and strictly validate runtime claims (e.g., JWT signatures, step-up MFA proofs) before constructing contextual tuples for authorization evaluation.

Code SHOULD sanitize and strictly validate runtime claims (e.g., JWT signatures, step-up MFA proofs) before constructing contextual tuples for authorization evaluation.

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 ensure that only durable domain relationships (e.g., org membership, role assignments, document ownership) are written to persistent OpenFGA storage.

Services MUST ensure that only durable domain relationships (e.g., org membership, role assignments, document ownership) are written to persistent OpenFGA storage.

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 leak client-controlled or unverified headers directly into contextual tuples without cryptographic verification at the boundary.

Components NEVER leak client-controlled or unverified headers directly into contextual tuples without cryptographic verification at the 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is OpenFGA Contextual Tuples Dynamic Evaluation Boundary critical for AI coding assistants?

Mandates that ephemeral, request-scoped, and high-churn attributes are injected exclusively via contextual tuples during the OpenFGA check call rather than written to persistent relational Zanzibar storage. Persisting transient state induces severe write amplification, cache invalidation storms, and race conditions that breach sub-millisecond authorization SLOs. Enforces an immutable architectural boundary separating persistent relationship graphs from runtime dynamic 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 (Persisting Ephemeral Request Context via WriteTuples Prior to Check Evaluation) 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