This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: openfga-rebac-mesh-drift-prevention

OpenFGA ReBAC Mesh Edge Authorization and Dual-Write Drift Guardrail

Enforces edge-evaluated OpenFGA authorization checks and transactional relationship tuple synchronization across distributed services. Eliminates authorization drift by preventing ad-hoc SQL privilege checks in downstream microservices and requiring transactional outbox patterns for OpenFGA write-tuple ingestion.

Prohibited Anti-Pattern: Ad-Hoc SQL Role Checks and Dual-Write Tuple Desynchronization

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA ReBAC Mesh Edge Authorization and Dual-Write Drift Guardrail - Enforces edge-evaluated OpenFGA authorization checks and transactional relationship tuple synchronization across distributed services. Eliminates authorization drift by preventing ad-hoc SQL privilege checks in downstream microservices and requiring transactional outbox patterns for OpenFGA write-tuple ingestion.
globs: src/middleware/**/*.{ts,js}, src/auth/**/*.{ts,js}, src/controllers/**/*.{ts,js}, src/services/**/*.{ts,js}, src/events/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-rebac-mesh-drift-prevention"
---

# OpenFGA ReBAC Mesh Edge Authorization and Dual-Write Drift Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Ad-Hoc SQL Role Checks and Dual-Write Tuple Desynchronization

## System Constraints
You are a Principal Security Architect enforcing zero-drift OpenFGA Relationship-Based Access Control (ReBAC) mesh patterns. Mandate that all client-facing requests resolve access decisions through OpenFGA check evaluations at edge or API gateway boundaries before reaching service domains. Prohibit direct authorization queries against relational databases (e.g., SELECT ... WHERE role = 'admin'). Enforce transactional outbox or Change Data Capture (CDC) pipelines for all OpenFGA tuple mutations to eliminate distributed state drift.

## Strict Guidelines
- Engineers MUST evaluate access authorization via OpenFGA 'check' calls at the edge gateway or ingress middleware, passing contextual user and object IDs.
- Engineers MUST NOT execute ad-hoc SQL joins, table role checks, or tenant scoping queries inside domain handlers to infer permissions.
- Services MUST synchronize relationship state to OpenFGA using an ACID-compliant Transactional Outbox pattern or CDC pipeline, never via loose asynchronous dual-writes.
- Code MUST pass client authorization tokens and contextual tuples explicitly to OpenFGA to maintain sub-millisecond edge resolution without querying downstream databases.
- Components NEVER fall back to default-allow behavior upon OpenFGA check failure or timeout; failures MUST fail-closed with HTTP 403 Forbidden.

## Bad vs Good Implementations
### Edge Gateway ReBAC Authorization Resolution

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Querying local relational stores directly bypasses the global OpenFGA authorization model, introduces latency at edge gateways, fails to resolve transitive relationships (e.g., inherited group permissions), and leads to distributed authorization drift.
```typescript
import { Request, Response, NextFunction } from 'express';
import { db } from '../db';

export async function authorizeDocumentAccess(req: Request, res: Response, next: NextFunction) {
  const { userId } = req.user;
  const { documentId } = req.params;

  // ANTI-PATTERN: Direct relational querying for access rights leads to authorization drift,
  // bypasses central ReBAC graph, and creates high database latency across edge regions.
  const membership = await db.query(
    'SELECT role FROM document_members WHERE document_id = $1 AND user_id = $2',
    [documentId, userId]
  );

  if (!membership.rows.length || membership.rows[0].role !== 'viewer') {
    return res.status(403).json({ error: 'Unauthorized' });
  }
  next();
}
```

#### Production Standard (Correct)
> **Standard**: Resolves authorization using the OpenFGA client against the ReBAC graph, respecting complex relational hierarchies and fail-closed security invariants independently of core relational stores.
```typescript
import { Request, Response, NextFunction } from 'express';
import { OpenFgaClient } from '@openfga/sdk';

const fgaClient = new OpenFgaClient({
  apiUrl: process.env.OPENFGA_API_URL!,
  storeId: process.env.OPENFGA_STORE_ID!,
  authorizationModelId: process.env.OPENFGA_MODEL_ID,
});

export async function authorizeDocumentAccess(req: Request, res: Response, next: NextFunction) {
  const { userId } = req.user;
  const { documentId } = req.params;

  try {
    // PRODUCTION INVARIANT: Sub-millisecond graph resolution via ReBAC edge mesh.
    // Evaluates direct, inherited, and contextual relations consistently across all nodes.
    const { allowed } = await fgaClient.check({
      user: `user:${userId}`,
      relation: 'viewer',
      object: `document:${documentId}`
    });

    if (!allowed) {
      return res.status(403).json({ error: 'Access denied: relationship check failed' });
    }

    return next();
  } catch (err) {
    // Fail-closed invariant on mesh connectivity errors
    return res.status(403).json({ error: 'Authorization service unavailable - failing closed' });
  }
}
```

