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

Strict Capability-Based Sandboxing for WASI 0.2 Guest Component Boundaries

Enforces strict capability-based least privilege and resource confinement when executing untrusted third-party plug-ins under the WebAssembly System Interface (WASI 0.2 / Preview 2) Component Model. Mandates explicit world link-time imports, ambient authority eradication, and cryptographically verified component signatures prior to instantiating host runtimes.

Prohibited Anti-Pattern: Ambient Host Authority Leakage and Unbounded Resource Exposure in Guest WASI Runtimes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Strict Capability-Based Sandboxing for WASI 0.2 Guest Component Boundaries - Enforces strict capability-based least privilege and resource confinement when executing untrusted third-party plug-ins under the WebAssembly System Interface (WASI 0.2 / Preview 2) Component Model. Mandates explicit world link-time imports, ambient authority eradication, and cryptographically verified component signatures prior to instantiating host runtimes.
globs: src/**/*.rs, crates/**/*.rs, src/**/*.wit, wit/**/*.wit
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/wasi-p2-capability-sandbox-boundary"
---

# Strict Capability-Based Sandboxing for WASI 0.2 Guest Component Boundaries

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Ambient Host Authority Leakage and Unbounded Resource Exposure in Guest WASI Runtimes

## System Constraints
You are a Principal Security Architect enforcing WASI 0.2 (Preview 2) Component Model capability boundaries. You must reject any code exposing ambient host authority (such as unrestricted filesystem root access, unmetered network sockets, or default WASI CLI worlds) to untrusted guest plugins. You enforce fine-grained capability passing via WIT (WebAssembly Interface Type) contracts, pre-opened relative directory descriptors, domain-allowlisted outbound HTTP interceptors, deterministic fuel/epoch interruption, and pre-instantiation cryptographic signature verification.

## Strict Guidelines
- Engineers MUST NEVER provide default `wasi:cli` or ambient filesystem/network access to untrusted guest components.
- Engineers MUST explicitly construct `WasiCtx` using strict capability builders, granting only explicit, relative pre-opened directories with read-only flags where possible.
- Engineers MUST implement explicit outgoing HTTP socket filtering through custom `WasiHttpView` interceptors, strictly matching against domain allowlists.
- Host runtimes MUST enforce resource metering via Wasmtime fuel consumption (`consume_fuel(true)`) or epoch-based interruption to prevent compute denial-of-service.
- Host linkers MUST cryptographically verify component bytecode signatures (e.g., via Sigstore/Ed25519) before calling `Linker::instantiate`.
- Guest WIT interfaces MUST define isolated, fine-grained capability-based resource handles rather than importing arbitrary host OS syscall equivalents.

## Bad vs Good Implementations
### Configuring WASI 0.2 Host Context with Fuel Metering and Sandboxed I/O

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Inheriting the host network, environment variables, and preopening the root directory (`/`) with full read/write permissions completely destroys the WASI isolation boundary. Furthermore, the absence of fuel or epoch-based limits allows guest components to trigger unmetered CPU exhaustion.
```rust
use wasmtime::component::Linker;
use wasmtime::{Config, Engine, Store};
use wasmtime_wasi::p2::WasiCtxBuilder;

pub struct HostState {
    pub ctx: wasmtime_wasi::p2::WasiCtx,
    pub table: wasmtime_wasi::ResourceTable,
}

impl wasmtime_wasi::p2::WasiView for HostState {
    fn ctx(&mut self) -> &mut wasmtime_wasi::p2::WasiCtx { &mut self.ctx }
    fn table(&mut self) -> &mut wasmtime_wasi::ResourceTable { &mut self.table }
}

pub fn run_untrusted_plugin(engine: &Engine, guest_bytes: &[u8]) -> anyhow::Result<()> {
    // ANTI-PATTERN: Inheriting ambient OS capabilities, unbounded access, no fuel limiting
    let mut wasi = WasiCtxBuilder::new();
    wasi.inherit_stdio()
        .inherit_network()
        .inherit_env();
    
    // Exposes entire host root directory to the guest
    wasi.preopened_dir("/", ".", wasmtime_wasi::DirPerms::all(), wasmtime_wasi::FilePerms::all())?;

    let state = HostState {
        ctx: wasi.build(),
        table: wasmtime_wasi::ResourceTable::new(),
    };
    let mut store = Store::new(engine, state);
    let component = wasmtime::component::Component::new(engine, guest_bytes)?;
    let mut linker = Linker::new(engine);
    wasmtime_wasi::p2::add_to_linker_sync(&mut linker)?;
    
    let instance = linker.instantiate(&mut store, &component)?;
    Ok(())
}
```

