sandbox

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 7, 2026 License: MIT Imports: 20 Imported by: 0

README

micromax/sandbox

Go Reference

Run untrusted or AI-generated code in strict isolation, as an embeddable Go library.

github.com/micromax/sandbox provides defense-in-depth execution environments with zero host daemons required for lightweight languages and hardened container sandboxes for heavy compilers.


Key Features

  • Zero-Daemon Pure Go Backend (wazero): Run JavaScript, TypeScript, Python, Lua, and pre-compiled Wasm binaries with zero CGO (CGO_ENABLED=0) and no Docker required.
  • Universal Docker Tier (Opt-In): Hardened, read-only OCI containers with dropped capabilities for Java, Go, Rust, Node.js, and Bash.
  • Hard Resource Limits: Strict caps on memory, wall-clock time, stdout/stderr byte limits, and virtual disk quotas.
  • Virtual Filesystem (VFS): Isolated in-memory filesystem (/in, /work, /out) that prevents host filesystem leaks and rejects path traversal attacks.
  • Stateful REPL Sessions: Multi-turn conversational code execution for AI agents and notebooks.
  • Serving Network Ports (Serve): Expose guest web services through a secured host-side reverse proxy with rate limiting and bearer token authentication.
  • Deny-By-Default Outbound Networking: Optional host allow-lists with SSRF guards and DNS rebinding prevention.
  • AI Agent & Model Context Protocol (MCP): Built-in sandbox mcp server for Claude Desktop, Cursor, and LLM agent function calling.
  • Unified CLI (sandbox): Terminal companion for running, testing, serving, and diagnosing sandboxes.

Language Support Matrix

Language Identifier(s) Default Backend Cold Start Memory Floor Host Requirements
JavaScript js, javascript Wasm (QuickJS-NG) ~50 ms ~5 MB Zero Docker (Embedded in binary)
TypeScript ts, typescript Wasm (QuickJS-NG) ~50 ms ~5 MB Zero Docker (Embedded in binary)
Python python, py Wasm (CPython 3.13) ~250 ms ~25 MB Zero Docker (Cached WASI bundle)
Lua lua, lua54 Wasm (Lua 5.4.6) ~20 ms ~2 MB Zero Docker (Embedded in binary)
Raw WASI wasm, wasi, wasip1 Wasm (wazero) ~5–15 ms ~1 MB Zero Docker (Pre-compiled Go/Rust/C)
Node.js node, nodejs Docker (node:slim) ~600 ms ~35 MB Docker or Podman daemon
Java java Docker (eclipse-temurin:21) ~1.2 s ~128 MB Docker or Podman daemon
Go go, golang Docker (golang:alpine) ~1.0 s ~64 MB Docker or Podman daemon
Rust rust, rs Docker (rust:alpine) ~1.5 s ~128 MB Docker or Podman daemon
Bash bash, sh Docker (alpine:latest) ~400 ms ~10 MB Docker or Podman daemon

Quickstart

1. Installation
go get github.com/micromax/sandbox
2. Run Code in Pure WebAssembly (Zero Docker)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/micromax/sandbox"
	"github.com/micromax/sandbox/backend/wasm"
	"github.com/micromax/sandbox/packs/js"
)

