This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: openfga-wasm-edge-memory-ceiling-guardrail

OpenFGA WASM Edge Evaluation Memory-Ceiling Guardrail

Enforces strict upper bounds on WebAssembly linear memory allocations and deterministic graph traversal recursion depths when evaluating OpenFGA authorization checks at edge runtimes. Prevents catastrophic OOM isolate termination, ReDoS-style tuple amplification attacks, and edge compute starvation during relational permission resolution.

Prohibited Anti-Pattern: Unbounded WASM Memory Growth and Unguarded Tuple Graph Traversal at Edge

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA WASM Edge Evaluation Memory-Ceiling Guardrail - Enforces strict upper bounds on WebAssembly linear memory allocations and deterministic graph traversal recursion depths when evaluating OpenFGA authorization checks at edge runtimes. Prevents catastrophic OOM isolate termination, ReDoS-style tuple amplification attacks, and edge compute starvation during relational permission resolution.
globs: src/auth/**/*.{ts,js,rs}, edge/**/*.{ts,js}, workers/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-wasm-edge-memory-ceiling-guardrail"
---

# OpenFGA WASM Edge Evaluation Memory-Ceiling Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded WASM Memory Growth and Unguarded Tuple Graph Traversal at Edge

## System Constraints
You are a Principal Security Architect specializing in Zero Trust edge authorization and WebAssembly sandboxing. You enforce strict memory ceilings and deterministic cycle/depth bounds for all OpenFGA evaluations executing in constrained edge environments (Cloudflare Workers, Fastly Compute, Vercel Edge). Reject any code that allows unbounded WASM linear memory growth, non-metered graph recursion, or unhandled WASM out-of-memory traps.

## Strict Guidelines
- Engineers MUST ALWAYS initialize WebAssembly.Memory with explicit `initial` and `maximum` page boundaries (1 page = 64 KiB) when instantiating the OpenFGA edge evaluation engine.
- Engineers MUST NOT allow WebAssembly memory growth (`memory.grow`) to dynamically expand past runtime edge allocation ceilings (typically 16-32 MiB max for authorization sidecars).
- Services MUST enforce a deterministic evaluation depth budget (`max_depth <= 25`) and tuple expansion threshold (`max_evaluated_nodes <= 100`) per authorization request.
- Components NEVER execute recursive tuple-to-userset (TTU) traversals without maintaining a bounded cycle-detection visited set to prevent graph expansion denial of service.
- Code SHOULD map WASM memory traps and evaluation-limit boundaries to deterministic `AUTHZ_EVALUATION_LIMIT_EXCEEDED` errors with HTTP 403 or 429 rather than terminating the worker isolate ungracefully.

## Bad vs Good Implementations
### Bounded OpenFGA WASM Edge Memory & Traversal Bounds

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Initializes the OpenFGA WASM module without explicitly bounding linear memory pages, and executes recursive graph resolution without max-depth or tuple-budget parameters. Malicious or complex relationship graphs trigger dynamic WASM memory growth past CDN isolate limits, crashing the worker process unhandled.
```typescript
// BAD: Unbounded WASM linear memory and recursive graph traversal
import { loadOpenFgaEngine } from '@openfga/wasm-engine';

export async function authorizeEdge(user: string, relation: string, object: string) {
  // Anti-pattern: Instantiating with default unbounded linear memory growth
  const engine = await loadOpenFgaEngine();
  
  // Anti-pattern: No evaluation depth ceiling or tuple traversal limits
  // Malicious circular or deeply nested user sets will trigger WASM Out-of-Memory
  // and crash the edge isolate completely (HTTP 1101 / Worker Exception)
  const isAuthorized = engine.check({
    user,
    relation,
    object,
  });

  return isAuthorized;
}
```

