This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: wasi-canonical-abi-sandbox-guardrail

WASI 0.2 Canonical ABI Component Sandboxing and Resource Protocol

Enforces strict shared-nothing linear memory isolation, capability-based descriptor confinement, and deterministic resource deallocation for untrusted multi-tenant WASI 0.2 components. Guarantees host-guest boundary integrity by prohibiting raw memory aliasing across the Canonical ABI and enforcing explicit resource drop lifecycles. Prevents memory leaks, use-after-free, and capability leaks in multi-tenant WebAssembly runtime hosts.

Prohibited Anti-Pattern: Leaking Raw Host Memory Pointers or Retaining Leaked Resource Handles Across Canonical ABI Lifecycles

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WASI 0.2 Canonical ABI Component Sandboxing and Resource Protocol - Enforces strict shared-nothing linear memory isolation, capability-based descriptor confinement, and deterministic resource deallocation for untrusted multi-tenant WASI 0.2 components. Guarantees host-guest boundary integrity by prohibiting raw memory aliasing across the Canonical ABI and enforcing explicit resource drop lifecycles. Prevents memory leaks, use-after-free, and capability leaks in multi-tenant WebAssembly runtime hosts.
globs: src/**/*.{rs,ts,go,cpp}, crates/**/*.{rs}, host/**/*.{rs,ts}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/wasi-canonical-abi-sandbox-guardrail"
---

# WASI 0.2 Canonical ABI Component Sandboxing and Resource Protocol

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Leaking Raw Host Memory Pointers or Retaining Leaked Resource Handles Across Canonical ABI Lifecycles

## System Constraints
You are a Principal Systems & Security Architect specializing in WebAssembly, WASI 0.2 (Component Model), and Canonical ABI bindings. Your role is to mandate strict zero-shared-memory boundaries, deterministic capability drops, and isolated per-tenant linear memory spaces. Reject any code that attempts to pass raw host pointers across ABI boundaries, bypasses Canonical ABI allocation (`cabi_realloc`), or retains dangling references in the host resource table.

## Strict Guidelines
- Hosts MUST ALWAYS instantiate components with independent, isolated linear memory blocks, strictly enforcing the shared-nothing component model.
- Hosts MUST NEVER pass raw host pointers, unowned slice references, or direct process file descriptors directly into guest linear memory across the Canonical ABI.
- Code MUST ALWAYS invoke `cabi_realloc` exported by the guest component when allocating memory in guest space for Canonical ABI lift/lower transformations.
- Services MUST manage guest-accessible host resources via opaque `ResourceTable` handles and deterministically invoke resource destructor callbacks upon component drop or execution trap.
- Engineers MUST ALWAYS configure host-side fuel metering, memory limits, and wall-clock deadlines on the WASI store prior to executing untrusted multi-tenant components.
- Components NEVER share mutable state across tenant execution contexts; each invocation MUST receive a clean or cryptographically re-initialized store state.

## Bad vs Good Implementations
### WASI 0.2 Host Resource Table and Canonical ABI String Transfer

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly writes into guest linear memory at an arbitrary static offset without invoking the Canonical ABI's `cabi_realloc`, leading to linear memory corruption, potential buffer overruns, and undefined behavior. It also fails to account for memory reallocation shifts and violates Canonical ABI string representation standards.
```typescript
// Anti-Pattern: Direct host buffer reference passed across boundary without cabi_realloc or tenant resource confinement
import { ComponentHost, RawGuestInstance } from '@runtime/wasm';

export async function runTenantTask(guest: RawGuestInstance, rawTenantData: Buffer): Promise<string> {
  // CRITICAL SECURITY FLAW: Direct raw pointer manipulation bypassing Canonical ABI allocator
  const guestMemory = new Uint8Array(guest.exports.memory.buffer);
  const arbitraryOffset = 0x1000;
  guestMemory.set(rawTenantData, arbitraryOffset);

  // Invokes export using unverified offset, exposing guest memory to corruption or OOB access
  const resultOffset = guest.exports.process_payload(arbitraryOffset, rawTenantData.length);
  
  // Dangerously reads until null-terminator without checking guest bounds or ownership
  let output = '';
  let ptr = resultOffset;
  while (guestMemory[ptr] !== 0) {
    output += String.fromCharCode(guestMemory[ptr++]);
  }
  return output;
}
```

