This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: openfga-rebac-graph-integrity-and-context-verification

OpenFGA Graph Invariants: Cyclic Relation Prevention & Contextual Tuple Hardening

Enforces strict directed acyclic graph (DAG) topology validation during relationship mutation writes and mandates strict server-side schema verification for ephemeral contextual tuples in OpenFGA evaluations. Prohibits persistent storage of ephemeral request attributes and guards against recursive relation loops causing graph expansion denial-of-service.

Prohibited Anti-Pattern: Persisting Ephemeral Request State as Store Tuples and Unvalidated Cyclic Parent-Child Relationship Writes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Graph Invariants: Cyclic Relation Prevention & Contextual Tuple Hardening - Enforces strict directed acyclic graph (DAG) topology validation during relationship mutation writes and mandates strict server-side schema verification for ephemeral contextual tuples in OpenFGA evaluations. Prohibits persistent storage of ephemeral request attributes and guards against recursive relation loops causing graph expansion denial-of-service.
globs: src/authz/**/*.ts, src/services/authz/**/*.ts, src/lib/openfga/**/*.ts, src/controllers/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-rebac-graph-integrity-and-context-verification"
---

# OpenFGA Graph Invariants: Cyclic Relation Prevention & Contextual Tuple Hardening

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Persisting Ephemeral Request State as Store Tuples and Unvalidated Cyclic Parent-Child Relationship Writes

## System Constraints
You are a Principal Engineer enforcing OpenFGA Relationship-Based Access Control (ReBAC). Mandate strict DAG topology validation on relationship writes to prevent recursive graph expansion and cyclic denial-of-service. Enforce cryptographic or strict server-side validation of contextual tuples in OpenFGA check evaluations, prohibiting the persistence of short-lived ABAC-style claims into durable store tuple storage.

## Strict Guidelines
- Engineers MUST ALWAYS run an acyclic pre-check query (e.g., verifying child does not already reach parent via transitive relation) prior to committing hierarchical relationship tuples into OpenFGA.
- Engineers MUST NOT persist ephemeral, session-bound, or time-sensitive claims (e.g., IP address, step-up MFA, request timestamp) as durable tuples in the OpenFGA store; these MUST be injected exclusively as transient contextual tuples or dynamic context objects during `check` calls.
- Code MUST sanitize, type-check, and cryptographically verify client-originated data before transcribing it into `contextual_tuples` or `context` parameters during OpenFGA `check` or `expand` calls.
- Services MUST enforce strict idempotency and atomic transactional semantics (via OpenFGA conditional tuples or application-level read-locks) when issuing tuple mutations to eliminate race conditions in graph updates.
- Components NEVER construct OpenFGA user strings (`type:id#relation`) or object strings (`type:id`) using unchecked string interpolation without validating that IDs conform to strict alphanumeric patterns and do not contain delimiter injection characters (`:`, `#`, `@`).

## Bad vs Good Implementations
### Unchecked Cyclic Tuple Mutation and Ephemeral Attribute Persistence

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly writes hierarchical edges without detecting cyclic paths (e.g., folder A inside folder B while folder B is placed in folder A), risking infinite recursion or graph expansion exhaustion. Persists ephemeral IP context into persistent store tuples rather than utilizing transient context. Lacks identity string sanitization.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

