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

WASI 0.2 Component Model Capability Sandboxing Guardrail

Enforces strict capability-based security boundaries for third-party WebAssembly components running in multi-tenant edge runtimes under WASI 0.2 (Preview 2). Prohibits ambient authority by requiring explicit, per-instance capability tokens for virtualized filesystem, network sockets, and environment variables. Guarantees deterministic memory limits and isolated linear memory heaps to eliminate cross-tenant data leakage and remote host compromise.

Prohibited Anti-Pattern: Ambient Host Access & Unbounded Linear Memory in Multi-Tenant Plugin Execution

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WASI 0.2 Component Model Capability Sandboxing Guardrail - Enforces strict capability-based security boundaries for third-party WebAssembly components running in multi-tenant edge runtimes under WASI 0.2 (Preview 2). Prohibits ambient authority by requiring explicit, per-instance capability tokens for virtualized filesystem, network sockets, and environment variables. Guarantees deterministic memory limits and isolated linear memory heaps to eliminate cross-tenant data leakage and remote host compromise.
globs: src/**/wasm/**/*.{rs,ts}, src/**/runtime/**/*.{rs,ts}, src/**/plugins/**/*.{rs,ts}, crates/**/src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/wasi-p2-capability-sandboxing-guardrail"
---

# WASI 0.2 Component Model Capability Sandboxing Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Ambient Host Access & Unbounded Linear Memory in Multi-Tenant Plugin Execution

## System Constraints
You are a Principal Systems Architect enforcing the WASI 0.2 (Preview 2) Component Model Capability Sandboxing Guardrail. Mandate that every WebAssembly component instantiated within the runtime utilizes isolated capability-based interfaces. Forbid any ambient host filesystem inheritance, unrestricted network socket bind/connect, or shared execution contexts across distinct tenants. Ensure memory limits, CPU fuel/epoch interruption, and pre-opened virtual directory sandboxes are enforced per invocation.

## Strict Guidelines
- Engineers MUST ALWAYS construct a dedicated WasiCtx per guest component invocation using WasiCtxBuilder with empty ambient defaults.
- Engineers MUST NOT grant direct host filesystem access via `.inherit_stdio()`, `.inherit_env()`, or ambient directory mounts to untrusted tenant components.
- Engineers MUST explicitly constrain network capabilities via custom implementations of `wasi:sockets` or deny socket creation entirely using non-routable dummy adapters.
- Engineers MUST configure explicit resource limiting (StoreLimits or ResourceLimiter) restricting max memory allocation, table elements, and async fuel/epoch-based preemption.
- Code SHOULD enforce isolated WIT (WebAssembly Interface Type) contracts for inter-component communication rather than sharing raw memory pointers or mutable buffers.

## Bad vs Good Implementations
### Wasmtime WASI 0.2 Host Instantiation with Capability Isolation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Inheriting host stdio, environment variables, and network grants ambient authority to untrusted guest code, enabling environment variable theft, unmonitored egress traffic, and host resource exhaustion.
```rust
use wasmtime::Engine;
use wasmtime_wasi::preview2::{WasiCtx, WasiCtxBuilder};

pub fn create_tenant_runtime(engine: &Engine) -> WasiCtx {
    // ANTI-PATTERN: Inheriting ambient authority exposes the host environment,
    // standard streams, and unconstrained host filesystem access to tenant plugins.
    WasiCtxBuilder::new()
        .inherit_stdio()
        .inherit_env()
        .inherit_network()
        .build()
}
```