func main() {
	// Initialize pure-Go Wasm backend
	wBackend, err := wasm.New()
	if err != nil {
		log.Fatal(err)
	}

	sb, err := sandbox.New(
		sandbox.WithBackends(wBackend),
		sandbox.WithPacks(js.Pack()),
	)
	if err != nil {
		log.Fatal(err)
	}

	res, err := sb.Run(context.Background(), sandbox.Spec{
		Lang: "js",
		Code: `console.log("6 * 7 = " + (6 * 7));`,
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%s", res.Stdout)
}

CLI Tool

Install the standalone CLI:

go install github.com/micromax/sandbox/cmd/sandbox@latest
# Check your environment and installed engines
sandbox doctor

# Run a script with memory and time caps
sandbox run --timeout 5s --mem 64M script.py

# Start an interactive REPL
sandbox repl --lang python

# Start Model Context Protocol server for Claude / Cursor
sandbox mcp

# Serve a guest web server
sandbox serve --lang js --port 8080 app.js

AI Agent Integration (Claude Desktop & Cursor)

sandbox implements the standard Model Context Protocol (MCP), allowing LLMs to securely execute code on your machine:

Add sandbox to your Claude Desktop config (%APPDATA%\Claude\claude_desktop_config.json on Windows or ~/Library/Application Support/Claude/claude_desktop_config.json on macOS):

{
  "mcpServers": {
    "sandbox": {
      "command": "sandbox",
      "args": ["mcp"]
    }
  }
}

Claude Desktop automatically gains three secure tools:

  • execute_code: Stateless one-shot execution across TypeScript, Python, Lua, JS, Go, Rust, Java.
  • eval_session: Persistent multi-turn REPL execution preserving variables across conversation turns.
  • list_languages: Runtime diagnostics and language tier matrix.

Detailed Documentation


License

MIT — see LICENSE.

Documentation

Overview

Package sandbox runs untrusted or generated code in isolation so the host machine stays safe.

A Sandbox owns a set of language [Pack]s and one or more [Backend]s. Run asks the routing Policy which backend may execute a pack, builds an empty virtual world (a quota-limited in-memory filesystem, no network, capped output, a wall-clock deadline) and returns what the code printed and wrote.

Safety rules

  • Deny by default: no network, no host files, no environment variables unless the caller grants them in the Spec.
  • Zero never means unlimited: unset Limits fields take safe defaults. Unlimited must be requested explicitly.
  • No silent downgrades: if the backends allowed by the Policy cannot run a language, Run fails with ErrBackendUnavailable instead of falling back to weaker isolation.

Backends live in sub-packages (for example backend/wasm) and are passed to New with WithBackends; the core package has no heavy dependencies.

Index

Constants

View Source
const (
	// Unlimited disables a byte-valued limit (Memory, MaxOutput, FSQuota).
	Unlimited uint64 = math.MaxUint64
	// UnlimitedTime disables a duration-valued limit (WallTime, CPUTime).
	UnlimitedTime time.Duration = -1
	// UnlimitedCount disables a count-valued limit (MaxFiles, MaxProcs).
	UnlimitedCount = -1
)

Unlimited and friends disable a limit explicitly. A zero value in a Limits field never means unlimited; it means "use the default".

Variables

View Source
var (
	// PreferWasm uses Wasm when the pack supports it, otherwise Docker (if
	// that backend is registered). This is the default.
	PreferWasm = Policy{Order: []string{"wasm", "docker"}}
	// WasmOnly never uses anything but the Wasm backend.
	WasmOnly = Policy{Order: []string{"wasm"}}
	// DockerOnly never uses anything but the Docker backend.
	DockerOnly = Policy{Order: []string{"docker"}}
)

Built-in policies.

View Source
var (
	// ErrTimeout means the wall-clock limit expired.
	ErrTimeout = errors.New("sandbox: time limit exceeded")
	// ErrMemoryLimit means the guest exceeded its memory limit.
	ErrMemoryLimit = errors.New("sandbox: memory limit exceeded")
	// ErrOutputLimit means the guest produced more output than allowed.
	ErrOutputLimit = errors.New("sandbox: output limit exceeded")
	// ErrFSQuota means the virtual filesystem quota (bytes or file count)
	// was exceeded. It is the same value as [vfs.ErrQuota].
	ErrFSQuota = errFSQuota
	// ErrSessionKilled means a session was destroyed, for example by a
	// timeout, and its state is gone.
	ErrSessionKilled = errors.New("sandbox: session killed")
	// ErrBackendUnavailable means no backend permitted by the routing
	// policy can run the requested language.
	ErrBackendUnavailable = errors.New("sandbox: no permitted backend available")
	// ErrUnsupported means the chosen backend cannot do what was asked.
	ErrUnsupported = errors.New("sandbox: operation not supported")
	// ErrNetworkDenied means the guest tried to use the network and the
	// policy forbids it.
	ErrNetworkDenied = errors.New("sandbox: network access denied")
	// ErrUnknownLanguage means no registered pack matches the language.
	ErrUnknownLanguage = errors.New("sandbox: unknown language")
	// ErrInvalidSpec means the run specification is malformed.
	ErrInvalidSpec = errors.New("sandbox: invalid spec")
	// ErrInvalidLimits means a Limits value is out of range.
	ErrInvalidLimits = errors.New("sandbox: invalid limits")
	// ErrInvalidPack means a pack definition is malformed.
	ErrInvalidPack = errors.New("sandbox: invalid pack")
)

Sentinel errors, for use with errors.Is.

A non-zero exit code from guest code is not a Go error; it is reported in Result.ExitCode.

View Source
var (
	// ErrSessionClosed is returned when an operation is attempted on a closed session.
	ErrSessionClosed = errors.New("sandbox: session is closed")

	// ErrTooManySessions is returned by Manager when the maximum number of active sessions is reached.
	ErrTooManySessions = errors.New("sandbox: too many concurrent sessions")

	// ErrSessionNotFound is returned when a session ID is not registered in the manager.
	ErrSessionNotFound = errors.New("sandbox: session not found")
)
View Source
var (
	// ErrManagerClosed is returned when an operation is performed on a closed manager.
	ErrManagerClosed = errors.New("sandbox: session manager is closed")
)
View Source
var NoAuth = AuthOption{Enabled: false}

NoAuth disables proxy-level authentication.

Functions

This section is empty.

Types

type Artifact

type Artifact struct {
	// Name is a human-readable file name.
	Name string
	// URL is where to download it from; empty when Embedded is set.
	URL string
	// SHA256 is the lower-case hex digest every use is verified against.
	SHA256 string
	// Size is the expected size in bytes; 0 when unknown.
	Size int64
	// Embedded holds the bytes when the artifact ships inside the binary.
	Embedded []byte
	// ArchiveEntry extracts a specific file from a zip archive when set.
	ArchiveEntry string
}

Artifact is a runtime file (a .wasm module, a standard library archive...) pinned by hash.

type AuthOption

type AuthOption struct {
	Enabled bool
	Token   string
}

AuthOption configures authentication at the host proxy layer.

func BearerToken

func BearerToken(token string) AuthOption

BearerToken enables HTTP Bearer token authentication at the proxy layer. If token is empty (""), a cryptographically secure random token is generated.

type Backend

type Backend interface {
	// Name is the stable identifier the routing policy refers to, e.g. "wasm".
	Name() string
	// Supports reports whether this backend can run the pack.
	Supports(p *Pack) bool
	// Run executes the request. See [Request] for the contract.
	Run(ctx context.Context, req *Request) (Outcome, error)
}

Backend is an isolation mechanism: Wasm, Docker, and so on. Implementations live in sub-packages and are registered with WithBackends.

type BindMode

type BindMode string

BindMode specifies the host IP or interface for the service proxy.

const (
	// Loopback binds the proxy to 127.0.0.1 (default, only reachable by the local host).
	Loopback BindMode = "127.0.0.1"

	// AllInterfaces binds the proxy to 0.0.0.0 (reachable from outside the host).
	AllInterfaces BindMode = "0.0.0.0"
)

func Interface

func Interface(addr string) BindMode

Interface specifies a custom IP or interface address to bind to.

type Capabilities

type Capabilities struct {
	// Sessions: supports REPL-style stateful sessions.
	Sessions bool
	// ServeHandler: can serve through the host-bridged handler model.
	ServeHandler bool
	// ServeSocket: can run servers that open their own sockets.
	ServeSocket bool
	// Network: supports a network policy.
	Network bool
	// Compiles: has a compile step before running.
	Compiles bool
}

Capabilities declares what a pack can do.

type DockerSpec

type DockerSpec struct {
	// Image is the image reference pinned by digest, e.g. "python@sha256:...".
	Image string
	// Cmd is the command to run.
	Cmd []string
	// Workdir is the working directory inside the container.
	Workdir string
}

DockerSpec describes running a language in a container.

type GuestService

type GuestService interface {
	// PortMapping returns the host target address (e.g. "127.0.0.1:49152") for the guest port.
	PortMapping(guestPort int) (string, error)

	// Handler returns an in-process HTTP handler for Wasm bridge services, or nil for network containers.
	Handler() http.Handler

	// Wait blocks until the guest process or container terminates.
	Wait() (Outcome, error)

	// Stop terminates the guest process or container.
	Stop() error
}

GuestService is the backend handle for a running server process or container.

type Limits

type Limits struct {
	// Memory is the maximum guest memory in bytes. Default 128 MiB.
	Memory uint64
	// WallTime is the maximum elapsed time. Default 10 s.
	WallTime time.Duration
	// CPUTime is the maximum CPU time, best effort. Default 10 s.
	CPUTime time.Duration
	// MaxOutput is the combined stdout+stderr byte cap. Default 1 MiB.
	MaxOutput uint64
	// FSQuota is the byte quota of the virtual filesystem. Default 16 MiB.
	FSQuota uint64
	// MaxFiles caps files plus directories in the virtual filesystem,
	// including the three base directories in, work and out. Default 256.
	MaxFiles int
	// MaxProcs caps processes/threads where the backend has them. Default 64.
	MaxProcs int
}

Limits bounds the resources one execution may use.

Zero fields take the value from DefaultLimits (or the sandbox-wide defaults set with WithDefaultLimits). Whether and how precisely a limit is enforced depends on the backend; each backend documents its guarantees.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits returns the built-in safe defaults.

func (Limits) Validate

func (l Limits) Validate() error

Validate reports whether a fully resolved Limits value is usable. It is called on the result of merging, so zero values are rejected here: they would mean a default was missing, never "unlimited".

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager coordinates concurrent interactive sessions, enforcing capacity caps, idle pruning, and clean shutdown without resource leaks.

func NewManager

func NewManager(sb *Sandbox, opts ManagerOpts) *Manager

NewManager creates a session manager backed by the given sandbox.

func (*Manager) Close

func (m *Manager) Close(id string) error

Close explicitly terminates and unregisters the session with the specified ID.

func (*Manager) Count

func (m *Manager) Count() int

Count returns the number of active sessions currently managed.

func (*Manager) Create

func (m *Manager) Create(ctx context.Context, lang string, opts ...SessionOpt) (Session, error)

Create spawns a new session for the given language. Returns ErrTooManySessions if the maximum session capacity has been reached.

func (*Manager) Get

func (m *Manager) Get(id string) (Session, bool)

Get returns the session with the specified ID, or false if not found.

func (*Manager) Shutdown

func (m *Manager) Shutdown(ctx context.Context) error

Shutdown cleanly terminates all active sessions and halts the background reaper.

type ManagerOpts

type ManagerOpts struct {
	// MaxSessions is the maximum number of concurrent active sessions. Defaults to 64.
	MaxSessions int

	// Idle is the default inactivity timeout for sessions. Defaults to 5 minutes.
	Idle time.Duration

	// MaxLifetime is the maximum allowed duration of a session. Defaults to 1 hour.
	MaxLifetime time.Duration

	// ReapInterval is how frequently the background reaper checks for expired/idle sessions.
	// Defaults to 10 seconds.
	ReapInterval time.Duration

	// DefaultLimits specifies default resource limits for sessions created by this manager.
	DefaultLimits Limits

	// AutoRestart configures whether created sessions automatically restart if killed.
	AutoRestart bool
}

ManagerOpts configures the session manager.

type Mount

type Mount struct {
	Artifact  Artifact
	GuestPath string
}

Mount makes an artifact available inside the guest, read-only.

type NetLogEntry

type NetLogEntry struct {
	Timestamp        time.Time
	Method           string
	URL              string
	StatusCode       int
	BytesTransferred int64
	Duration         time.Duration
	Error            string
}

NetLogEntry records one outbound network request made by the guest.

type NetPolicy

type NetPolicy struct {
	// AllowHosts lists permitted host names; a leading "*." matches any
	// subdomain.
	AllowHosts []string
	// AllowPorts lists permitted destination ports. Empty means 80 and 443.
	AllowPorts []int
	// MaxRequests caps the number of outbound requests. Zero means the
	// backend default.
	MaxRequests int
	// MaxBytes caps total bytes received. Zero means the backend default.
	MaxBytes uint64
	// AllowPrivate permits private, loopback and link-local destinations.
	// Leave false unless you fully understand the SSRF implications.
	AllowPrivate bool
}

NetPolicy describes the outbound network access granted to a guest. The zero value of Spec.Net (nil) grants none.

Enforcement is backend specific and arrives with the network milestone; until a backend declares support (see NetworkCapable), a non-nil policy makes Run fail with ErrUnsupported instead of being silently ignored.

type NetworkCapable

type NetworkCapable interface {
	SupportsNetwork() bool
}

NetworkCapable is implemented by backends that can enforce a NetPolicy. A backend that does not implement it, or returns false, is never given a request with a network policy: the policy would otherwise be silently ignored.

type Option

type Option func(*config)

Option configures New.

func WithBackends

func WithBackends(backends ...Backend) Option

WithBackends registers isolation backends.

func WithDefaultLimits

func WithDefaultLimits(l Limits) Option

WithDefaultLimits overrides the built-in defaults field by field. Fields left zero keep the built-in value.

func WithPacks

func WithPacks(packs ...*Pack) Option

WithPacks registers language packs.

func WithPolicy

func WithPolicy(p Policy) Option

WithPolicy sets the routing policy. The default is PreferWasm.

type Outcome

type Outcome struct {
	// ExitCode is the guest exit status. Non-zero is not an error.
	ExitCode int
	// PeakMemory is the peak guest memory in bytes, or 0 if unknown.
	PeakMemory uint64
	// NetLog records outbound requests if network was enabled.
	NetLog []NetLogEntry
}

Outcome is what a backend reports about a completed run.

type Pack

type Pack struct {
	// Name is the canonical lower-case language name, e.g. "python".
	Name string
	// Aliases are alternative names, e.g. "py". Lower-case.
	Aliases []string
	// Version is the language/runtime version the pack pins.
	Version string
	// Wasm describes how to run the language on the Wasm backend.
	Wasm *WasmSpec
	// Docker describes how to run the language on the Docker backend.
	Docker *DockerSpec
	// Extra carries specs for out-of-tree or experimental backends, keyed
	// by backend name.
	Extra map[string]any
	// Caps declares what this pack supports so callers and the router know
	// before running anything.
	Caps Capabilities
}

Pack describes one language and how to run it on each backend. Packs are plain data: adding a language never changes the core API.

func (*Pack) Validate

func (p *Pack) Validate() error

Validate checks that the pack is well formed.

type Policy

type Policy struct {
	// Order lists backend names, most preferred first.
	Order []string
}

Policy decides which backends may run code, and in which order they are tried. Only backends named in Order are ever used, which is how the "never silently downgrade isolation" rule is enforced: if none of them can run a language, Run fails instead of picking something weaker.

func NewPolicy

func NewPolicy(names ...string) Policy

NewPolicy returns a custom policy from backend names in preference order.

func (Policy) String

func (p Policy) String() string

type PortMap

type PortMap struct {
	// Guest is the port number inside the guest container or runtime.
	Guest int

	// Host is the optional host port to bind to. If 0, an ephemeral port is chosen.
	Host int
}

PortMap defines a port mapping between the guest and the host.

type ReadinessProbe

type ReadinessProbe interface {
	Check(ctx context.Context, targetAddr string, handler http.Handler) error
	Timeout() time.Duration
}

ReadinessProbe verifies that a service is ready to accept traffic before opening the host listener.

func HTTPReady

func HTTPReady(path string, timeout time.Duration) ReadinessProbe

HTTPReady creates a readiness probe that checks whether an HTTP GET request returns 2xx or 3xx status.

func TCPReady

func TCPReady(timeout time.Duration) ReadinessProbe

TCPReady creates a readiness probe that checks whether the guest port accepts TCP connections.

type Request

type Request struct {
	Pack   *Pack
	Spec   Spec
	Limits Limits
	// FS is the guest's virtual filesystem, pre-populated with /in, /work
	// and /out and the injected files.
	FS *vfs.FS
	// Stdin is never nil.
	Stdin  io.Reader
	Stdout io.Writer
	Stderr io.Writer
}

Request is what the core hands to a backend. All limits are already validated and resolved.

A backend must:

  • write guest stdout and stderr only to Stdout and Stderr, which enforce the output cap and return ErrOutputLimit when it is hit; stop the guest and return that error when a write fails;
  • honour ctx, which carries the wall-clock deadline;
  • present FS to the guest as /in (read-only), /work and /out, and write nothing to the host filesystem;
  • never grant network access unless Spec.Net allows it;
  • return limit violations as the matching Err* sentinel (wrapped is fine).

type Result

type Result struct {
	// Stdout and Stderr hold the captured output, together capped by
	// Limits.MaxOutput.
	Stdout, Stderr []byte
	// Truncated is true when output was cut short by Limits.MaxOutput.
	Truncated bool
	// ExitCode is the guest exit status.
	ExitCode int
	// Files holds the files the guest left under /out, keyed by path
	// relative to /out.
	Files map[string][]byte
	// Usage reports the resources consumed.
	Usage Usage
	// Backend is the name of the backend that ran the code.
	Backend string
	// Restarted reports whether the session was restarted prior to this eval.
	Restarted bool
	// NetLog records outbound requests if network was enabled.
	NetLog []NetLogEntry
}

Result is what an execution produced.

When Run fails because a resource limit was hit (see ErrTimeout, ErrMemoryLimit, ErrOutputLimit, ErrFSQuota) the returned Result is still non-nil and holds whatever was captured before the limit tripped.

type Sandbox

type Sandbox struct {
	// contains filtered or unexported fields
}

Sandbox runs code through registered backends. Create one with New. It is safe for concurrent use.

func New

func New(opts ...Option) (*Sandbox, error)

New creates a Sandbox. It validates every pack and limit up front so misconfiguration fails at startup rather than during a run.

func (*Sandbox) Languages

func (s *Sandbox) Languages() []string

Languages returns the canonical names of all registered packs, sorted.

func (*Sandbox) NewSession

func (s *Sandbox) NewSession(ctx context.Context, lang string, opts ...SessionOpt) (Session, error)

NewSession starts a stateful interactive REPL session for the given language.

func (*Sandbox) Run

func (s *Sandbox) Run(ctx context.Context, spec Spec) (*Result, error)

Run executes spec once and returns what it produced.

A non-zero guest exit code is not an error. Resource-limit violations return a non-nil partial Result together with the matching error (ErrTimeout, ErrMemoryLimit, ErrOutputLimit, ErrFSQuota). Any other failure returns a nil Result.

func (*Sandbox) Serve

func (s *Sandbox) Serve(ctx context.Context, spec Spec, opts ServeOpts) (*Service, error)

Serve runs a server inside the sandbox and safely exposes it on the host machine.

type ServeBackend

type ServeBackend interface {
	Serve(ctx context.Context, req *ServeRequest) (GuestService, error)
}

ServeBackend is implemented by backends capable of running background servers.

type ServeOpts

type ServeOpts struct {
	// Ports specifies guest ports to expose on the host.
	Ports []PortMap

	// Bind specifies the host interface to bind to. Defaults to [Loopback] ("127.0.0.1").
	Bind BindMode

	// TTL is the maximum lifetime for this service. When it expires, the service is stopped.
	TTL time.Duration

	// Auth configures Bearer token authorization at the proxy layer.
	Auth AuthOption

	// Ready specifies the readiness probe. Defaults to [TCPReady](15*time.Second).
	Ready ReadinessProbe

	// Proxy limits
	MaxConnections int
	MaxRequestBody int64
	MaxHeaderBytes int
	IdleTimeout    time.Duration
}

ServeOpts configures how a service is exposed and managed.

type ServeRequest

type ServeRequest struct {
	Pack      *Pack
	Spec      Spec
	Limits    Limits
	FS        *vfs.FS
	Ports     []PortMap
	LogWriter io.Writer
}

ServeRequest contains all parameters handed to a backend that supports Serve.

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service represents an actively running and exposed guest service.

func (*Service) Addr

func (s *Service) Addr(guestPort int) string

Addr returns the host "ip:port" address for the given guest port.

func (*Service) Done

func (s *Service) Done() <-chan struct{}

Done returns a channel that is closed when the service stops, exits, or times out.

func (*Service) Err

func (s *Service) Err() error

Err returns the error that caused the service to terminate, if any.

func (*Service) Logs

func (s *Service) Logs() io.Reader

Logs returns an io.Reader streaming the recent captured guest logs.

func (*Service) RecentLogs

func (s *Service) RecentLogs() string

RecentLogs returns a string snapshot of recent stdout/stderr output from the guest.

func (*Service) Stop

func (s *Service) Stop() error

Stop shuts down the host proxies and stops the underlying guest process.

func (*Service) Token

func (s *Service) Token() string

Token returns the Bearer auth token if one was configured or generated.

func (*Service) URL

func (s *Service) URL() string

URL returns the default primary HTTP URL for accessing the service.

func (*Service) URLFor

func (s *Service) URLFor(guestPort int) string

URLFor returns the HTTP URL exposed for a specific guest port.

type Session

type Session interface {
	// ID returns the unique identifier for this session.
	ID() string

	// Lang returns the canonical language name of this session.
	Lang() string

	// Eval executes code in the session and returns the execution result.
	// If the eval times out or exceeds resource limits without AutoRestart,
	// the session is killed and subsequent calls return [ErrSessionKilled].
	Eval(ctx context.Context, code string) (*Result, error)

	// Reset clears the session state or restarts the guest interpreter instance.
	Reset(ctx context.Context) error

	// Close terminates the session, killing the interpreter and freeing resources.
	Close() error

	// Alive reports whether the session interpreter is currently alive and accepting evals.
	Alive() bool
}

Session represents a stateful interactive interpreter session (REPL). Variables, imports, and definitions persist across successive Session.Eval calls. Calls to Eval on the same Session are serialized.

type SessionBackend

type SessionBackend interface {
	NewSession(ctx context.Context, req *SessionRequest) (Session, error)
}

SessionBackend is an optional interface implemented by backends capable of running stateful sessions.

type SessionConfig

type SessionConfig struct {
	// ID is the session identifier. If empty, a cryptographically secure random ID is assigned.
	ID string

	// Limits holds resource limits. Zero values receive sensible defaults.
	Limits Limits

	// AutoRestart determines whether a killed session (e.g. on timeout) is automatically
	// recreated on the next Eval. When true, Result.Restarted is set to true on the first eval after restart.
	AutoRestart bool

	// IdleTimeout is how long the session can remain without an Eval call before being closed.
	IdleTimeout time.Duration

	// MaxLifetime is the hard ceiling on total session duration from creation.
	MaxLifetime time.Duration

	// MaxEvals is the maximum number of Eval calls allowed before the session closes.
	MaxEvals int

	// Env specifies environment variables passed to the session runtime.
	Env map[string]string
}

SessionConfig configures an interactive session.

type SessionOpt

type SessionOpt func(*SessionConfig)

SessionOpt configures session creation options.

func WithAutoRestart

func WithAutoRestart(auto bool) SessionOpt

WithAutoRestart configures whether the session automatically restarts after being killed.

func WithIdleTimeout

func WithIdleTimeout(d time.Duration) SessionOpt

WithIdleTimeout sets the inactivity duration before an idle session is eligible for reaping.

func WithMaxEvals

func WithMaxEvals(n int) SessionOpt

WithMaxEvals sets the maximum number of Eval operations permitted on this session.

func WithMaxLifetime

func WithMaxLifetime(d time.Duration) SessionOpt

WithMaxLifetime sets the maximum total lifetime of the session.

func WithSessionEnv

func WithSessionEnv(env map[string]string) SessionOpt

WithSessionEnv sets environment variables available to the session interpreter.

func WithSessionID

func WithSessionID(id string) SessionOpt

WithSessionID sets an explicit ID for the session.

func WithSessionLimits

func WithSessionLimits(l Limits) SessionOpt

WithSessionLimits overrides the default resource limits for this session.

type SessionRequest

type SessionRequest struct {
	Pack   *Pack
	Config SessionConfig
	FS     *vfs.FS
}

SessionRequest contains the parameters for starting a session on a backend.

type Spec

type Spec struct {
	// Lang selects the language pack (case-insensitive; aliases allowed).
	Lang string
	// Code is the program source.
	Code string
	// Args are passed to the program.
	Args []string
	// Env is the complete environment visible to the guest. Nothing is
	// inherited from the host.
	Env map[string]string
	// Stdin is the program's standard input. Nil means empty.
	Stdin io.Reader
	// Files are injected read-only under /in. Keys are slash-separated
	// paths relative to /in and are validated by [vfs.Clean].
	Files map[string][]byte
	// Limits overrides the sandbox defaults field by field. Nil keeps them.
	Limits *Limits
	// Net is the network policy. Nil means no network access at all.
	Net *NetPolicy
}

Spec describes one execution.

type Usage

type Usage struct {
	// Wall is the elapsed time.
	Wall time.Duration
	// PeakMemory is the peak guest memory in bytes, if the backend reports it.
	PeakMemory uint64
	// FSBytes is the virtual filesystem size at the end of the run.
	FSBytes uint64
	// FSFiles is the number of files and directories at the end of the run.
	FSFiles int
}

Usage reports resources consumed by one execution.

type WasmSpec

type WasmSpec struct {
	// Module is the interpreter or runtime .wasm.
	Module Artifact
	// Args are the fixed arguments passed to the module.
	Args []string
	// Mounts are extra read-only files (for example a standard library).
	Mounts []Mount
	// SessionDriver is the REPL driver script used for sessions, if any.
	SessionDriver string
}

WasmSpec describes running a language as a WebAssembly module.

Directories

Path Synopsis
Package artifact manages fetching, caching, and SHA-256 verification of language runtimes (.wasm modules, libraries, etc.).
Package artifact manages fetching, caching, and SHA-256 verification of language runtimes (.wasm modules, libraries, etc.).
backend
wasm
Package wasm implements the WebAssembly isolation backend using wazero.
Package wasm implements the WebAssembly isolation backend using wazero.
cmd
sandbox command
Command sandbox provides a unified command-line interface for running, testing, serving, and diagnosing sandboxed code executions.
Command sandbox provides a unified command-line interface for running, testing, serving, and diagnosing sandboxed code executions.
examples
hello command
Command hello shows the shape of the sandbox API.
Command hello shows the shape of the sandbox API.
repl command
Command repl demonstrates interactive stateful REPL sessions in Python and JavaScript.
Command repl demonstrates interactive stateful REPL sessions in Python and JavaScript.
run-docker command
Command run-docker demonstrates executing code inside hardened Docker containers.
Command run-docker demonstrates executing code inside hardened Docker containers.
run-js command
Command run-js demonstrates running untrusted JavaScript inside the Wasm sandbox.
Command run-js demonstrates running untrusted JavaScript inside the Wasm sandbox.
run-lua command
Command run-lua demonstrates running untrusted Lua inside the Wasm sandbox with zero Docker.
Command run-lua demonstrates running untrusted Lua inside the Wasm sandbox with zero Docker.
run-python command
Command run-python demonstrates running untrusted Python inside the Wasm sandbox.
Command run-python demonstrates running untrusted Python inside the Wasm sandbox.
run-ts command
Command run-ts demonstrates running untrusted TypeScript inside the Wasm sandbox without Node.js or Docker.
Command run-ts demonstrates running untrusted TypeScript inside the Wasm sandbox without Node.js or Docker.
scripts command
serve-docker command
Command serve-docker demonstrates running a server in a hardened Docker container and exposing it safely to the host through the sandbox proxy.
Command serve-docker demonstrates running a server in a hardened Docker container and exposing it safely to the host through the sandbox proxy.
serve-js command
Command serve-js demonstrates exposing a JavaScript service via Wasm handler bridge.
Command serve-js demonstrates exposing a JavaScript service via Wasm handler bridge.
internal
fake
Package fake is an in-process backend used only to test the sandbox core.
Package fake is an in-process backend used only to test the sandbox core.
limitbuf
Package limitbuf provides output capture with a hard byte budget.
Package limitbuf provides output capture with a hard byte budget.
Package mcp implements the Model Context Protocol (MCP) server for micromax/sandbox, enabling AI agents and assistants (Claude Desktop, Cursor, OpenAI assistants, etc.) to securely execute untrusted code.
Package mcp implements the Model Context Protocol (MCP) server for micromax/sandbox, enabling AI agents and assistants (Claude Desktop, Cursor, OpenAI assistants, etc.) to securely execute untrusted code.
packs
bash
Package bash provides the Bash/Shell language pack for the Docker backend.
Package bash provides the Bash/Shell language pack for the Docker backend.
go
Package golang provides the Go language pack for the Docker backend.
Package golang provides the Go language pack for the Docker backend.
java
Package java provides the Java language pack for the Docker backend.
Package java provides the Java language pack for the Docker backend.
js
Package js provides the JavaScript language pack using QuickJS compiled to WebAssembly (WASI).
Package js provides the JavaScript language pack using QuickJS compiled to WebAssembly (WASI).
lua
Package lua provides the Lua 5.4 language pack using a WASI-compiled Lua runtime.
Package lua provides the Lua 5.4 language pack using a WASI-compiled Lua runtime.
node
Package node provides the Node.js language pack for the Docker backend.
Package node provides the Node.js language pack for the Docker backend.
python
Package python provides the Python language pack using CPython compiled to WebAssembly (WASI).
Package python provides the Python language pack using CPython compiled to WebAssembly (WASI).
rust
Package rust provides the Rust language pack for the Docker backend.
Package rust provides the Rust language pack for the Docker backend.
ts
Package ts provides the TypeScript language pack for the Wasm backend.
Package ts provides the TypeScript language pack for the Wasm backend.
wasm
Package wasm provides a generic WebAssembly/WASI binary pack.
Package wasm provides a generic WebAssembly/WASI binary pack.
Package vfs implements the in-memory virtual filesystem a sandboxed guest sees.
Package vfs implements the in-memory virtual filesystem a sandboxed guest sees.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL