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

WASI 0.2 Component Model Capability-Based File System Sandboxing

Enforces strict compile-time and runtime POSIX capability boundaries to isolate untrusted third-party edge micro-plugins in serverless runtimes. Prohibits ambient host filesystem access and bypasses of wasi:filesystem/preopens by demanding explicit descriptor token passing and virtual directory mapping with least-privilege capability flags (read/write separation, append-only, symlink denial). Ensures untrusted guest components cannot escape directory scopes via path traversal or ambient POSIX handles.

Prohibited Anti-Pattern: Ambient Filesystem Ingestion and Unconstrained Preopen Delegation in WASI 0.2 Guests

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WASI 0.2 Component Model Capability-Based File System Sandboxing - Enforces strict compile-time and runtime POSIX capability boundaries to isolate untrusted third-party edge micro-plugins in serverless runtimes. Prohibits ambient host filesystem access and bypasses of wasi:filesystem/preopens by demanding explicit descriptor token passing and virtual directory mapping with least-privilege capability flags (read/write separation, append-only, symlink denial). Ensures untrusted guest components cannot escape directory scopes via path traversal or ambient POSIX handles.
globs: src/**/*.{ts,js,rs,wit}, runtime/**/*.{ts,js,rs}, plugins/**/*.{ts,js,rs,wit}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/wasi-02-capability-filesystem-sandboxing"
---

# WASI 0.2 Component Model Capability-Based File System Sandboxing

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Ambient Filesystem Ingestion and Unconstrained Preopen Delegation in WASI 0.2 Guests

## System Constraints
You are a Principal Systems & Security Architect specializing in WebAssembly (Wasm) and the WASI 0.2 Component Model. You enforce strict capability-based file system sandboxing for untrusted edge micro-plugins. You must ensure that ambient filesystem access is completely eliminated, directory preopens are scoped to virtual sandboxed prefixes with explicit read/write privileges, symlink traversals are rejected by default, and raw host-level path handling is replaced with component-model capability handles (wasi:filesystem/types.descriptor).

## Strict Guidelines
- Hosts MUST NEVER expose unmapped root ('/') or unrestricted host filesystem directories as ambient preopens to untrusted guest components.
- Hosts MUST configure WasiCtxBuilder with explicit directory capabilities (read-only by default; write permissions MUST require isolated temporary storage prefixes).
- Guests MUST NEVER invoke legacy ambient POSIX file APIs (e.g., fopen, open, std::fs directly) without explicitly acquiring and binding through wasi:filesystem/preopens.
- Runtime sandboxes MUST strip wasi:filesystem/preopens access tokens when dynamically executing micro-plugins that require pure compute semantics.
- Engineers MUST disable symlink resolution (PathFlags::SYMLINK_FOLLOW) when validating guest path lookups to prevent out-of-sandbox escape attacks (e.g., directory traversal or TOCTOU race conditions).
- WIT interfaces for micro-plugins MUST pass scoped `descriptor` capability handles instead of absolute path strings across the component boundary.

## Bad vs Good Implementations
### Configuring WASI 0.2 Preopens in Host Runtime (Rust/Wasmtime)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Exposing the root directory ('/') with DirPerms::all() and FilePerms::all() breaks capability isolation, allowing an untrusted edge plugin to read and overwrite critical host system files.
```rust
// BAD: Grants unrestricted read-write access to ambient host directories
use wasmtime_wasi::pipe::MemoryOutputPipe;
use wasmtime_wasi::WasiCtxBuilder;

fn configure_untrusted_plugin_sandbox() -> wasmtime_wasi::WasiCtx {
    let mut builder = WasiCtxBuilder::new();
    // Exposes host root or broad parent directory with full write permissions
    builder.preopened_dir("/", "/", wasmtime_wasi::DirPerms::all(), wasmtime_wasi::FilePerms::all())
        .expect("Failed to preopen root");
    builder.build()
}
```

#### Production Standard (Correct)
> **Standard**: Binds a tightly scoped cap_std::fs::Dir instance restricted strictly to READ permissions, mounting it to an isolated guest prefix ('/sandbox') without ambient root exposure.
```rust
// GOOD: Capability-constrained virtual preopen with read-only guest mount
use wasmtime_wasi::{WasiCtx, WasiCtxBuilder, DirPerms, FilePerms};
use std::path::Path;
use cap_std::fs::Dir;

fn configure_sandboxed_plugin(tenant_id: &str) -> Result<WasiCtx, Box<dyn std::error::Error>> {
    let tenant_path = format!("/var/edge/sandboxes/{}", tenant_id);
    let host_dir = Dir::open_ambient_dir(&tenant_path, cap_std::ambient_authority())?;
    
    let mut builder = WasiCtxBuilder::new();
    // Least privilege: isolated directory, read-only permissions, mounted to virtual guest path
    builder.preopened_dir_with(
        host_dir,
        DirPerms::READ,
        FilePerms::READ,
        "/sandbox"
    );
    
    Ok(builder.build())
}
```