export async function addFolderParent(
  fga: OpenFgaClient,
  folderId: string,
  newParentId: string,
  clientIp: string
) {
  // VULNERABILITY 1: Persisting ephemeral request state as durable tuple
  await fga.write({
    writes: [
      {
        user: `folder:${newParentId}`,
        relation: 'parent',
        object: `folder:${folderId}`
      },
      {
        user: `ip:${clientIp}`,
        relation: 'origin_network',
        object: `folder:${folderId}`
      }
    ]
  });

  // VULNERABILITY 2: Blindly using unsanitized user payload as contextual tuple
  const isAllowed = await fga.check({
    user: `user:123`,
    relation: 'can_view',
    object: `folder:${folderId}`
  });
  return isAllowed.allowed;
}
```

#### Production Standard (Correct)
> **Standard**: Validates identifiers against injection, performs a pre-write reachability check using transitive parent relations to prevent cyclic graphs, rejects self-references, and supplies transient request metadata through evaluation context rather than corrupting durable tuple storage.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';

const ID_REGEX = /^[a-zA-Z0-9_-]{1,64}$/;

export async function addFolderParentSafe(
  fga: OpenFgaClient,
  folderId: string,
  newParentId: string,
  verifiedClientIp: string
): Promise<boolean> {
  if (!ID_REGEX.test(folderId) || !ID_REGEX.test(newParentId)) {
    throw new Error('Invalid resource identifier format');
  }
  if (folderId === newParentId) {
    throw new Error('Self-referential cycles are prohibited');
  }

  // INVARIANT 1: Detect potential cycles before write using transitive relation check
  const cycleCheck = await fga.check({
    user: `folder:${folderId}`,
    relation: 'parent_transitive',
    object: `folder:${newParentId}`
  });

  if (cycleCheck.allowed) {
    throw new Error(`Cycle detected: folder:${folderId} is already an ancestor of folder:${newParentId}`);
  }

  // INVARIANT 2: Write ONLY durable structural relationships
  await fga.write({
    writes: [{
      user: `folder:${newParentId}`,
      relation: 'parent',
      object: `folder:${folderId}`
    }]
  });

  // INVARIANT 3: Supply ephemeral context via dynamic context or contextual_tuples
  const checkRequest: ClientCheckRequest = {
    user: `user:123`,
    relation: 'can_view',
    object: `folder:${folderId}`,
    context: {
      current_ip: verifiedClientIp,
      request_timestamp: Math.floor(Date.now() / 1000)
    }
  };

  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 Graph Invariants: Cyclic Relation Prevention & Contextual Tuple Hardening

OpenFGA Graph Invariants: Cyclic Relation Prevention & Contextual Tuple Hardening defines an industrial-grade behavioral standard for security engineering. Enforces strict directed acyclic graph (DAG) topology validation during relationship mutation writes and mandates strict server-side schema verification for ephemeral contextual tuples in OpenFGA evaluations. Prohibits persistent storage of ephemeral request attributes and guards against recursive relation loops causing graph expansion denial-of-service. 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 State as Store Tuples and Unvalidated Cyclic Parent-Child Relationship Writes 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 State as Store Tuples and Unvalidated Cyclic Parent-Child Relationship WritesCritical
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 run an acyclic pre-check query (e.g., verifying child does not already reach parent via transitive relation) prior to committing hierarchical relationship tuples into OpenFGA.

Engineers MUST ALWAYS run an acyclic pre-check query (e.g., verifying child does not already reach parent via transitive relation) prior to committing hierarchical relationship tuples into OpenFGA.

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 persist ephemeral, session-bound, or time-sensitive claims (e.g., IP address, step-up MFA, request timestamp) as durable tuples in the OpenFGA store

Engineers MUST NOT persist ephemeral, session-bound, or time-sensitive claims (e.g., IP address, step-up MFA, request timestamp) as durable tuples in the OpenFGA store; these MUST be injected exclusively as transient contextual tuples or dynamic context objects during `check` calls.

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 MUST sanitize, type-check, and cryptographically verify client-originated data before transcribing it into `contextual_tuples` or `context` parameters during OpenFGA `check` or `expand` calls.

Code MUST sanitize, type-check, and cryptographically verify client-originated data before transcribing it into `contextual_tuples` or `context` parameters during OpenFGA `check` or `expand` calls.

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 enforce strict idempotency and atomic transactional semantics (via OpenFGA conditional tuples or application-level read-locks) when issuing tuple mutations to eliminate race conditions in graph updates.

Services MUST enforce strict idempotency and atomic transactional semantics (via OpenFGA conditional tuples or application-level read-locks) when issuing tuple mutations to eliminate race conditions in graph updates.

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 construct OpenFGA user strings (`type

Components NEVER construct OpenFGA user strings (`type:id#relation`) or object strings (`type:id`) using unchecked string interpolation without validating that IDs conform to strict alphanumeric patterns and do not contain delimiter injection characters (`:`, `#`, `@`).

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 Graph Invariants: Cyclic Relation Prevention & Contextual Tuple Hardening critical for AI coding assistants?

Enforces strict directed acyclic graph (DAG) topology validation during relationship mutation writes and mandates strict server-side schema verification for ephemeral contextual tuples in OpenFGA evaluations. Prohibits persistent storage of ephemeral request attributes and guards against recursive relation loops causing graph expansion denial-of-service. 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 State as Store Tuples and Unvalidated Cyclic Parent-Child Relationship Writes) 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.

Related SECURITY Rules

View all rules →
security
81

WebAuthn Conditional UI Mediation, Nonce Atomicity, and Assertion Cryptographic Verification

Enforces zero-trust cryptographic validation for FIDO2/WebAuthn Passkey authentication with Conditional UI autofill. Requires atomic single-use challenge consumption to eliminate replay attacks, strict RP ID hash and origin binding, authenticatorData flag verification (User Presence and User Verification), and monotonic signature counter enforcement to detect authenticator cloning.

security
111

Enforce Sigstore Keyless OIDC Attestation and Admission Controller Verification

Enforces immutable supply-chain security using Sigstore Cosign keyless signing via ephemeral OIDC tokens issued by Fulcio and verified against the Rekor transparency log. Container workloads must be signed and attested at build time by digest, and admission controllers (such as Kyverno or Sigstore Policy Controller) must strictly validate the OIDC issuer and subject identity before allowing image execution.

security
89

HashiCorp Vault Ephemeral Database Credentials and Lease-Aware Connection Pool Lifecycle

Production services interacting with relational datastores must consume short-lived ephemeral credentials issued dynamically by HashiCorp Vault with zero persistent root or shared credentials in configuration. Application connection pools must actively monitor lease TTLs, schedule proactive renewals before expiry, and gracefully drain and refresh database connection pools upon credential rotation without service downtime.

1 Rule in Stack

OpenFGA