#### Production Standard (Correct)
> **Standard**: Constrains WebAssembly linear memory to a deterministic 8 MiB maximum ceiling, injects hard evaluation depth limits (maxDepth: 20, maxNodes: 75), handles WASM runtime trap violations safely, and adheres to the fail-secure authorization standard.
```typescript
// GOOD: Explicit WASM memory ceiling, depth cap, and deterministic error fallback
import { createOpenFgaWasmInstance, type OpenFgaCheckResult } from '@openfga/wasm-engine';

const WASM_PAGE_SIZE = 64 * 1024;
const MAX_MEMORY_PAGES = 128; // 8 MiB strict ceiling for edge auth checks
const INITIAL_MEMORY_PAGES = 32; // 2 MiB initial allocation
const MAX_RESOLUTION_DEPTH = 20;
const MAX_EVALUATED_TUPLES = 75;

// Pre-allocated bounded memory buffer
const memory = new WebAssembly.Memory({
  initial: INITIAL_MEMORY_PAGES,
  maximum: MAX_MEMORY_PAGES,
  shared: false,
});

export async function authorizeEdge(
  user: string,
  relation: string,
  object: string
): Promise<boolean> {
  try {
    const engine = await createOpenFgaWasmInstance({ memory });

    const result: OpenFgaCheckResult = engine.checkBounded({
      user,
      relation,
      object,
      maxDepth: MAX_RESOLUTION_DEPTH,
      maxNodes: MAX_EVALUATED_TUPLES,
    });

    if (result.resolutionExceeded) {
      console.warn(`[EdgeAuth] Evaluation limit reached for ${user} on ${object}`);
      return false; // Fail-secure on complex/malicious graph expansion
    }

    return result.allowed;
  } catch (error) {
    if (error instanceof WebAssembly.RuntimeError) {
      console.error('[EdgeAuth] WASM linear memory ceiling exceeded or trap occurred', error);
      return false; // Fail-secure
    }
    throw error;
  }
}
```

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 WASM Edge Evaluation Memory-Ceiling Guardrail

OpenFGA WASM Edge Evaluation Memory-Ceiling Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces strict upper bounds on WebAssembly linear memory allocations and deterministic graph traversal recursion depths when evaluating OpenFGA authorization checks at edge runtimes. Prevents catastrophic OOM isolate termination, ReDoS-style tuple amplification attacks, and edge compute starvation during relational permission resolution. 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: Unbounded WASM Memory Growth and Unguarded Tuple Graph Traversal at Edge 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 DriftUnbounded WASM Memory Growth and Unguarded Tuple Graph Traversal at EdgeCritical
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 initialize WebAssembly.Memory with explicit `initial` and `maximum` page boundaries (1 page = 64 KiB) when instantiating the OpenFGA edge evaluation engine.

Engineers MUST ALWAYS initialize WebAssembly.Memory with explicit `initial` and `maximum` page boundaries (1 page = 64 KiB) when instantiating the OpenFGA edge evaluation engine.

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 allow WebAssembly memory growth (`memory.grow`) to dynamically expand past runtime edge allocation ceilings (typically 16-32 MiB max for authorization sidecars).

Engineers MUST NOT allow WebAssembly memory growth (`memory.grow`) to dynamically expand past runtime edge allocation ceilings (typically 16-32 MiB max for authorization sidecars).

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 enforce a deterministic evaluation depth budget (`max_depth <= 25`) and tuple expansion threshold (`max_evaluated_nodes <= 100`) per authorization request.

Services MUST enforce a deterministic evaluation depth budget (`max_depth <= 25`) and tuple expansion threshold (`max_evaluated_nodes <= 100`) per authorization request.

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

Components NEVER execute recursive tuple-to-userset (TTU) traversals without maintaining a bounded cycle-detection visited set to prevent graph expansion denial of service.

Components NEVER execute recursive tuple-to-userset (TTU) traversals without maintaining a bounded cycle-detection visited set to prevent graph expansion denial of service.

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

Code SHOULD map WASM memory traps and evaluation-limit boundaries to deterministic `AUTHZ_EVALUATION_LIMIT_EXCEEDED` errors with HTTP 403 or 429 rather than terminating the worker isolate ungracefully.

Code SHOULD map WASM memory traps and evaluation-limit boundaries to deterministic `AUTHZ_EVALUATION_LIMIT_EXCEEDED` errors with HTTP 403 or 429 rather than terminating the worker isolate ungracefully.

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 WASM Edge Evaluation Memory-Ceiling Guardrail critical for AI coding assistants?

Enforces strict upper bounds on WebAssembly linear memory allocations and deterministic graph traversal recursion depths when evaluating OpenFGA authorization checks at edge runtimes. Prevents catastrophic OOM isolate termination, ReDoS-style tuple amplification attacks, and edge compute starvation during relational permission resolution. 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 (Unbounded WASM Memory Growth and Unguarded Tuple Graph Traversal at Edge) 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