### Transactional Outbox Tuple Synchronization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Dual-writes without transactional coordination create distributed drift. If the network drops or OpenFGA throttles after the database commit, the user has permissions in the relational DB but is denied at the ReBAC edge.
```typescript
import { db } from '../db';
import { OpenFgaClient } from '@openfga/sdk';

const fgaClient = new OpenFgaClient({ apiUrl: process.env.OPENFGA_API_URL! });

export async function assignEditor(documentId: string, targetUserId: string) {
  // ANTI-PATTERN: Direct dual-write. If the OpenFGA call fails after SQL commits,
  // the system enters an unrecoverable authorization drift state.
  await db.query(
    'INSERT INTO document_shares (document_id, user_id, permission) VALUES ($1, $2, $3)',
    [documentId, targetUserId, 'editor']
  );

  await fgaClient.write({
    writes: [{
      user: `user:${targetUserId}`,
      relation: 'editor',
      object: `document:${documentId}`
    }]
  });
}
```

#### Production Standard (Correct)
> **Standard**: Using a transactional outbox table inside the primary database transaction guarantees that relationship tuples are published to OpenFGA via CDC or an outbox worker, eliminating dual-write divergence.
```typescript
import { PoolClient } from 'pg';
import { db } from '../db';

export async function assignEditor(documentId: string, targetUserId: string) {
  const client: PoolClient = await db.connect();
  try {
    await client.query('BEGIN');

    await client.query(
      'INSERT INTO document_shares (document_id, user_id, permission) VALUES ($1, $2, $3)',
      [documentId, targetUserId, 'editor']
    );

    // PRODUCTION INVARIANT: Transactional Outbox pattern guarantees eventual
    // consistency without dual-write race conditions or authorization drift.
    await client.query(
      `INSERT INTO fga_outbox_events (user_tuple, relation, object_tuple, operation) 
       VALUES ($1, $2, $3, 'WRITE')`,
      [`user:${targetUserId}`, 'editor', `document:${documentId}`]
    );

    await client.query('COMMIT');
  } catch (error) {
    await client.query('ROLLBACK');
    throw error;
  } finally {
    client.release();
  }
}
```

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 ReBAC Mesh Edge Authorization and Dual-Write Drift Guardrail

OpenFGA ReBAC Mesh Edge Authorization and Dual-Write Drift Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces edge-evaluated OpenFGA authorization checks and transactional relationship tuple synchronization across distributed services. Eliminates authorization drift by preventing ad-hoc SQL privilege checks in downstream microservices and requiring transactional outbox patterns for OpenFGA write-tuple ingestion. 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: Ad-Hoc SQL Role Checks and Dual-Write Tuple Desynchronization 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 DriftAd-Hoc SQL Role Checks and Dual-Write Tuple DesynchronizationCritical
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 evaluate access authorization via OpenFGA 'check' calls at the edge gateway or ingress middleware, passing contextual user and object IDs.

Engineers MUST evaluate access authorization via OpenFGA 'check' calls at the edge gateway or ingress middleware, passing contextual user and object IDs.

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 ad-hoc SQL joins, table role checks, or tenant scoping queries inside domain handlers to infer permissions.

Engineers MUST NOT execute ad-hoc SQL joins, table role checks, or tenant scoping queries inside domain handlers to infer permissions.

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 synchronize relationship state to OpenFGA using an ACID-compliant Transactional Outbox pattern or CDC pipeline, never via loose asynchronous dual-writes.

Services MUST synchronize relationship state to OpenFGA using an ACID-compliant Transactional Outbox pattern or CDC pipeline, never via loose asynchronous dual-writes.

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

Code MUST pass client authorization tokens and contextual tuples explicitly to OpenFGA to maintain sub-millisecond edge resolution without querying downstream databases.

Code MUST pass client authorization tokens and contextual tuples explicitly to OpenFGA to maintain sub-millisecond edge resolution without querying downstream databases.

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 fall back to default-allow behavior upon OpenFGA check failure or timeout

Components NEVER fall back to default-allow behavior upon OpenFGA check failure or timeout; failures MUST fail-closed with HTTP 403 Forbidden.

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 ReBAC Mesh Edge Authorization and Dual-Write Drift Guardrail critical for AI coding assistants?

Enforces edge-evaluated OpenFGA authorization checks and transactional relationship tuple synchronization across distributed services. Eliminates authorization drift by preventing ad-hoc SQL privilege checks in downstream microservices and requiring transactional outbox patterns for OpenFGA write-tuple ingestion. 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 (Ad-Hoc SQL Role Checks and Dual-Write Tuple Desynchronization) 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