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

OpenFGA Monotonic Snapshot & Contextual Tuple Consistency Guardrail

Enforces strict monotonic snapshot barriers and contextual tuple reconciliation across OpenFGA authorization checks to prevent the New Enemy vulnerability and unauthorized stale read-after-write evaluations. Mandates explicit consistency constraints and temporal validation across distributed authorization checks.

Prohibited Anti-Pattern: Stale Replica Evaluations and Unbounded Contextual Tuples in Read-After-Write Paths

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Monotonic Snapshot & Contextual Tuple Consistency Guardrail - Enforces strict monotonic snapshot barriers and contextual tuple reconciliation across OpenFGA authorization checks to prevent the New Enemy vulnerability and unauthorized stale read-after-write evaluations. Mandates explicit consistency constraints and temporal validation across distributed authorization checks.
globs: src/**/authz/**/*.ts, src/**/services/**/*.ts, src/**/guards/**/*.ts, src/**/middleware/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-contextual-tuples-consistency-barrier"
---

# OpenFGA Monotonic Snapshot & Contextual Tuple Consistency Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Stale Replica Evaluations and Unbounded Contextual Tuples in Read-After-Write Paths

## System Constraints
You are a Principal Security Architect enforcing Zanzibar consistency guarantees and OpenFGA monotonic clock barriers. Mandate that all dynamic authorization evaluations occurring within read-after-write lifecycles explicitly specify consistency preferences, pass validated contextual tuples, and prohibit uncoordinated stale checks against distributed replica nodes.

## Strict Guidelines
- Engineers MUST ALWAYS set `consistency: ConsistencyPreference.HIGHER_CONSISTENCY` (or provide snapshot revision tokens) during authorization evaluations immediately following permission mutations or revocation events.
- Engineers MUST NOT evaluate authorization using ephemeral client-supplied contextual tuples without cryptographically signing or monotonically validating timestamps against server authority.
- Code SHOULD enforce idempotency and deterministic snapshot sequencing when serializing write-tuple commits and subsequent check evaluations.
- Services MUST reconcile distributed replica lag by propagating write tokens across service boundaries via distributed tracing context headers (e.g., W3C Baggage).
- Components NEVER rely on default eventual consistency checks for sensitive data-mutation boundaries or post-revocation verification flows.

## Bad vs Good Implementations
### Enforcing Consistency Barriers and Monotonic Contextual Tuples

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Executing OpenFGA checks without a consistency preference defaults to eventual consistency, allowing stale read replicas to grant access to recently revoked entities (the classic Zanzibar 'New Enemy' flaw). Ephemeral contextual tuples lack monotonic timestamps, enabling replay and out-of-order evaluations.
```typescript
// VULNERABLE: Default eventual consistency check permits 'New Enemy' race conditions
// and contextual tuples are accepted without temporal bounding or consistency barrier.
import { OpenFgaClient } from "@openfga/sdk";

export async function evaluateAccess(
  fga: OpenFgaClient,
  userId: string,
  docId: string,
  ipAddress: string
): Promise<boolean> {
  // Anti-pattern: Mutating relation and immediately checking with MINIMAL_CONSISTENCY (default)
  const result = await fga.check({
    user: `user:${userId}`,
    relation: "viewer",
    object: `document:${docId}`,
    contextualTuples: [
      {
        user: `user:${userId}`,
        relation: "device_session",
        object: `ip:${ipAddress}`
      }
    ]
  });

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

#### Production Standard (Correct)
> **Standard**: By explicitly configuring `ConsistencyPreference.HIGHER_CONSISTENCY`, the client enforces an upstream monotonic consistency barrier against OpenFGA replicas. Contextual tuples and context objects include monotonic time validations, fully eliminating read-after-write privilege leakage.
```typescript
// SECURE: Enforces ConsistencyPreference.HIGHER_CONSISTENCY, validates clock skew,
// and bounds contextual tuples using cryptographically verified temporal barriers.
import { OpenFgaClient, ConsistencyPreference, ClientCheckRequest } from "@openfga/sdk";

export interface SecureCheckParams {
  userId: string;
  docId: string;
  ipAddress: string;
  sessionExpiresAtMs: number;
  serverMonotonicEpochMs: number;
}

export async function evaluateAccess(
  fga: OpenFgaClient,
  params: SecureCheckParams
): Promise<boolean> {
  const nowMs = Date.now();

  // Guard against clock skew and expired dynamic claims
  if (params.sessionExpiresAtMs <= nowMs || params.serverMonotonicEpochMs > nowMs + 1000) {
    return false;
  }

  const checkRequest: ClientCheckRequest = {
    user: `user:${params.userId}`,
    relation: "viewer",
    object: `document:${params.docId}`,
    consistency: ConsistencyPreference.HIGHER_CONSISTENCY,
    contextualTuples: [
      {
        user: `user:${params.userId}`,
        relation: "active_network",
        object: `network:${params.ipAddress}`
      }
    ],
    context: {
      current_time: new Date(nowMs).toISOString(),
      monotonic_reference: params.serverMonotonicEpochMs
    }
  };

  const result = await fga.check(checkRequest);
  return result.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 Monotonic Snapshot & Contextual Tuple Consistency Guardrail

OpenFGA Monotonic Snapshot & Contextual Tuple Consistency Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces strict monotonic snapshot barriers and contextual tuple reconciliation across OpenFGA authorization checks to prevent the New Enemy vulnerability and unauthorized stale read-after-write evaluations. Mandates explicit consistency constraints and temporal validation across distributed authorization checks. 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: Stale Replica Evaluations and Unbounded Contextual Tuples in Read-After-Write Paths 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 DriftStale Replica Evaluations and Unbounded Contextual Tuples in Read-After-Write PathsCritical
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 set `consistency

Engineers MUST ALWAYS set `consistency: ConsistencyPreference.HIGHER_CONSISTENCY` (or provide snapshot revision tokens) during authorization evaluations immediately following permission mutations or revocation events.

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 evaluate authorization using ephemeral client-supplied contextual tuples without cryptographically signing or monotonically validating timestamps against server authority.

Engineers MUST NOT evaluate authorization using ephemeral client-supplied contextual tuples without cryptographically signing or monotonically validating timestamps against server authority.

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 idempotency and deterministic snapshot sequencing when serializing write-tuple commits and subsequent check evaluations.

Code SHOULD enforce idempotency and deterministic snapshot sequencing when serializing write-tuple commits and subsequent check evaluations.

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 reconcile distributed replica lag by propagating write tokens across service boundaries via distributed tracing context headers (e.g., W3C Baggage).

Services MUST reconcile distributed replica lag by propagating write tokens across service boundaries via distributed tracing context headers (e.g., W3C Baggage).

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 rely on default eventual consistency checks for sensitive data-mutation boundaries or post-revocation verification flows.

Components NEVER rely on default eventual consistency checks for sensitive data-mutation boundaries or post-revocation verification flows.

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 Monotonic Snapshot & Contextual Tuple Consistency Guardrail critical for AI coding assistants?

Enforces strict monotonic snapshot barriers and contextual tuple reconciliation across OpenFGA authorization checks to prevent the New Enemy vulnerability and unauthorized stale read-after-write evaluations. Mandates explicit consistency constraints and temporal validation across distributed authorization checks. 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 (Stale Replica Evaluations and Unbounded Contextual Tuples in Read-After-Write Paths) 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