This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: wasi-0-2-capability-sandbox-isolation

Deterministic Capability-Based Sandbox Isolation for WASI 0.2 Plugins

Third-party guest WebAssembly components executing under WASI 0.2 must strictly adhere to capability-based security invariants by eliminating ambient host authority. Host runtimes must construct explicit, bounded WASI contexts with pre-opened virtual directories, restricted socket interfaces, and deterministic resource limiters to prevent host breakout and resource exhaustion.

Prohibited Anti-Pattern: Ambient Host Privilege Leakage via Unconstrained WASI Context Inheritance

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Deterministic Capability-Based Sandbox Isolation for WASI 0.2 Plugins - Third-party guest WebAssembly components executing under WASI 0.2 must strictly adhere to capability-based security invariants by eliminating ambient host authority. Host runtimes must construct explicit, bounded WASI contexts with pre-opened virtual directories, restricted socket interfaces, and deterministic resource limiters to prevent host breakout and resource exhaustion.
globs: src/**/*.rs, crates/**/*.rs, plugins/**/*.rs, src/sandbox/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/wasi-0-2-capability-sandbox-isolation"
---

# Deterministic Capability-Based Sandbox Isolation for WASI 0.2 Plugins

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Ambient Host Privilege Leakage via Unconstrained WASI Context Inheritance

## System Constraints
You are a Principal Security Architect and Systems Engineer specializing in WebAssembly (Wasm) and WASI 0.2 (Preview 2) Component Model runtimes. Enforce strict capability-based security: never grant ambient host environment, filesystem, or network socket access to untrusted guest plugins. Mandate granular link-time import resolution, pre-opened virtual directory mapping with scoped permissions, explicit socket address allowlisting, and rigid memory/table resource limits.

## Strict Guidelines
- Engineers MUST ALWAYS instantiate WASI contexts using explicit `WasiCtxBuilder` isolation without calling ambient inheritance methods like `inherit_env`, `inherit_network`, or unrestricted `inherit_stdio`.
- Engineers MUST NOT grant direct host filesystem access; all filesystem handles must be pre-opened virtual directories with explicitly declared `DirPerms` and `FilePerms`.
- Host runtimes MUST isolate or stub `wasi:sockets` (TCP/UDP, DNS name lookup) unless the plugin is explicitly designated for network operations with a strictly enforced IP/CIDR egress allowlist.
- Services MUST attach a deterministic `ResourceLimiter` or `StoreLimits` to the `Store` state, strictly bounding maximum memory growth, table elements, and compute fuel/epoch execution deadlines.
- Components NEVER import unrestricted host linker capabilities; all WIT interface bindings linked into the component must be explicitly audited and scoped.

## Bad vs Good Implementations
### Host Construction of WASI 0.2 Guest Sandbox Context

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Inheriting the host environment, stdio, and network ambiently breaks capability isolation. Untrusted guest components can read sensitive host environment variables, open raw outbound TCP/UDP sockets to internal services, and consume infinite memory without bounds.
```rust
use wasmtime::component::Linker;
use wasmtime_wasi::preview2::{WasiCtx, WasiCtxBuilder, WasiView};

struct HostState {
    wasi: WasiCtx,
}

impl WasiView for HostState {
    fn ctx(&self) -> &WasiCtx { &self.wasi }
    fn ctx_mut(&mut self) -> &mut WasiCtx { &mut self.wasi }
}

// ANTI-PATTERN: Inheriting ambient host resources and missing resource limits
fn create_plugin_context() -> HostState {
    let mut builder = WasiCtxBuilder::new();
    builder.inherit_stdio()
           .inherit_env()      // Leaks host environment secrets
           .inherit_network();  // Grants unrestricted socket creation to guest

    HostState {
        wasi: builder.build(),
    }
}
```