#### Production Standard (Correct)
> **Standard**: Enforces strict least privilege by verifying guest cryptographic authenticity, configuring isolated directory capabilities through `cap_std` with no root escape, restricting maximum linear memory to 64MB, and attaching deterministic fuel limits to defeat CPU denial-of-service.
```rust
use std::path::Path;
use wasmtime::component::{Component, Linker};
use wasmtime::{Config, Engine, Store, StoreLimits, StoreLimitsBuilder};
use wasmtime_wasi::p2::{DirPerms, FilePerms, WasiCtx, WasiCtxBuilder, WasiView};
use wasmtime_wasi::ResourceTable;

pub struct SandboxedPluginState {
    ctx: WasiCtx,
    table: ResourceTable,
    limits: StoreLimits,
}

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

pub fn run_sandboxed_plugin(
    engine: &Engine,
    signed_guest_bytes: &[u8],
    plugin_data_dir: &Path,
    expected_public_key: &ed25519_dalek::VerifyingKey,
    signature: &ed25519_dalek::Signature,
) -> anyhow::Result<()> {
    // Cryptographic verification invariant
    expected_public_key.verify_strict(signed_guest_bytes, signature)?;

    // Least-privilege WASI 0.2 Context
    let mut wasi = WasiCtxBuilder::new();
    
    // Grant explicit sandboxed isolated directory only; no root, no parent traversals
    let sandbox_dir = cap_std::fs::Dir::open_ambient_dir(plugin_data_dir, cap_std::ambient_authority())?;
    wasi.preopened_dir(sandbox_dir, DirPerms::READ | DirPerms::MUTATE, FilePerms::READ | FilePerms::WRITE, "sandbox")?;

    // Eradicate ambient environment and network inheritance
    let state = SandboxedPluginState {
        ctx: wasi.build(),
        table: ResourceTable::new(),
        limits: StoreLimitsBuilder::new()
            .memory_size(64 * 1024 * 1024) // 64 MB max
            .instances(1)
            .build(),
    };

    let mut store = Store::new(engine, state);
    store.set_fuel(10_000_000)?; // Strict execution budget
    store.limiter(|s| &mut s.limits);

    let component = Component::from_binary(engine, signed_guest_bytes)?;
    let mut linker = Linker::new(engine);
    wasmtime_wasi::p2::add_to_linker_sync(&mut linker)?;

    let instance = linker.instantiate(&mut store, &component)?;
    Ok(())
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Strict Capability-Based Sandboxing for WASI 0.2 Guest Component Boundaries

Strict Capability-Based Sandboxing for WASI 0.2 Guest Component Boundaries defines an industrial-grade behavioral standard for security engineering. Enforces strict capability-based least privilege and resource confinement when executing untrusted third-party plug-ins under the WebAssembly System Interface (WASI 0.2 / Preview 2) Component Model. Mandates explicit world link-time imports, ambient authority eradication, and cryptographically verified component signatures prior to instantiating host runtimes. 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 Authority Leakage and Unbounded Resource Exposure in Guest WASI Runtimes 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 Authority Leakage and Unbounded Resource Exposure in Guest WASI RuntimesCritical
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 NEVER provide default `wasi

Engineers MUST NEVER provide default `wasi:cli` or ambient filesystem/network access to untrusted guest 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.
2

Engineers MUST explicitly construct `WasiCtx` using strict capability builders, granting only explicit, relative pre-opened directories with read-only flags where possible.

Engineers MUST explicitly construct `WasiCtx` using strict capability builders, granting only explicit, relative pre-opened directories with read-only flags where possible.

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 implement explicit outgoing HTTP socket filtering through custom `WasiHttpView` interceptors, strictly matching against domain allowlists.

Engineers MUST implement explicit outgoing HTTP socket filtering through custom `WasiHttpView` interceptors, strictly matching against domain allowlists.

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 runtimes MUST enforce resource metering via Wasmtime fuel consumption (`consume_fuel(true)`) or epoch-based interruption to prevent compute denial-of-service.

Host runtimes MUST enforce resource metering via Wasmtime fuel consumption (`consume_fuel(true)`) or epoch-based interruption to prevent compute 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

Host linkers MUST cryptographically verify component bytecode signatures (e.g., via Sigstore/Ed25519) before calling `Linker

Host linkers MUST cryptographically verify component bytecode signatures (e.g., via Sigstore/Ed25519) before calling `Linker::instantiate`.

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

Guest WIT interfaces MUST define isolated, fine-grained capability-based resource handles rather than importing arbitrary host OS syscall equivalents.

Guest WIT interfaces MUST define isolated, fine-grained capability-based resource handles rather than importing arbitrary host OS syscall equivalents.

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 Strict Capability-Based Sandboxing for WASI 0.2 Guest Component Boundaries critical for AI coding assistants?

Enforces strict capability-based least privilege and resource confinement when executing untrusted third-party plug-ins under the WebAssembly System Interface (WASI 0.2 / Preview 2) Component Model. Mandates explicit world link-time imports, ambient authority eradication, and cryptographically verified component signatures prior to instantiating host runtimes. 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 Authority Leakage and Unbounded Resource Exposure in Guest WASI Runtimes) 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

Strict