#### Production Standard (Correct)
> **Standard**: Creates a zero-trust WASI Preview 2 execution context: ambient access is entirely stripped, network sockets are dropped, memory limits are capped, and filesystem access is confined strictly to an isolated virtual mount point.
```rust
use wasmtime::ResourceLimiter;
use wasmtime_wasi::preview2::{DirPerms, FilePerms, WasiCtx, WasiCtxBuilder};
use std::path::Path;

pub struct TenantLimits {
    pub memory_size: usize,
    pub max_tables: usize,
}

impl ResourceLimiter for TenantLimits {
    fn memory_growing(&mut self, _current: usize, desired: usize, _maximum: Option<usize>) -> Result<bool, anyhow::Error> {
        Ok(desired <= self.memory_size)
    }
    fn table_growing(&mut self, _current: usize, desired: usize, _maximum: Option<usize>) -> Result<bool, anyhow::Error> {
        Ok(desired <= self.max_tables)
    }
}

pub fn create_sandboxed_tenant_runtime(
    guest_scratch_dir: &Path,
) -> anyhow::Result<WasiCtx> {
    // INVARIANT: Explicit zero-trust capability model.
    // No ambient stdio/env/sockets; strictly isolated scratch directory.
    let mut builder = WasiCtxBuilder::new();
    
    // Pre-open isolated virtual directory only, with constrained permissions
    builder.preopened_dir(
        guest_scratch_dir,
        "/tmp",
        DirPerms::READ | DirPerms::MUTATE,
        FilePerms::READ | FilePerms::WRITE,
    )?;

    // Sockets are deliberately omitted, preventing outbound C2 and local network scanning
    Ok(builder.build())
}
```

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: WASI 0.2 Component Model Capability Sandboxing Guardrail

WASI 0.2 Component Model Capability Sandboxing Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict capability-based security boundaries for third-party WebAssembly components running in multi-tenant edge runtimes under WASI 0.2 (Preview 2). Prohibits ambient authority by requiring explicit, per-instance capability tokens for virtualized filesystem, network sockets, and environment variables. Guarantees deterministic memory limits and isolated linear memory heaps to eliminate cross-tenant data leakage and remote host compromise. 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 Access & Unbounded Linear Memory in Multi-Tenant Plugin 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 DriftAmbient Host Access & Unbounded Linear Memory in Multi-Tenant Plugin 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 construct a dedicated WasiCtx per guest component invocation using WasiCtxBuilder with empty ambient defaults.

Engineers MUST ALWAYS construct a dedicated WasiCtx per guest component invocation using WasiCtxBuilder with empty ambient defaults.

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 via `.inherit_stdio()`, `.inherit_env()`, or ambient directory mounts to untrusted tenant components.

Engineers MUST NOT grant direct host filesystem access via `.inherit_stdio()`, `.inherit_env()`, or ambient directory mounts to untrusted 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.
3

Engineers MUST explicitly constrain network capabilities via custom implementations of `wasi

Engineers MUST explicitly constrain network capabilities via custom implementations of `wasi:sockets` or deny socket creation entirely using non-routable dummy adapters.

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

Engineers MUST configure explicit resource limiting (StoreLimits or ResourceLimiter) restricting max memory allocation, table elements, and async fuel/epoch-based preemption.

Engineers MUST configure explicit resource limiting (StoreLimits or ResourceLimiter) restricting max memory allocation, table elements, and async fuel/epoch-based preemption.

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 enforce isolated WIT (WebAssembly Interface Type) contracts for inter-component communication rather than sharing raw memory pointers or mutable buffers.

Code SHOULD enforce isolated WIT (WebAssembly Interface Type) contracts for inter-component communication rather than sharing raw memory pointers or mutable buffers.

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 Capability Sandboxing Guardrail critical for AI coding assistants?

Enforces strict capability-based security boundaries for third-party WebAssembly components running in multi-tenant edge runtimes under WASI 0.2 (Preview 2). Prohibits ambient authority by requiring explicit, per-instance capability tokens for virtualized filesystem, network sockets, and environment variables. Guarantees deterministic memory limits and isolated linear memory heaps to eliminate cross-tenant data leakage and remote host compromise. 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 Access & Unbounded Linear Memory in Multi-Tenant Plugin 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