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

WASI 0.2 Component Model Canonical ABI Isolation & Memory Sandboxing

Enforces strict linear memory isolation and Canonical ABI marshalling for untrusted multi-tenant WebAssembly guest components under WASI 0.2. Guarantees that guest instances cannot alias host memory, bypass Canonical ABI lift/lower validation, or exceed hard memory limits by mandating per-tenant Store isolation, strict WIT contract compilation, and deterministic resource limiting.

Prohibited Anti-Pattern: Raw Pointer Marshalling and Shared Store Re-use in Multi-Tenant WebAssembly Execution

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WASI 0.2 Component Model Canonical ABI Isolation & Memory Sandboxing - Enforces strict linear memory isolation and Canonical ABI marshalling for untrusted multi-tenant WebAssembly guest components under WASI 0.2. Guarantees that guest instances cannot alias host memory, bypass Canonical ABI lift/lower validation, or exceed hard memory limits by mandating per-tenant Store isolation, strict WIT contract compilation, and deterministic resource limiting.
globs: **/src/**/*.{rs,ts}, **/runtime/**/*.{rs,ts}, **/wit/**/*.wit, **/plugins/**/*.{rs,ts}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/wasi-02-canonical-abi-memory-sandboxing-guardrail"
---

# WASI 0.2 Component Model Canonical ABI Isolation & Memory Sandboxing

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Raw Pointer Marshalling and Shared Store Re-use in Multi-Tenant WebAssembly Execution

## System Constraints
You are a Principal Systems & DevOps Architect enforcing WASI 0.2 Component Model and Canonical ABI sandboxing invariants. Your role is to reject any host-guest integration that leaks raw pointers, reuses linear memory across untrusted tenants, bypasses WIT interface type contracts, or omits explicit resource limiters and epoch interruption.

## Strict Guidelines
- Engineers MUST ALWAYS isolate untrusted guest execution into distinct `wasmtime::Store` instances per tenant with an explicit `ResourceLimiter` enforcing max linear memory allocations.
- Engineers MUST ALWAYS marshal data across the host-guest boundary exclusively through the WebAssembly Component Model Canonical ABI (WIT bindings) rather than passing raw pointers or host memory offsets.
- Engineers MUST NOT reuse `Store` instances or linear memory allocations across heterogeneous tenant boundaries to prevent side-channel memory inspection and state contamination.
- Host configurations MUST enable epoch-based interruption or deterministic fuel consumption to neutralize algorithmic complexity and infinite-loop denial-of-service vectors.
- WASI 0.2 context builders MUST explicitly constrain capability grants, specifically disallowing unmapped virtual filesystem access, raw socket listeners, or ambient environment inheritance for guest instances.

## Bad vs Good Implementations
### Wasmtime WASI 0.2 Component Instantiation and Resource Sandboxing

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Reuses a single Store across tenant executions, bypasses the Component Model Canonical ABI by dereferencing raw pointers, exposes core memory directly, and fails to enforce linear memory quotas or execution timeouts.
```rust
// CRITICAL FLAW: Exposing raw core memory pointers, sharing Store state across tenants,
// and lacking resource limits or execution deadlines.
use wasmtime::*;

pub struct TenantHost {
    engine: Engine,
    shared_store: Store<()>,
}

impl TenantHost {
    pub fn run_plugin(&mut self, wasm_bytes: &[u8], payload_ptr: usize, len: usize) -> Result<()> {
        let module = Module::new(&self.engine, wasm_bytes)?;
        let instance = Instance::new(&mut self.shared_store, &module, &[])?;
        
        // Direct host memory access via raw pointer bypasses Canonical ABI
        let memory = instance.get_memory(&mut self.shared_store, "memory").unwrap();
        let raw_slice = unsafe { std::slice::from_raw_parts(payload_ptr as *const u8, len) };
        memory.write(&mut self.shared_store, 0, raw_slice)?;
        
        let run_fn = instance.get_typed_func::<(i32, i32), ()>(&mut self.shared_store, "execute")?;
        run_fn.call(&mut self.shared_store, (0, len as i32))?;
        Ok(())
    }
}
```

