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

WASI 0.2 Component Model Capability-Scoped Sandbox Standard

Mandates zero-shared-memory execution boundaries and explicit capability mediation for untrusted tenant plugins using the WebAssembly System Interface (WASI 0.2) Component Model. Eliminates ambient authority by restricting imports to capability-scoped WIT interfaces, requiring per-execution store isolation, and enforcing strict resource metering (fuel/epoch deadlines).

Prohibited Anti-Pattern: Ambient Host Authority Inheritance and Unmetered Shared-Instance Execution in Multi-Tenant WebAssembly Hosts

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WASI 0.2 Component Model Capability-Scoped Sandbox Standard - Mandates zero-shared-memory execution boundaries and explicit capability mediation for untrusted tenant plugins using the WebAssembly System Interface (WASI 0.2) Component Model. Eliminates ambient authority by restricting imports to capability-scoped WIT interfaces, requiring per-execution store isolation, and enforcing strict resource metering (fuel/epoch deadlines).
globs: src/**/wasm/**/*.ts, src/**/plugins/**/*.ts, src/**/runtime/**/*.ts, src/**/sandbox/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/wasi-0-2-component-model-sandbox-standard"
---

# WASI 0.2 Component Model Capability-Scoped Sandbox Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Ambient Host Authority Inheritance and Unmetered Shared-Instance Execution in Multi-Tenant WebAssembly Hosts

## System Constraints
You are a Principal Engineer and Security Architect enforcing the WASI 0.2 Component Model Capability-Scoped Sandbox Standard. Untrusted tenant code must never inherit ambient authority, share linear memory across executions, or execute without deterministic resource bounds. Reject any patterns that bypass the Canonical ABI, reuse mutable Wasm Store state between tenants, or provide unrestricted host filesystem, network, or clock primitives.

## Strict Guidelines
- Engineers MUST ALWAYS instantiate a dedicated, isolated runtime Store and Instance for each tenant execution to enforce strict zero-shared-memory boundaries.
- Engineers MUST NOT provide ambient authority (e.g., inheriting host `process.env`, unrestricted `/` filesystem preopens, or raw TCP sockets via `wasi:sockets`).
- Services MUST mediate guest outbound networking exclusively through a capability-scoped implementation of `wasi:http/outgoing-handler` with explicit domain allowlisting and payload size limits.
- Code MUST configure deterministic compute boundaries on every guest store, utilizing fuel metering or epoch-based interruption deadlines to prevent compute exhaustion attacks.
- Components NEVER pass raw host pointers or expose unmediated shared buffers; all cross-boundary communications MUST adhere strictly to Canonical ABI value-copy semantics via typed WIT interfaces.
- Engineers MUST mock or sandbox non-deterministic host capabilities (`wasi:clocks`, `wasi:random`) when tenant execution requires reproducible verification or strict entropy budgeting.

## Bad vs Good Implementations
### Tenant Plugin Execution Configuration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Reuses stateful instances across invocations, inherits host process environment variables, provides raw filesystem access to host /tmp, enables unmediated TCP sockets, and lacks execution timeouts or fuel limits, exposing the host runtime to data exfiltration and CPU starvation.
```typescript
import { instantiateComponent } from '@bytecodealliance/jco';
import * as fs from 'node:fs';

// ANTI-PATTERN: Ambient authority, shared state, no fuel/timeout limits
const cachedStore = new Map<string, any>();

export async function runTenantPlugin(tenantId: string, componentBytes: Uint8Array, inputData: unknown) {
  let instance = cachedStore.get(tenantId);
  
  if (!instance) {
    // DANGEROUS: Ambient host access and shared filesystem preopens
    instance = await instantiateComponent(componentBytes, {
      'wasi:cli/[email protected]': { getEnvironment: () => process.env },
      'wasi:filesystem/[email protected]': { 
        getDirectories: () => [{ descriptor: fs.openSync('/tmp', 'r'), path: '/tmp' }]
      },
      'wasi:sockets/[email protected]': { /* raw host socket access */ },
    });
    cachedStore.set(tenantId, instance);
  }

  // DANGEROUS: Mutable state retained between invocations; no execution deadline or metering
  return instance.process(inputData);
}
```

