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

OpenFGA Consistency Token Propagation Barrier for Distributed Edge Mutation Guardrails

Enforces strict read-after-write authorization consistency across distributed edge microservices interacting with OpenFGA or Google Zanzibar implementations. Mandates extracting, validating, and propagating the `consistency_token` (Zookiez/continuation token) across asynchronous message buses and edge boundaries before executing state mutations or subsequent access evaluations. Prevents the New Enemy Problem and stale authorization cache vulnerabilities in multi-region deployments.

Prohibited Anti-Pattern: Executing edge mutations or checks using eventually consistent OpenFGA reads without propagated snapshot consistency tokens

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Consistency Token Propagation Barrier for Distributed Edge Mutation Guardrails - Enforces strict read-after-write authorization consistency across distributed edge microservices interacting with OpenFGA or Google Zanzibar implementations. Mandates extracting, validating, and propagating the `consistency_token` (Zookiez/continuation token) across asynchronous message buses and edge boundaries before executing state mutations or subsequent access evaluations. Prevents the New Enemy Problem and stale authorization cache vulnerabilities in multi-region deployments.
globs: src/**/middleware/**/*.{ts,js}, src/**/auth/**/*.{ts,js}, src/**/services/**/*.{ts,js}, src/**/consumers/**/*.{ts,js}, src/**/controllers/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-zanzibar-consistency-token-propagation-barrier"
---

# OpenFGA Consistency Token Propagation Barrier for Distributed Edge Mutation Guardrails

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Executing edge mutations or checks using eventually consistent OpenFGA reads without propagated snapshot consistency tokens

## System Constraints
You are a Principal Security Architect enforcing Zanzibar consistency token barriers in distributed microservices. In OpenFGA/Zanzibar systems, mutations to relations emit a consistency token (continuation/Zookie token). Calling services and edge nodes MUST pass this token in the `consistency` parameter with `HIGHER_CONSISTENCY` or `AT_LEAST_AS_FRESH` semantics for any subsequent mutation or critical check. Failure to do so allows the 'New Enemy Problem', where revoked access permits unauthorized writes due to replication lag across edge clusters. Block any code where write operations or subsequent authorization checks discard or omit the consistency token returned from prior writes.

## Strict Guidelines
- Services MUST extract the OpenFGA `consistency_token` returned by `client.write()` and attach it to downstream execution contexts, HTTP headers (`X-OpenFGA-Consistency-Token`), or messaging payloads.
- Engineers MUST ALWAYS configure OpenFGA `check()` calls that guard critical mutations to use `ConsistencyPreference.HIGHER_CONSISTENCY` along with the upstream request's propagated `consistency_token`.
- Engineers MUST NOT rely on default `ConsistencyPreference.UNSPECIFIED` or `MINIMIZE_LATENCY` when authorizing state mutations or access revocations.
- Edge gateway and messaging consumers MUST halt execution and throw a `412 Precondition Failed` or re-queue the message if a required mutation sequence is missing the upstream consistency barrier token.
- Services MUST serialize the consistency token into trace baggage (W3C Baggage / OpenTelemetry) to preserve authorization context across asynchronous distributed message broker hops.

## Bad vs Good Implementations
### Enforcing Consistency Token Barrier in Edge Mutation Controller

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The check call uses default consistency parameters and ignores the consistency token from previous operations. In a distributed multi-region edge setup, an immediate read-after-write (such as removing a compromised user) will evaluate to stale data due to replication lag, enabling the 'New Enemy Problem'.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { Request, Response } from 'express';

export async function updateResourceController(req: Request, res: Response, fgaClient: OpenFgaClient) {
  // VULNERABLE: Omits consistency token and relies on stale local edge replica
  const isAllowed = await fgaClient.check({
    user: `user:${req.userId}`,
    relation: 'editor',
    object: `document:${req.params.id}`,
  });

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

  // Mutation proceeds despite possible stale revocation
  await updateDatabase(req.params.id, req.body);
  return res.status(200).json({ success: true });
}
```

#### Production Standard (Correct)
> **Standard**: The authorization check explicitly sets HIGHER_CONSISTENCY, validates against the propagated upstream token, and emits the latest consistency token in the response header, guaranteeing linearizable authorization consistency across the distributed edge.
```typescript
import { OpenFgaClient, ConsistencyPreference } from '@openfga/sdk';
import { Request, Response } from 'express';