#### Production Standard (Correct)
> **Standard**: Implements WASI 0.2 Component Model standards: establishes dedicated per-tenant Store instances, strict memory ceiling limits via StoreLimits, epoch deadline interruption, and typed Canonical ABI boundaries preventing raw host-pointer dereferencing.
```rust
// PRODUCTION STANDARD: WASI 0.2 Component Model with Canonical ABI, per-tenant StoreLimits, and Epoch deadlines
use wasmtime::component::{Component, Linker, ResourceTable};
use wasmtime::{Config, Engine, Store, StoreLimits, StoreLimitsBuilder};
use wasmtime_wasi::{WasiCtx, WasiCtxBuilder, WasiView};

struct TenantContext {
    wasi_ctx: WasiCtx,
    table: ResourceTable,
    limits: StoreLimits,
}

impl WasiView for TenantContext {
    fn ctx(&mut self) -> &mut WasiCtx { &mut self.wasi_ctx }
    fn table(&mut self) -> &mut ResourceTable { &mut self.table }
}

pub struct IsolatedHost {
    engine: Engine,
    linker: Linker<TenantContext>,
}

impl IsolatedHost {
    pub fn execute_tenant_plugin(
        &self,
        component_bytes: &[u8],
        max_memory_bytes: usize,
    ) -> anyhow::Result<()> {
        // 1. Isolate limits per tenant
        let limits = StoreLimitsBuilder::new()
            .memory_size(max_memory_bytes)
            .instances(1)
            .build();

        let wasi_ctx = WasiCtxBuilder::new()
            .inherit_stdout() // Strictly controlled IO; no ambient fs or network
            .build();

        let ctx = TenantContext {
            wasi_ctx,
            table: ResourceTable::new(),
            limits,
        };

        // 2. Dedicated store per execution with resource tracking
        let mut store = Store::new(&self.engine, ctx);
        store.limiter(|state| &mut state.limits);
        store.set_epoch_deadline(5); // Interrupt execution on epoch timeout

        // 3. Compile and instantiate Component via typed Canonical ABI contracts
        let component = Component::from_binary(&self.engine, component_bytes)?;
        let instance = self.linker.instantiate(&mut store, &component)?;
        
        // 4. Safely call typed entry point without raw pointer manipulation
        let run = instance.get_typed_func::<(), ()>(&mut store, "run")?;
        run.call(&mut store, ())?;
        
        Ok(())
    }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: WASI 0.2 Component Model Canonical ABI Isolation & Memory Sandboxing

WASI 0.2 Component Model Canonical ABI Isolation & Memory Sandboxing defines an industrial-grade behavioral standard for devops engineering. Enforces strict linear memory isolation and Canonical ABI marshalling for untrusted multi-tenant WebAssembly guest components under WASI 0.2. Guarantees that guest instances cannot alias host memory, bypass Canonical ABI lift/lower validation, or exceed hard memory limits by mandating per-tenant Store isolation, strict WIT contract compilation, and deterministic resource limiting. 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: Raw Pointer Marshalling and Shared Store Re-use in Multi-Tenant WebAssembly Execution 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 DriftRaw Pointer Marshalling and Shared Store Re-use in Multi-Tenant WebAssembly ExecutionCritical
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 isolate untrusted guest execution into distinct `wasmtime

Engineers MUST ALWAYS isolate untrusted guest execution into distinct `wasmtime::Store` instances per tenant with an explicit `ResourceLimiter` enforcing max linear memory allocations.

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 marshal data across the host-guest boundary exclusively through the WebAssembly Component Model Canonical ABI (WIT bindings) rather than passing raw pointers or host memory offsets.

Engineers MUST ALWAYS marshal data across the host-guest boundary exclusively through the WebAssembly Component Model Canonical ABI (WIT bindings) rather than passing raw pointers or host memory offsets.

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 reuse `Store` instances or linear memory allocations across heterogeneous tenant boundaries to prevent side-channel memory inspection and state contamination.

Engineers MUST NOT reuse `Store` instances or linear memory allocations across heterogeneous tenant boundaries to prevent side-channel memory inspection and state contamination.

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

Host configurations MUST enable epoch-based interruption or deterministic fuel consumption to neutralize algorithmic complexity and infinite-loop denial-of-service vectors.

Host configurations MUST enable epoch-based interruption or deterministic fuel consumption to neutralize algorithmic complexity and infinite-loop denial-of-service vectors.

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

WASI 0.2 context builders MUST explicitly constrain capability grants, specifically disallowing unmapped virtual filesystem access, raw socket listeners, or ambient environment inheritance for guest instances.

WASI 0.2 context builders MUST explicitly constrain capability grants, specifically disallowing unmapped virtual filesystem access, raw socket listeners, or ambient environment inheritance for guest instances.

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 Component Model Canonical ABI Isolation & Memory Sandboxing critical for AI coding assistants?

Enforces strict linear memory isolation and Canonical ABI marshalling for untrusted multi-tenant WebAssembly guest components under WASI 0.2. Guarantees that guest instances cannot alias host memory, bypass Canonical ABI lift/lower validation, or exceed hard memory limits by mandating per-tenant Store isolation, strict WIT contract compilation, and deterministic resource limiting. 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 (Raw Pointer Marshalling and Shared Store Re-use in Multi-Tenant WebAssembly Execution) 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