#### Production Standard (Correct)
> **Standard**: Creates an ephemeral execution sandbox per invocation with zero ambient authority, eliminates raw filesystem and socket access, enforces strict egress domain allowlisting on wasi:http, bounds execution via AbortController timeouts, and transfers data strictly through value serialization across the Canonical ABI.
```typescript
import { instantiateComponent } from '@bytecodealliance/jco';
import { createHash, randomBytes } from 'node:crypto';

export interface SandboxOptions {
  readonly timeoutMs: number;
  readonly maxMemoryPages: number;
  readonly allowedEgressHosts: ReadonlySet<string>;
}

export async function runTenantPlugin(
  tenantId: string,
  componentBytes: Uint8Array,
  inputPayload: Record<string, unknown>,
  options: SandboxOptions
): Promise<Record<string, unknown>> {
  const abortController = new AbortController();
  const timeoutHandle = setTimeout(() => abortController.abort(new Error('ExecutionTimeout')), options.timeoutMs);

  try {
    // INVARIANT: Isolated, per-invocation capability-scoped context with zero ambient authority
    const virtualizedWasi = {
      'wasi:cli/[email protected]': {
        getEnvironment: () => [['TENANT_ID', tenantId]],
        getArguments: () => []
      },
      'wasi:filesystem/[email protected]': {
        getDirectories: () => [] // Zero ambient filesystem access
      },
      'wasi:http/[email protected]': {
        handle: async (request: { authority: string; pathWithQuery: string; headers: [string, Uint8Array][] }) => {
          if (!options.allowedEgressHosts.has(request.authority)) {
            throw new Error(`CapabilityDenied: Egress to ${request.authority} is unauthorized`);
          }
          // Dispatched via isolated, capability-checked outbound proxy
          return await fetch(`https://${request.authority}${request.pathWithQuery}`, {
            signal: abortController.signal
          });
        }
      },
      'wasi:random/[email protected]': {
        getRandomBytes: (len: bigint) => randomBytes(Number(len))
      }
    };

    // INVARIANT: Ephemeral instantiation prevents cross-tenant state leakage
    const instance = await instantiateComponent(componentBytes, virtualizedWasi);

    // Canonical ABI value copy; no shared memory pointers
    const serializedInput = JSON.stringify(inputPayload);
    const result = await Promise.race([
      instance.process(serializedInput),
      new Promise((_, reject) => {
        abortController.signal.addEventListener('abort', () => reject(abortController.signal.reason));
      })
    ]);

    return JSON.parse(result as string);
  } finally {
    clearTimeout(timeoutHandle);
  }
}
```

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-Scoped Sandbox Standard

WASI 0.2 Component Model Capability-Scoped Sandbox Standard defines an industrial-grade behavioral standard for backend engineering. Mandates zero-shared-memory execution boundaries and explicit capability mediation for untrusted tenant plugins using the WebAssembly System Interface (WASI 0.2) Component Model. Eliminates ambient authority by restricting imports to capability-scoped WIT interfaces, requiring per-execution store isolation, and enforcing strict resource metering (fuel/epoch deadlines). 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 Inheritance and Unmetered Shared-Instance Execution in Multi-Tenant WebAssembly Hosts 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 Inheritance and Unmetered Shared-Instance Execution in Multi-Tenant WebAssembly HostsCritical
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 a dedicated, isolated runtime Store and Instance for each tenant execution to enforce strict zero-shared-memory boundaries.

Engineers MUST ALWAYS instantiate a dedicated, isolated runtime Store and Instance for each tenant execution to enforce strict zero-shared-memory boundaries.

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 provide ambient authority (e.g., inheriting host `process.env`, unrestricted `/` filesystem preopens, or raw TCP sockets via `wasi

Engineers MUST NOT provide ambient authority (e.g., inheriting host `process.env`, unrestricted `/` filesystem preopens, or raw TCP sockets via `wasi:sockets`).

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

Services MUST mediate guest outbound networking exclusively through a capability-scoped implementation of `wasi

Services MUST mediate guest outbound networking exclusively through a capability-scoped implementation of `wasi:http/outgoing-handler` with explicit domain allowlisting and payload size limits.

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

Code MUST configure deterministic compute boundaries on every guest store, utilizing fuel metering or epoch-based interruption deadlines to prevent compute exhaustion attacks.

Code MUST configure deterministic compute boundaries on every guest store, utilizing fuel metering or epoch-based interruption deadlines to prevent compute exhaustion attacks.

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 pass raw host pointers or expose unmediated shared buffers

Components NEVER pass raw host pointers or expose unmediated shared buffers; all cross-boundary communications MUST adhere strictly to Canonical ABI value-copy semantics via typed WIT interfaces.

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

Engineers MUST mock or sandbox non-deterministic host capabilities (`wasi

Engineers MUST mock or sandbox non-deterministic host capabilities (`wasi:clocks`, `wasi:random`) when tenant execution requires reproducible verification or strict entropy budgeting.

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-Scoped Sandbox Standard critical for AI coding assistants?

Mandates zero-shared-memory execution boundaries and explicit capability mediation for untrusted tenant plugins using the WebAssembly System Interface (WASI 0.2) Component Model. Eliminates ambient authority by restricting imports to capability-scoped WIT interfaces, requiring per-execution store isolation, and enforcing strict resource metering (fuel/epoch deadlines). 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 Inheritance and Unmetered Shared-Instance Execution in Multi-Tenant WebAssembly Hosts) 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