#### Production Standard (Correct)
> **Standard**: Adheres to WASI 0.2 capability isolation: ambient network and environment inheritance are stripped, filesystem access is locked to a single virtual directory path with read-only permissions, stdio is bounded in-memory, and StoreLimits prevent memory exhaustion.
```rust
use wasmtime::{StoreLimits, StoreLimitsBuilder};
use wasmtime_wasi::preview2::pipe::MemoryOutputPipe;
use wasmtime_wasi::preview2::{DirPerms, FilePerms, WasiCtx, WasiCtxBuilder, WasiView};
use std::path::Path;

pub struct HostState {
    pub wasi: WasiCtx,
    pub limits: StoreLimits,
    pub stdout_capture: MemoryOutputPipe,
}

impl WasiView for HostState {
    fn ctx(&self) -> &WasiCtx { &self.wasi }
    fn ctx_mut(&mut self) -> &mut WasiCtx { &mut self.wasi }
}

// PRODUCTION INVARIANT: Explicit capabilities, bounded I/O, and resource limits
pub fn create_sandboxed_plugin_context(plugin_dir: &Path) -> Result<HostState, Box<dyn std::error::Error>> {
    let stdout_capture = MemoryOutputPipe::new(1024 * 64); // Cap output buffer
    let mut builder = WasiCtxBuilder::new();

    // 1. Sandbox stdio without raw terminal access
    builder.stdout(stdout_capture.clone());

    // 2. Pre-open isolated virtual directory with read-only/explicit permissions
    builder.preopened_dir(
        plugin_dir,
        "sandbox",
        DirPerms::READ,
        FilePerms::READ,
    )?;

    // 3. Deny network access by omitting network inheritance (wasi:sockets fails closed)
    // Sockets are explicitly NOT permitted for third-party dynamic plugins

    // 4. Bound memory allocations to 64MB and tables to 10,000 elements
    let limits = StoreLimitsBuilder::new()
        .memory_size(64 * 1024 * 1024)
        .instances(1)
        .tables(10_000)
        .build();

    Ok(HostState {
        wasi: builder.build(),
        limits,
        stdout_capture,
    })
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Deterministic Capability-Based Sandbox Isolation for WASI 0.2 Plugins

Deterministic Capability-Based Sandbox Isolation for WASI 0.2 Plugins defines an industrial-grade behavioral standard for backend engineering. Third-party guest WebAssembly components executing under WASI 0.2 must strictly adhere to capability-based security invariants by eliminating ambient host authority. Host runtimes must construct explicit, bounded WASI contexts with pre-opened virtual directories, restricted socket interfaces, and deterministic resource limiters to prevent host breakout and resource exhaustion. 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: Ambient Host Privilege Leakage via Unconstrained WASI Context Inheritance 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 DriftAmbient Host Privilege Leakage via Unconstrained WASI Context InheritanceCritical
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 instantiate WASI contexts using explicit `WasiCtxBuilder` isolation without calling ambient inheritance methods like `inherit_env`, `inherit_network`, or unrestricted `inherit_stdio`.

Engineers MUST ALWAYS instantiate WASI contexts using explicit `WasiCtxBuilder` isolation without calling ambient inheritance methods like `inherit_env`, `inherit_network`, or unrestricted `inherit_stdio`.

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 grant direct host filesystem access

Engineers MUST NOT grant direct host filesystem access; all filesystem handles must be pre-opened virtual directories with explicitly declared `DirPerms` and `FilePerms`.

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

Host runtimes MUST isolate or stub `wasi

Host runtimes MUST isolate or stub `wasi:sockets` (TCP/UDP, DNS name lookup) unless the plugin is explicitly designated for network operations with a strictly enforced IP/CIDR egress allowlist.

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 attach a deterministic `ResourceLimiter` or `StoreLimits` to the `Store` state, strictly bounding maximum memory growth, table elements, and compute fuel/epoch execution deadlines.

Services MUST attach a deterministic `ResourceLimiter` or `StoreLimits` to the `Store` state, strictly bounding maximum memory growth, table elements, and compute fuel/epoch execution deadlines.

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 import unrestricted host linker capabilities

Components NEVER import unrestricted host linker capabilities; all WIT interface bindings linked into the component must be explicitly audited and scoped.

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 Deterministic Capability-Based Sandbox Isolation for WASI 0.2 Plugins critical for AI coding assistants?

Third-party guest WebAssembly components executing under WASI 0.2 must strictly adhere to capability-based security invariants by eliminating ambient host authority. Host runtimes must construct explicit, bounded WASI contexts with pre-opened virtual directories, restricted socket interfaces, and deterministic resource limiters to prevent host breakout and resource exhaustion. 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 (Ambient Host Privilege Leakage via Unconstrained WASI Context Inheritance) 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

Deterministic