Contents
What Sandcrab is
Sandcrab is a self-hostable Rust sandbox manager and SDK for running untrusted agent code. An agent (or the program driving it) asks for an ephemeral sandbox built from a pinned OCI template, mounts one or more persistent workspaces into it read-write or read-only, runs tools such as bash, file_edit and grep, and throws the sandbox away. The workspace survives, and the host may change its files before the next turn.
Isolation is pluggable through the RuntimeBackend trait. V1 ships two backends: Docker (a hardened shared-kernel container, officially supported, selected explicitly) and Firecracker (KVM microVMs, hardware isolated). Both talk to the same in-sandbox daemon, crabd, over the same length-prefixed JSON-RPC protocol, so tests on Docker exercise the protocol that production uses. Sandcrab never falls back from one backend to another without being told.
Source of the picture: crates/sandcrab-core/src/backend.rs:100 (the trait), crates/sandcrab-core/src/manager.rs:146 (spawn), crates/sandcrab-guest/src/server.rs:384 (the guest server). The README's mermaid chart also lists Cloud Hypervisor and libkrun; those are Phase 2 and have no crate yet.
Crate map
Nine crates in one Cargo workspace. Dependencies point one way: protocol at the bottom, core above it, backends above core, SDK above backends, and the binaries on top. The rules in AGENTS.md §2 are enforced by the [dependencies] sections, which are summarised below as written (workspace-level crates such as serde are omitted).
| Crate (binary) | Role | Key types / entry points | Sandcrab deps · notable external deps |
|---|---|---|---|
sandcrab-protocol | Wire framing, JSON-RPC envelopes, typed tool params/results, JSON Schemas, the init.* control types. | encode_frame, FrameDecoder, RpcRequest, Call, ToolCall, ToolResult, ProtocolError, InitConfig, tool_definitions() | none · schemars, thiserror, uuid. No tokio. |
sandcrab-guest (crabd) | Static musl daemon inside every sandbox: tool server, plus PID 1 init mode for microVMs. | serve_connection, handle_request, tools::dispatch, ToolContext, init::* | protocol · tokio (only the features it uses), rustix, pty-process, ignore, globset, grep-searcher, similar, tar; tokio-vsock on Linux |
sandcrab-core | Backend trait, sandbox lifecycle, workspace registry and leases, templates, the crabd client, safe archive unpacking. | RuntimeBackend, SandboxHandle, BackendCapabilities, SandboxManager, SandboxConfig, WorkspaceRegistry, WorkspaceLease, TemplateRegistry, CrabdClient, unpack_safe | protocol · rustix (fs), tar, toml. No backend crates. |
sandcrab-backend-docker | Docker backend: hardened containers running the host's crabd over a Unix socket. Dev/CI only. | DockerBackend, DockerConfig, build_container_spec, orphan reaping | core, protocol · bollard, rustix, sha2 |
sandcrab-backend-firecracker (sandcrab-rootfs) | Firecracker microVMs: owned HTTP-over-UDS API client, vsock handshake, rootfs pipeline, workspace drives, tap pool, pinned artifacts. | FirecrackerBackend, FirecrackerConfig, ApiClient, vsock_connect, ControlClient, RootfsBuilder | core, protocol · flate2, tar, sha2, rustix. No hyper. |
sandcrab-sdk | Public API: builder with explicit backend, typed sandbox methods, LLM tool_dispatch, workspace and template clients. | Sandcrab, SandcrabBuilder, Sandbox, WorkspaceClient, ToolError | core, protocol; backend-docker (feature docker, default), backend-firecracker (feature firecracker, Linux only) |
sandcrab-cli (sandcrab) | Operator CLI: doctor, workspace, template, rootfs, run, tool. | Commands in main.rs, doctor.rs, run.rs | sdk · clap, anyhow |
sandcrab-agent (crabagent) | Test harness: a minimal coding agent that drives Claude over the sandbox tools. | agent, session, llm::anthropic, llm::fake | sdk · reqwest, rustyline, clap |
sandcrab-bench | Benchmark runner across backends; emits schema-versioned JSON. publish = false. | Scenario (lifecycle, calls, agent-turn, resources, density, drift) | sdk · bollard (optional), schemars, sha2 |
Boundary to protect: sandcrab-core must not depend on bollard or anything Firecracker-specific, and nothing above crabd may shell out with docker exec. Backends only hand core a Connector; everything else goes over the wire.
Life of a tool call
sandbox.bash("ls") through six hops.-
SDK: a typed method, or an LLM's JSON
Sandbox::bashbuilds aBashParamsand calls the typed path. An agent loop usestool_dispatchinstead, which parses(name, input)into aToolCalland turns recoverable failures into a JSON{"error":{…}}for the model, keepingErrfor fatal ones (sandbox gone, transport lost).crates/sandcrab-sdk/src/sandbox.rs:167Rust pub async fn bash(&self, command: impl Into<String>) -> Result<BashResult> { self.bash_with(BashParams { command: command.into(), cwd: None, env: Default::default(), timeout_ms: None, }) .await }
crates/sandcrab-sdk/src/dispatch.rs:127Rust pub async fn tool_dispatch(&self, name: &str, input: Value) -> Result<Value, ToolError> { match self.tool_call(name, input).await { Ok(v) => Ok(v), Err(e) if !e.fatal => Ok(e.to_json()), Err(e) => Err(e), } }
-
Core: the live sandbox
sandcrab_core::Sandbox::call_toolrefuses calls on a destroyed sandbox, forwards to the per-sandboxCrabdClient, and records theFirstCalltiming mark on the first response (success or tool error).crates/sandcrab-core/src/manager.rs:670Rust pub async fn call_tool(&self, call: ToolCall) -> Result<ToolResult> { if self.is_destroyed() { return Err(SandboxError::not_found("sandbox", self.id())); } let result = self.shared.client.call(call).await; if matches!(result, Ok(_) | Err(SandboxError::Protocol(_))) { self.shared.timings.mark(LifecyclePhase::FirstCall); } result }
-
CrabdClient: id, frame, wait
The client is multiplexed: each request gets a fresh
i64id and aoneshotwaiter; a writer task sends frames and a reader task routes responses by id, so concurrent calls on one sandbox may complete out of order. The timeout is the default call timeout (150 s), or a bashtimeout_msplus 10 s of grace when that is longer (client.rs:339effective_timeout). A timed-out call does not poison the connection.crates/sandcrab-core/src/client.rs:225Rust · trimmed pub async fn request(&self, call: &Call, timeout: Duration) -> Result<Value> { let id = self.next_id.fetch_add(1, Ordering::Relaxed); let frame = encode_frame(&call.to_request(id)).map_err(ProtocolError::from)?; // … grab the outbox sender … let (tx, rx) = oneshot::channel(); self.shared.register(id, tx)?; // … PendingGuard unregisters the id if this future is dropped … let exchange = async { outbox.send(frame).await.map_err(|_| self.closed_error())?; rx.await.map_err(|_| self.closed_error()) }; // tokio::time::timeout(timeout, exchange) → SandboxError::Timeout on expiry }
-
The frame on the wire
ADR 0001 §2 fixed the format: a 4-byte big-endian
u32payload length, then that many bytes of JSON-RPC 2.0, withmethod= tool name andparams= the typed params. Zero-length frames and frames over 16 MiB (MAX_FRAME_LEN) are rejected before allocation.00 00 00 42u32 BE length {"jsonrpc":"2.0","id":7,"method":"bash","params":{"command":"ls"}}JSON-RPC 2.0 payload (illustrative: 0x42 = 66 bytes)crates/sandcrab-protocol/src/framing.rs:64Rust pub fn parse_header(header: [u8; HEADER_LEN]) -> Result<usize, FrameError> { let len = u32::from_be_bytes(header) as usize; if len == 0 { return Err(FrameError::Empty); } if len > MAX_FRAME_LEN { return Err(FrameError::TooLarge { len, max: MAX_FRAME_LEN }); } Ok(len) }
Transports: Docker returns
Endpoint::Unix(socket_dir.join(SOCKET_NAME)), bind-mounted in the container at/run/sandcrab/crabd.sock. Firecracker connects to the VMM's vsock UDS, writesCONNECT 1024\nand expectsOK <port>\n(crates/sandcrab-backend-firecracker/src/vsock.rs:23). After that the bytes are identical. -
crabd: read, spawn, answer by id
serve_connectionreads frames under a semaphore ofmax_inflightslots and runs each request on its own task (inside an innertokio::spawn, so a panicking tool still produces anInternalerror response for its id).handle_requestanswershelloandpingitself and hands every tool totools::dispatch, a single exhaustivematch.crates/sandcrab-guest/src/server.rs:116Rust pub async fn handle_request(ctx: &ToolContext, req: RpcRequest) -> RpcResponse { let outcome = match Call::from_request(&req) { Ok(Call::Hello(p)) => Ok(Reply::Hello(hello(ctx, &p))), Ok(Call::Ping) => Ok(Reply::Ping(PingResult {})), Ok(Call::Tool(call)) => { let tool = call.name(); let res = tools::dispatch(ctx, call).await; // … debug-log failures … res.map(Reply::Tool) } Err(e) => Err(e), }; RpcResponse::from_outcome(req.id, outcome) }
crates/sandcrab-guest/src/tools/mod.rs:29Rust · trimmed pub async fn dispatch(ctx: &ToolContext, call: ToolCall) -> Result<ToolResult, ProtocolError> { use ToolCall as C; Ok(match call { C::Bash(p) => exec::bash(ctx, p).await?.into(), C::ProcessStart(p) => process::process_start(ctx, p).await?.into(), // … process_poll/stdin/kill/list, file_read/write/edit/delete/move, // upload, download, list_dir, glob … C::Grep(p) => search::grep(ctx, p).await?.into(), }) }
-
exec::bash: process group, timeout, truncationTide clock: timeout + killpg
bash -cruns with.process_group(0)and.kill_on_drop(true); stdin is/dev/null.- Timeout =
timeout_msor the default (120 s), capped at the max (1 h). - On timeout: SIGTERM the group, wait
KILL_GRACE(500 ms), SIGKILL (terminate_group, exec.rs:130). Not an RPC error:timed_out = true,exit_code = None. - A
GroupGuardSIGKILLs the group if the request future is dropped, and leftovers such asserver &are killed after bash exits.
Few grains: bounded output
- stdout and stderr are pumped concurrently into a
HeadTailbuffer (exec.rs:245), at most 32 KiB per stream by default. - Memory stays bounded while reading; the middle is replaced by
[... N bytes truncated ...], andtruncatedis set. - Output is decoded lossily as UTF-8, so one bad byte cannot break the JSON.
crates/sandcrab-guest/src/tools/exec.rs:59Rust · trimmed let mut cmd = Command::new("bash"); cmd.arg("-c") .arg(&p.command) .current_dir(&cwd) .envs(&p.env) .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .process_group(0) .kill_on_drop(true); let mut child = cmd.spawn().map_err(|e| spawn_error(&e))?; // Armed before anything can fail or be cancelled: SIGKILLs the group on drop. let mut guard = GroupGuard::new(&child); // … spawn stdout/stderr pumps into HeadTail … let (status, timed_out) = match tokio::time::timeout(Duration::from_millis(timeout_ms), child.wait()).await { Ok(status) => (status.map_err(wait_error)?, false), Err(_) => (terminate_group(&mut child, guard.pgid).await?, true), }; // Reap stragglers left in the group (backgrounded jobs) so the pipes reach EOF. guard.kill(Signal::KILL);
Precise wording:
bashmakes its child a process-group leader (setpgidviaprocess_group(0)), not a session leader.setsidis used byprocess_startin PTY mode (crates/sandcrab-guest/src/tools/process.rs). A descendant that callssetsid/setpgiditself escapes the group kill; the documented backstop is container or microVM teardown.The
BashResult(exit_code,signal,stdout,stderr,truncated,timed_out,duration_ms) travels back as a JSON-RPC response with the same id; the client's reader task finds the waiter and the typed value surfaces asResult<BashResult>in the SDK.
Life of a sandbox

Spawn: everything is checked before the backend is touched
SandboxManager::spawn (crates/sandcrab-core/src/manager.rs:146) runs this sequence:
config.validate(); then the capability gate:require_hardware_isolationon a backend without it →HardwareIsolationRequired. Non-emptysecrets→PolicyUnenforceable(reserved for Phase 3).- Template resolve from the
TemplateRegistry; the network policy defaults to the manifest's. Ifbackend.enforces_network_policy(&network)is false →PolicyUnenforceable(no V1 backend enforcesegress_restricted). - Resources = template limits plus overrides; user = config or manifest.
- Mount resolution (
resolve_mounts, crates/sandcrab-core/src/mounts.rs:98): guest paths normalised, no duplicates or nesting, none under/proc /sys /dev /run/sandcrab /opt/sandcrab.default_cwd= explicit → first rw mount → template workdir. - Leases for each mount (rw exclusive, ro shared); the lease's verified root,
(dev, ino)and generation are copied into theResolvedMount. backend.spawn(&spec), markBackendStarted, then aSpawnGuardowns the handle so a cancelled spawn future cannot leak the sandbox.- Ready:
wait_readyretries connect +hello(backoff 2 ms ×1.5, capped at 20 ms) untilready_timeout(30 s default). A protocol-version mismatch is fatal. Failure destroys the handle. - The sandbox enters the active map and the TTL reaper task is started if it is not already running.
Docker spawn
verify_image: the image ID must match this host's pin for the template (unpinned images refused unlessallow_unpinned_images).- Per-sandbox socket dir on the host, mounted at
/run/sandcrab. - Hardened container (§6), entrypoint pinned to
/opt/sandcrab/crabd serve --unix /run/sandcrab/crabd.sock;crabdis bind-mounted read-only from the host, never baked into the image. - Workspace roots are re-verified with
verify_workspace_rootbefore the bind mount is built.
Firecracker spawn
- Cached read-only rootfs + a sparse per-sandbox scratch drive (overlayfs in the guest).
- Each mount becomes an ext4 drive
ws<n>: ro images cached, rw images built per spawn. - Optional tap from the pre-created pool (only for
unrestricted), cgroup v2 leaf, then the VMM API: machine config, boot source, drives,InstanceStart. crabdis PID 1; the host sendsInitConfigover vsock control port 1 (init.configure), and init startscrabd serveon port 1024 as the sandbox user.
let init = InitConfig { sandbox_id: spec.id.to_string(), hostname: format!("sc-{}", &spec.id.to_string()[..8]), user: InitUser { uid: user.uid, gid: user.gid, home: None, name: None }, env: spec.env.clone(), default_cwd: spec.default_cwd.clone(), mounts: guest_mounts, network: net.is_some(), // dns: only when a NIC exists tools_port: DEFAULT_TOOLS_PORT, host_time_unix_ms: unix_ms(), }; let configured = init_guest(vm, &init, deadline, t).await?;
Destroy: single-flight
Explicit destroy, the SDK drop guard, the TTL reaper and shutdown can all race. SandboxShared::start_teardown takes the live handle out of a Mutex<Option<Live>>, so exactly one caller starts the teardown; it runs on a runtime task (a cancelled caller cannot abort it) and everyone awaits the same outcome on a watch channel. A TeardownGuard publishes an outcome even on panic or runtime shutdown, and removes the sandbox from the active list before waking waiters. If the backend teardown fails, rw leases are released as failed and the workspace is marked dirty.
async fn destroy(self: &Arc<Self>) -> Result<TimingMarks> { self.start_teardown(); let mut rx = self.teardown.subscribe(); match rx.wait_for(Option::is_some).await { Ok(outcome) => outcome.clone().expect("checked by wait_for"), // Unreachable: the sender lives in `self`. Err(_) => Err(self.teardown_error("teardown outcome channel closed")), } }
Backend teardown: Docker stops and removes the container and its socket dir with a stop grace. Firecracker first syncs back every rw drive (§5), then stops the VM (graceful init.shutdown, then fallbacks) and cleans the run dir, preserving images whose sync-back failed (crates/sandcrab-backend-firecracker/src/vm.rs:501).
TTL reaper
DEFAULT_TTL_SECS). ensure_reaper runs a tokio interval (1 s default) holding only a Weak to the manager, collects expired sandboxes and destroys them through the same single-flight path (manager.rs:349).Timing marks
Every sandbox carries LifecycleTimings; the phases are the LifecyclePhase enum (crates/sandcrab-core/src/timings.rs:18). The standard phases match the benchmark spec's metric boundaries; backends add custom marks.
spawn_requestedspawn enteredBackendStartedcontainer started / InstanceStartReadyfirst hello parsedFirstCallfirst tool responseTeardownStarteddestroy enteredTeardownFinishedresources releasedCustom marks: Docker image_verified; Firecracker rootfs_ready, ws_attach_start, ws_attach_done, vmm_started, ws_sync_done, vmm_exited, cleanup_done.
Workspaces

The model
A Workspace has an id, a name, a generation counter and a backing (crates/sandcrab-core/src/workspace.rs:123):
HostDir(PathBuf): an existing user directory, registered canonical; never deleted by Sandcrab.ManagedDir(PathBuf): lives at<state_root>/workspaces/<id>/data(state root~/.sandcrab, or$SANDCRAB_HOME).BlockVolume(PathBuf): reserved in V1; a backend may attach it directly, host file ops are not implemented.
Mounts are MountMode::ReadWrite or ReadOnly; one sandbox can mount several workspaces at disjoint guest paths.
Host-side mutation between turns
WorkspaceRegistry::put_file, read_file, delete_file and list_files (exposed through the SDK's WorkspaceClient) let the host add attachments or collect output between agent turns. While a rw lease is held by any process, host mutation fails with WorkspaceBusy unless the caller opts in with HostWriteOptions::force; reads are always allowed. put_file bumps the generation, which invalidates cached read-only images.
Race-free, fd-relative file ops
A rw-mounted workspace is attacker-controlled, and it can change between any two host syscalls (a guest looping renameat2(RENAME_EXCHANGE) to swap a directory with a symlink). So crates/sandcrab-core/src/fsx.rs never checks a path and then re-walks it by name:
- The root is opened once; every walk is relative to that fd.
- On Linux the directory walk is a single
openat2withRESOLVE_BENEATH | RESOLVE_NO_SYMLINKS | RESOLVE_NO_MAGICLINKS; elsewhere, or whenopenat2is unavailable, oneopenat(O_DIRECTORY | O_NOFOLLOW)per component. - Writes go to a fresh
O_CREAT | O_EXCLtemp file in the target dir fd, thenrenameatwithin that fd; deletes useunlinkaton the parent fd. - Any symlink on the path, even one pointing inside the workspace, is refused with
PathEscape.
match rustix::fs::openat2( root, &path, DIR_FLAGS, Mode::empty(), ResolveFlags::BENEATH | ResolveFlags::NO_SYMLINKS | ResolveFlags::NO_MAGICLINKS, ) { Ok(fd) => return Ok(fd), // No openat2 (old kernel, seccomp), a spurious resolution retry, or ENOTDIR // (possibly a symlink as the last component): walk instead, which classifies. Err(Errno::NOSYS | Errno::PERM | Errno::AGAIN | Errno::NOTDIR) => {} Err(e) => return Err(map(rel, e)), }
Roots: overlap refusal and dev/ino pinning
- No overlap: workspace roots may not be equal to, an ancestor of, or a descendant of another workspace root or the state root (
ensure_no_overlap, crates/sandcrab-core/src/registry.rs:426). Otherwise a sandbox holding the outer one rw could swap the inner one's root. Overlapping entries in older registries are tolerated but cannot be leased. - Pinned identity: each directory root is stored with its
(dev, ino)(RootIdentity). Every host op and lease reopens it from/withO_NOFOLLOW | O_DIRECTORYper component and compares; a root replaced by a symlink or another directory fails withWorkspaceRootChanged. Backends callverify_workspace_root(registry.rs:400) again right before use.
Leases across processes
WorkspaceRegistry::lease (registry.rs:837) takes non-blocking flocks on <state root>/locks/<id>.mount.lock (exclusive for rw, shared for ro) and <state root>/locks/<id>.rw.lock (held exclusive by the rw lease; host mutation probes it). The lock files live outside the workspace directory, so leasing a registered host directory creates no workspaces/<id>/ entry; remove deletes them. registry.json is written atomically (tmp + fsync + rename) under registry.lock. Releasing a rw lease bumps the generation.
Firecracker: block-volume pack and sync-back
Firecracker has no virtio-fs, so supports_host_dir_mounts = false: the host directory stays the source of truth, copied in at spawn and synced back at teardown (docs/design/firecracker-backend.md §5).
- Pack (
pack_dir, crates/sandcrab-backend-firecracker/src/workspace.rs:54): asandcrab-tar-v1-style tar. Symlinks are stored, not followed; special files skipped; setuid/setgid dropped; ownership normalised to the guest user. - Image (
build_image, :224):mke2fs -dturns the tar into ext4. Read-only images are cached per (generation, tree fingerprint, owner) bycached_ro_image(:281) and shared by every sandbox mounting that generation. - Export: at teardown the guest's
init.exportacks with formatsandcrab-tar-v1and streams the rw tree over vsock. - Unpack (
receive_export, :393 →sandcrab_core::archive::unpack_safe): hostile input. Absolute paths,.., hard links, devices and FIFOs are rejected; setuid/setgid are refused and modes masked (& 0o777 & !umask); duplicates and missing end-of-archive markers fail the whole archive; byte caps follow the drive size, not a constant; zero runs become holes. - Commit (
commit, :433): aManagedDiris swapped atomically (RENAME_EXCHANGEwhere available); aHostDiris mirror-applied in place, which is not atomic (documented V1 trade-off). A failed sync-back preserves the guest image and returns an error.
python-dev can write a chart and the next turn in render can mount the same workspace (perhaps ro) and turn it into a PDF.Security model & invariants

Declared capabilities
| Capability | Docker | Firecracker (V1) | Meaning |
|---|---|---|---|
hardware_isolated | false | true | Guest behind a virtualization boundary, not a shared kernel. |
multi_tenant_safe | false | false | Firecracker stays false until jailer confinement lands (design §8). |
supports_snapshots | false | false | Not in V1. |
supports_host_dir_mounts | true | false | Live sharing vs. copy-in + sync-back. |
| network policies enforced | disabled, unrestricted | disabled, unrestricted | egress_restricted is refused at spawn by both. |
crates/sandcrab-backend-docker/src/backend.rs:322 · crates/sandcrab-backend-firecracker/src/backend.rs:426
No silent downgrade: what you get instead
Each of these is an explicit error. None of them is ever turned into a warning plus a weaker setup.
| Situation | Where | Result |
|---|---|---|
| No backend chosen in the builder | sandcrab-sdk/src/lib.rs:248 | InvalidConfig: "Sandcrab never picks or falls back to a backend" |
require_hardware_isolation on Docker | SDK builder and spawn | HardwareIsolationRequired |
egress_restricted on Docker | backend-docker/src/spec.rs:88 | PolicyUnenforceable: "docker cannot enforce network policy `egress_restricted`…" |
Any secrets | spawn + each backend's reject_secrets | PolicyUnenforceable (Phase 3) |
| Template image ID ≠ this host's pin | Docker verify_image | refused unless allow_unpinned_images / --allow-unpinned |
No /dev/kvm | check_kvm in FirecrackerBackend::new | error; never a switch to Docker |
The CLI mirrors this: the backend is always named explicitly (--backend docker or --backend firecracker); nothing falls back to Docker.
Docker hardening
Built as pure data in build_container_spec, so the whole matrix is unit-tested without a daemon:
host_config: Some(HostConfig { network_mode: Some(mode.to_owned()), // "none" unless unrestricted cap_drop: Some(vec!["ALL".into()]), security_opt: Some(vec!["no-new-privileges:true".into()]), privileged: Some(false), init: Some(true), ipc_mode: Some("private".into()), readonly_rootfs: Some(false), pids_limit: Some(ctx.limits.pids_limit), memory: Some(memory), memory_swap: Some(memory), // no swap nano_cpus: Some(nano_cpus), tmpfs: Some(HashMap::from([( "/tmp".to_owned(), format!("rw,nosuid,nodev,noexec,size={}m,mode=1777", ctx.limits.tmp_size_mb), )])), ulimits: Some(vec![ResourcesUlimits { // no core dumps name: Some("core".into()), soft: Some(0), hard: Some(0), }]), // … }),
Also: runs as the host uid:gid (so bind-mounted files stay editable on the host), published ports bind to 127.0.0.1 only, /tmp is noexec (binaries and shared objects cannot run from it; use $HOME or the workspace), core dumps are disabled so crashes never drop core.* files into a workspace, the entrypoint is pinned to crabd, and disk_mb is not enforced (a warning is logged; overlay2 would need xfs + pquota). The root filesystem stays writable on purpose: templates need a writable HOME and caches, and the layer is discarded on destroy.
Review rounds
The Nebula QA + security review (flow step review) took three rounds:
| Round | Findings | Fix commits (branch feat/phase-1) |
|---|---|---|
| 1 | 1 HIGH (symlink / rename TOCTOU in host workspace ops) + 5 MEDIUM + 5 LOW | 6abe868 fd-relative workspace ops · e021c6d cross-process leases · a5fcf38, 9ae2f01 bounded sync-back, masked modes · dce638b export deadline · 44525fa, ffd05d4 tap anti-spoofing, root-owned setup · 063d351 unpinned images refused · 64a3eed owner-scoped reaping · 96a77e7 CLI destroys on SIGTERM/SIGHUP · e999f92 redacted .env |
| 2 | 1 new HIGH: nested-registration root swap | 9305037 refuse overlapping workspaces, open roots without following symlinks, pin dev/ino · 6ec2d38 bounded remove_tree, read cap · 079f679 crabagent --mount-host |
| 3 | "V1 review: PASS" | n/a |
Deferred to Phase 2 (MEDIUM), so don't assume these are closed:
- Two registries with different
SANDCRAB_HOMEcan still nest roots: the overlap check is per registry. - dockerd and the Firecracker pack step resolve the bind path by name after verification (4 race wins in 80 attempts in review). Planned fix: pack/commit through the verified root fd, and a
crabddev/ino check after start.
Templates & pinning
A template is a standard Dockerfile plus a sandcrab.toml manifest in templates/<name>/. TemplateRegistry::load reads every directory and validates the manifest (crates/sandcrab-core/src/template.rs:18).
| Template | Built from | Contents |
|---|---|---|
base | debian:trixie-20261104-slim@sha256:… | Debian 13 + core utilities |
python-dev | sandcrab/base:0.1.0 (+ uv stage pinned by digest) | Python 3.15, uv, ruff, pytest, mypy |
ts-dev | sandcrab/base:0.1.0 (+ Node 26 and bun stages pinned by digest) | Node.js 26, pnpm, bun, TypeScript, vitest, biome, Debian python3; no browser (use render) |
render | sandcrab/base:0.1.0 (+ Node and typst stages) | Chromium, Playwright, ffmpeg, ImageMagick, Typst |
[template] name = "python-dev" version = "0.1.0" image = "sandcrab/python-dev:0.1.0" # The built image ID is pinned per host, not here (local image IDs do not reproduce # across hosts): `templates/build.sh python-dev` records it under ~/.sandcrab/template-pins. # The Dockerfile FROM base images are digest-pinned. [resources] vcpu = 2 memory_mb = 1024 disk_mb = 4096 [workspace] workdir = "/workspace" [network] default_policy = "disabled" [tools] tiers = ["core", "process"]
What the pin means: templates/build.sh records each built image ID in a host-local pin file (~/.sandcrab/template-pins/<name>/<version>/<arch>.json), and spawns refuse an image that does not match it. That is local integrity (unchanged since this host built it), not provenance: image IDs do not reproduce across hosts yet, because apt packages are not pinned and image stores differ. sandcrab template pin adopts an image that is already present. Base images are pinned by digest in the Dockerfiles; reproducible template digests are a planned follow-up. See docs/template-pins.md.
Rootfs pipeline (Firecracker)
sandcrab/<tpl>:0.1.0 ─docker create+export─▶ rootfs.tar ─augment─▶ rootfs+crabd.tar ─mke2fs -d─▶ rootfs.ext4 (ro, shared)
rootfs::augmentappends/sbin/crabd(static musl, sha-pinned) and the needed empty dirs; ownership stays root.rootfs::mkfsrunsmke2fs -t ext4 -d <tar>(rootless; strategiesnative | container | fakeroot).- Cached at
~/.sandcrab/cache/rootfs/<key>/{rootfs.ext4, manifest.json}withkey = sha256(image_id ‖ crabd_sha256 ‖ PIPELINE_VERSION)(crates/sandcrab-backend-firecracker/src/rootfs/mod.rs:48); the recordedrootfs_sha256is checked on load. - Guest kernel and Firecracker binaries are pinned by SHA-256 in crates/sandcrab-backend-firecracker/src/artifacts.rs and fetched by
scripts/fetch-artifacts.sh(orsandcrab doctor --fix). - Entry points:
scripts/build-rootfs.sh(a thin wrapper), thesandcrab-rootfsbinary andsandcrab rootfs.
crabagent & the bench harness
crabagent
A minimal, pi-style coding agent (crates/sandcrab-agent/src/lib.rs) whose tools are exactly Sandcrab's tools. It exists to exercise the SDK the way a real agent does.
llm::anthropic: Messages API client with SSE streaming, prompt caching and retries; default modelclaude-sonnet-5-5(--model/CRABAGENT_MODEL).agent: the tool-use loop, running parallel tool calls throughSandbox::tool_dispatch.session: workspace resolution (-w,--mount,--mount-host), sandbox lifecycle, REPL or one-shot-p(with--keep-alive SECSto hold published ports after the task); template defaultts-dev. With a managed workspace at the cwd, npm / pip / Playwright caches go to<cwd>/.cacheso installs survive sessions.media: images returned bydownload(or a binaryfile_read) reach the model asimageblocks, never as base64 text; other binaries are summarised.llm::fake: a scripted LLM, so the loop is tested on the fake backend and real Docker without an API key.
sandcrab-bench
Backend-generic runner for docs/plans/phase-1-mvp.bench-spec.md, documented in docs/bench/README.md.
- Scenarios:
lifecycle,calls,agent-turn,resources,density,drift. - Seeded RNG and fixtures, ABAB scheduling, percentile and bootstrap stats, cgroup /
/procsampling, host declaration. - Schema-versioned JSON results; the JSON Schema is committed at
docs/bench/results/schema.json. - V1 measures Docker only. Firecracker is wired in but is recorded as
unavailableon hosts without/dev/kvm, never substituted.
Where to start
Build, test, lint
# unit tests: protocol, core (fake backend), guest tools cargo test --workspace # Docker end-to-end suites (need a Docker daemon, built templates and a static crabd) cargo test --workspace -- --ignored # must pass before committing cargo fmt --all -- --check cargo clippy --workspace --all-targets -- -D warnings # static musl crabd for injection (prints path + SHA-256) scripts/build-crabd.sh # or: scripts/build-crabd.sh aarch64 # build all four templates and pin their image IDs on this host templates/build.sh # check the host: crabd, Docker, template pins, Firecracker prerequisites sandcrab doctor # one command in a throwaway sandbox (the backend is always chosen explicitly) sandcrab --backend docker run -t python-dev -- 'python3 --version'
Reading order
- sandcrab-protocol/src/framing.rs and rpc.rs: the wire, in about 600 lines.
- sandcrab-guest/src/tools/exec.rs: the module doc is the
bashcontract. - sandcrab-core/src/backend.rs then manager.rs: the trait and the lifecycle.
- registry.rs (module doc) and fsx.rs: the security-critical host side.
- sandcrab-core/src/testing.rs:
FakeBackendand the mock crabd (featuretest-util), the fastest way to test lifecycle changes. - The e2e suites in crates/sandcrab-sdk/tests/: harness, lifecycle, security, tools, workspace.
Firecracker status
KVM end-to-end tests pass. The backend, rootfs pipeline, vsock transport, workspace drives, tap pool, published ports and CLI wiring are covered by a fake-VMM suite (crates/sandcrab-backend-firecracker/tests/fake_vmm.rs) and by the real-KVM tests (firecracker_kvm.rs, ignored by default), which pass on a bare-metal KVM host (kvm-dedicated). It still reports multi_tenant_safe = false until jailer confinement lands.
Rules of the road
- Every new backend reports honest
BackendCapabilitiesand refuses what it cannot enforce. - New tools go in
crabd, native Rust (no shelling out tosed/grep/find), with params/results insandcrab-protocolso the schema reaches LLMs and MCP. - Host-side code that touches a workspace goes through
fsx; nevercanonicalizeand re-walk. - Conventional Commits with crate scope, atomic commits, no
.sandcrab/state committed.