export async function updateResourceController(req: Request, res: Response, fgaClient: OpenFgaClient) {
  const upstreamToken = req.headers['x-openfga-consistency-token'] as string | undefined;

  // SECURE: Enforce barrier using HIGHER_CONSISTENCY and upstream consistency token
  const checkResult = await fgaClient.check({
    user: `user:${req.userId}`,
    relation: 'editor',
    object: `document:${req.params.id}`,
    consistency: ConsistencyPreference.HIGHER_CONSISTENCY,
  }, {
    consistencyToken: upstreamToken,
  });

  if (!checkResult.allowed) {
    return res.status(403).json({ error: 'Access denied: authorization condition not satisfied' });
  }

  const dbResult = await updateDatabase(req.params.id, req.body);

  // Propagate newest consistency token generated during audit write or relation sync
  const writeResult = await fgaClient.write({
    writes: [{ user: `user:${req.userId}`, relation: 'last_editor', object: `document:${req.params.id}` }]
  });

  res.setHeader('X-OpenFGA-Consistency-Token', writeResult.continuation_token ?? checkResult.resolution);
  return res.status(200).json({ success: true, data: dbResult });
}
```

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA Consistency Token Propagation Barrier for Distributed Edge Mutation Guardrails

OpenFGA Consistency Token Propagation Barrier for Distributed Edge Mutation Guardrails defines an industrial-grade behavioral standard for security engineering. Enforces strict read-after-write authorization consistency across distributed edge microservices interacting with OpenFGA or Google Zanzibar implementations. Mandates extracting, validating, and propagating the `consistency_token` (Zookiez/continuation token) across asynchronous message buses and edge boundaries before executing state mutations or subsequent access evaluations. Prevents the New Enemy Problem and stale authorization cache vulnerabilities in multi-region deployments. 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: Executing edge mutations or checks using eventually consistent OpenFGA reads without propagated snapshot consistency tokens 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 DriftExecuting edge mutations or checks using eventually consistent OpenFGA reads without propagated snapshot consistency tokensCritical
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 extract the OpenFGA `consistency_token` returned by `client.write()` and attach it to downstream execution contexts, HTTP headers (`X-OpenFGA-Consistency-Token`), or messaging payloads.

Services MUST extract the OpenFGA `consistency_token` returned by `client.write()` and attach it to downstream execution contexts, HTTP headers (`X-OpenFGA-Consistency-Token`), or messaging 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.
2

Engineers MUST ALWAYS configure OpenFGA `check()` calls that guard critical mutations to use `ConsistencyPreference.HIGHER_CONSISTENCY` along with the upstream request's propagated `consistency_token`.

Engineers MUST ALWAYS configure OpenFGA `check()` calls that guard critical mutations to use `ConsistencyPreference.HIGHER_CONSISTENCY` along with the upstream request's propagated `consistency_token`.

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 NOT rely on default `ConsistencyPreference.UNSPECIFIED` or `MINIMIZE_LATENCY` when authorizing state mutations or access revocations.

Engineers MUST NOT rely on default `ConsistencyPreference.UNSPECIFIED` or `MINIMIZE_LATENCY` when authorizing state mutations or access revocations.

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

Edge gateway and messaging consumers MUST halt execution and throw a `412 Precondition Failed` or re-queue the message if a required mutation sequence is missing the upstream consistency barrier token.

Edge gateway and messaging consumers MUST halt execution and throw a `412 Precondition Failed` or re-queue the message if a required mutation sequence is missing the upstream consistency barrier token.

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

Services MUST serialize the consistency token into trace baggage (W3C Baggage / OpenTelemetry) to preserve authorization context across asynchronous distributed message broker hops.

Services MUST serialize the consistency token into trace baggage (W3C Baggage / OpenTelemetry) to preserve authorization context across asynchronous distributed message broker hops.

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 Consistency Token Propagation Barrier for Distributed Edge Mutation Guardrails critical for AI coding assistants?

Enforces strict read-after-write authorization consistency across distributed edge microservices interacting with OpenFGA or Google Zanzibar implementations. Mandates extracting, validating, and propagating the `consistency_token` (Zookiez/continuation token) across asynchronous message buses and edge boundaries before executing state mutations or subsequent access evaluations. Prevents the New Enemy Problem and stale authorization cache vulnerabilities in multi-region deployments. 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 (Executing edge mutations or checks using eventually consistent OpenFGA reads without propagated snapshot consistency tokens) 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