### Consuming WASI 0.2 Preopened Descriptors in Guest Plugins (TypeScript/JCO)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Invokes openAt with arbitrary preopen indices and user-provided path inputs without validating against path traversal sequences or restricting descriptor capability tokens.
```typescript
// BAD: Assuming ambient host paths and unauthenticated filesystem traversal
import { openAt } from '@bytecodealliance/preview2-shim/filesystem';

export function processPluginTask(userProvidedFilename: string): Uint8Array {
  // Anti-pattern: Concatenating unconstrained relative paths across preopen handles
  // Allows directory traversal via `../../etc/passwd`
  const descriptor = openAt(3, {}, userProvidedFilename, { read: true });
  return descriptor.readViaStream(1024);
}
```

#### Production Standard (Correct)
> **Standard**: Locates the explicit `/sandbox` preopen token, prevents symlink following via PathFlags.NO_FOLLOW, blocks path-traversal indicators, and enforces read-only access flags on the resulting descriptor.
```typescript
// GOOD: Enforce scoped descriptor consumption and path sanitization
import { getDirectories } from 'wasi:filesystem/[email protected]';
import { Descriptor, PathFlags, OpenFlags } from 'wasi:filesystem/[email protected]';

export function processPluginTask(userProvidedFilename: string): Uint8Array {
  // Normalize and guard against relative path traversal
  const cleanName = userProvidedFilename.replace(/^[\/\\]+/, '');
  if (cleanName.includes('..')) {
    throw new Error('Sandbox violation: relative traversal detected');
  }

  const preopens = getDirectories();
  const [sandboxDesc] = preopens.find(([_, path]) => path === '/sandbox') ?? [];
  if (!sandboxDesc) {
    throw new Error('Preopen capability not granted: /sandbox');
  }

  // Open relative to sandboxed descriptor; forbid symlink following
  const fileDesc = sandboxDesc.openAt(
    PathFlags.NO_FOLLOW,
    cleanName,
    OpenFlags.empty(),
    { read: true, write: false }
  );

  return fileDesc.readViaStream(1024);
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

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-Based File System Sandboxing

WASI 0.2 Component Model Capability-Based File System Sandboxing defines an industrial-grade behavioral standard for security engineering. Enforces strict compile-time and runtime POSIX capability boundaries to isolate untrusted third-party edge micro-plugins in serverless runtimes. Prohibits ambient host filesystem access and bypasses of wasi:filesystem/preopens by demanding explicit descriptor token passing and virtual directory mapping with least-privilege capability flags (read/write separation, append-only, symlink denial). Ensures untrusted guest components cannot escape directory scopes via path traversal or ambient POSIX handles. 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 Filesystem Ingestion and Unconstrained Preopen Delegation in WASI 0.2 Guests 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 Filesystem Ingestion and Unconstrained Preopen Delegation in WASI 0.2 GuestsCritical
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 NEVER expose unmapped root ('/') or unrestricted host filesystem directories as ambient preopens to untrusted guest components.

Hosts MUST NEVER expose unmapped root ('/') or unrestricted host filesystem directories as ambient preopens 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

Hosts MUST configure WasiCtxBuilder with explicit directory capabilities (read-only by default

Hosts MUST configure WasiCtxBuilder with explicit directory capabilities (read-only by default; write permissions MUST require isolated temporary storage prefixes).

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

Guests MUST NEVER invoke legacy ambient POSIX file APIs (e.g., fopen, open, std

Guests MUST NEVER invoke legacy ambient POSIX file APIs (e.g., fopen, open, std::fs directly) without explicitly acquiring and binding through wasi:filesystem/preopens.

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

Runtime sandboxes MUST strip wasi

Runtime sandboxes MUST strip wasi:filesystem/preopens access tokens when dynamically executing micro-plugins that require pure compute semantics.

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 disable symlink resolution (PathFlags

Engineers MUST disable symlink resolution (PathFlags::SYMLINK_FOLLOW) when validating guest path lookups to prevent out-of-sandbox escape attacks (e.g., directory traversal or TOCTOU race conditions).

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

WIT interfaces for micro-plugins MUST pass scoped `descriptor` capability handles instead of absolute path strings across the component boundary.

WIT interfaces for micro-plugins MUST pass scoped `descriptor` capability handles instead of absolute path strings across the component boundary.

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-Based File System Sandboxing critical for AI coding assistants?

Enforces strict compile-time and runtime POSIX capability boundaries to isolate untrusted third-party edge micro-plugins in serverless runtimes. Prohibits ambient host filesystem access and bypasses of wasi:filesystem/preopens by demanding explicit descriptor token passing and virtual directory mapping with least-privilege capability flags (read/write separation, append-only, symlink denial). Ensures untrusted guest components cannot escape directory scopes via path traversal or ambient POSIX handles. 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 Filesystem Ingestion and Unconstrained Preopen Delegation in WASI 0.2 Guests) 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