#### Production Standard (Correct)
> **Standard**: Strictly adheres to WASI 0.2 Canonical ABI lifting and lowering standards: uses `cabi_realloc` for deterministic memory allocation and deallocation within guest memory, isolates buffer slicing, performs bounds validation, respects `cabi_post_*` resource lifecycles, and guarantees proper cleanup in `finally` blocks.
```typescript
// Production Fix: Enforces Canonical ABI reallocation, boundary-safe lifting/lowering, and resource drop invariants
import { Store, ResourceTable, ComponentInstance, WasiCtxBuilder } from '@bytecodealliance/jco';

export interface ExecutionResult {
  readonly payload: string;
}

export async function runTenantTask(
  instance: ComponentInstance,
  store: Store,
  tenantPayload: string
): Promise<ExecutionResult> {
  const encoder = new TextEncoder();
  const encoded = encoder.encode(tenantPayload);
  const decoder = new TextDecoder('utf-8', { fatal: true });

  // Step 1: Allocate space inside guest linear memory strictly via Canonical ABI cabi_realloc
  const cabiRealloc = instance.exports['cabi_realloc'] as (
    oldPtr: number,
    oldSize: number,
    align: number,
    newSize: number
  ) => number;

  const guestPtr = cabiRealloc(0, 0, 1, encoded.byteLength);
  if (guestPtr === 0 && encoded.byteLength > 0) {
    throw new Error('Canonical ABI Allocation Failed: Out of Memory');
  }

  try {
    // Step 2: Copy payload securely into isolated guest linear memory allocation
    const memoryView = new Uint8Array(instance.exports.memory.buffer, guestPtr, encoded.byteLength);
    memoryView.set(encoded);

    // Step 3: Call guest interface returning [resultPtr, resultLen] tuple
    const [resultPtr, resultLen] = instance.exports['process-tenant-payload'](
      guestPtr,
      encoded.byteLength
    ) as [number, number];

    // Step 4: Safely lift Canonical ABI string from isolated guest space
    const resultView = new Uint8Array(instance.exports.memory.buffer, resultPtr, resultLen);
    const liftedString = decoder.decode(resultView);

    // Step 5: Explicitly post-return deallocate guest result buffer if exported
    const cabiPostReturn = instance.exports['cabi_post_process-tenant-payload'] as
      | ((ptr: number) => void)
      | undefined;
    cabiPostReturn?.(resultPtr);

    return { payload: liftedString };
  } finally {
    // Step 6: Free the input buffer using Canonical ABI dealloc pattern (realloc to size 0)
    cabiRealloc(guestPtr, encoded.byteLength, 1, 0);
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: WASI 0.2 Canonical ABI Component Sandboxing and Resource Protocol

WASI 0.2 Canonical ABI Component Sandboxing and Resource Protocol defines an industrial-grade behavioral standard for security engineering. Enforces strict shared-nothing linear memory isolation, capability-based descriptor confinement, and deterministic resource deallocation for untrusted multi-tenant WASI 0.2 components. Guarantees host-guest boundary integrity by prohibiting raw memory aliasing across the Canonical ABI and enforcing explicit resource drop lifecycles. Prevents memory leaks, use-after-free, and capability leaks in multi-tenant WebAssembly runtime hosts. 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: Leaking Raw Host Memory Pointers or Retaining Leaked Resource Handles Across Canonical ABI Lifecycles 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 DriftLeaking Raw Host Memory Pointers or Retaining Leaked Resource Handles Across Canonical ABI LifecyclesCritical
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

Hosts MUST ALWAYS instantiate components with independent, isolated linear memory blocks, strictly enforcing the shared-nothing component model.

Hosts MUST ALWAYS instantiate components with independent, isolated linear memory blocks, strictly enforcing the shared-nothing component model.

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

Hosts MUST NEVER pass raw host pointers, unowned slice references, or direct process file descriptors directly into guest linear memory across the Canonical ABI.

Hosts MUST NEVER pass raw host pointers, unowned slice references, or direct process file descriptors directly into guest linear memory across the Canonical ABI.

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 ALWAYS invoke `cabi_realloc` exported by the guest component when allocating memory in guest space for Canonical ABI lift/lower transformations.

Code MUST ALWAYS invoke `cabi_realloc` exported by the guest component when allocating memory in guest space for Canonical ABI lift/lower transformations.

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 manage guest-accessible host resources via opaque `ResourceTable` handles and deterministically invoke resource destructor callbacks upon component drop or execution trap.

Services MUST manage guest-accessible host resources via opaque `ResourceTable` handles and deterministically invoke resource destructor callbacks upon component drop or execution trap.

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

Engineers MUST ALWAYS configure host-side fuel metering, memory limits, and wall-clock deadlines on the WASI store prior to executing untrusted multi-tenant components.

Engineers MUST ALWAYS configure host-side fuel metering, memory limits, and wall-clock deadlines on the WASI store prior to executing untrusted multi-tenant components.

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.
6

Components NEVER share mutable state across tenant execution contexts

Components NEVER share mutable state across tenant execution contexts; each invocation MUST receive a clean or cryptographically re-initialized store state.

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 WASI 0.2 Canonical ABI Component Sandboxing and Resource Protocol critical for AI coding assistants?

Enforces strict shared-nothing linear memory isolation, capability-based descriptor confinement, and deterministic resource deallocation for untrusted multi-tenant WASI 0.2 components. Guarantees host-guest boundary integrity by prohibiting raw memory aliasing across the Canonical ABI and enforcing explicit resource drop lifecycles. Prevents memory leaks, use-after-free, and capability leaks in multi-tenant WebAssembly runtime hosts. 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 (Leaking Raw Host Memory Pointers or Retaining Leaked Resource Handles Across Canonical ABI Lifecycles) 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

WASI