Skip to content
Sandcrab

Contributor guide · branch feat/phase-1

A guided tour of the Sandcrab codebase

Follow one tool call from the SDK down a single wire into crabd and back, watch a sandbox molt, see how workspaces persist between turns, and learn which invariants every change must keep. Each claim links to the file and line it comes from.

9 crates 16 tools in crabd 2 backends: Docker · Firecracker 1 wire protocol review: PASS after 3 rounds
A crab messenger walking along a single wire between the host and a sealed jar one wire: every request and result travels the same protocol
Contents
  1. What Sandcrab is
  2. Crate map
  3. Life of a tool call
  4. Life of a sandbox
  5. Workspaces
  6. Security model
  7. Templates & pinning
  8. crabagent & bench
  9. Where to start
01

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.

02

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)RoleKey types / entry pointsSandcrab deps · notable external deps
sandcrab-protocolWire 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-coreBackend trait, sandbox lifecycle, workspace registry and leases, templates, the crabd client, safe archive unpacking.RuntimeBackend, SandboxHandle, BackendCapabilities, SandboxManager, SandboxConfig, WorkspaceRegistry, WorkspaceLease, TemplateRegistry, CrabdClient, unpack_safeprotocol · rustix (fs), tar, toml. No backend crates.
sandcrab-backend-dockerDocker backend: hardened containers running the host's crabd over a Unix socket. Dev/CI only.DockerBackend, DockerConfig, build_container_spec, orphan reapingcore, 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, RootfsBuildercore, protocol · flate2, tar, sha2, rustix. No hyper.
sandcrab-sdkPublic API: builder with explicit backend, typed sandbox methods, LLM tool_dispatch, workspace and template clients.Sandcrab, SandcrabBuilder, Sandbox, WorkspaceClient, ToolErrorcore, 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.rssdk · clap, anyhow
sandcrab-agent (crabagent)Test harness: a minimal coding agent that drives Claude over the sandbox tools.agent, session, llm::anthropic, llm::fakesdk · reqwest, rustyline, clap
sandcrab-benchBenchmark 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.

03

Life of a tool call

One wire. The same frames travel over a Unix socket (Docker), TCP (tests) and vsock (Firecracker). Follow sandbox.bash("ls") through six hops.
  1. SDK: a typed method, or an LLM's JSON

    Sandbox::bash builds a BashParams and calls the typed path. An agent loop uses tool_dispatch instead, which parses (name, input) into a ToolCall and turns recoverable failures into a JSON {"error":{…}} for the model, keeping Err for 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),
        }
    }
  2. Core: the live sandbox

    sandcrab_core::Sandbox::call_tool refuses calls on a destroyed sandbox, forwards to the per-sandbox CrabdClient, and records the FirstCall timing 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
    }
  3. CrabdClient: id, frame, wait

    The client is multiplexed: each request gets a fresh i64 id and a oneshot waiter; 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 bash timeout_ms plus 10 s of grace when that is longer (client.rs:339 effective_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
    }
  4. The frame on the wire

    ADR 0001 §2 fixed the format: a 4-byte big-endian u32 payload length, then that many bytes of JSON-RPC 2.0, with method = tool name and params = 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, writes CONNECT 1024\n and expects OK <port>\n (crates/sandcrab-backend-firecracker/src/vsock.rs:23). After that the bytes are identical.

  5. crabd: read, spawn, answer by id

    serve_connection reads frames under a semaphore of max_inflight slots and runs each request on its own task (inside an inner tokio::spawn, so a panicking tool still produces an Internal error response for its id). handle_request answers hello and ping itself and hands every tool to tools::dispatch, a single exhaustive match.

    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(),
        })
    }
  6. exec::bash: process group, timeout, truncation

    Tide clock: timeout + killpg

    • bash -c runs with .process_group(0) and .kill_on_drop(true); stdin is /dev/null.
    • Timeout = timeout_ms or 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 GroupGuard SIGKILLs the group if the request future is dropped, and leftovers such as server & are killed after bash exits.

    Few grains: bounded output

    • stdout and stderr are pumped concurrently into a HeadTail buffer (exec.rs:245), at most 32 KiB per stream by default.
    • Memory stays bounded while reading; the middle is replaced by [... N bytes truncated ...], and truncated is 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: bash makes its child a process-group leader (setpgid via process_group(0)), not a session leader. setsid is used by process_start in PTY mode (crates/sandcrab-guest/src/tools/process.rs). A descendant that calls setsid/setpgid itself 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 as Result<BashResult> in the SDK.

04

Life of a sandbox

A crab stepping out of its old shell, which stays behind on the sand
Molting: the shell (sandbox) is discarded every time; what the crab carries out (workspace changes) survives.

Spawn: everything is checked before the backend is touched

SandboxManager::spawn (crates/sandcrab-core/src/manager.rs:146) runs this sequence:

  1. config.validate(); then the capability gate: require_hardware_isolation on a backend without it → HardwareIsolationRequired. Non-empty secrets → PolicyUnenforceable (reserved for Phase 3).
  2. Template resolve from the TemplateRegistry; the network policy defaults to the manifest's. If backend.enforces_network_policy(&network) is false → PolicyUnenforceable (no V1 backend enforces egress_restricted).
  3. Resources = template limits plus overrides; user = config or manifest.
  4. 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.
  5. Leases for each mount (rw exclusive, ro shared); the lease's verified root, (dev, ino) and generation are copied into the ResolvedMount.
  6. backend.spawn(&spec), mark BackendStarted, then a SpawnGuard owns the handle so a cancelled spawn future cannot leak the sandbox.
  7. Ready: wait_ready retries connect + hello (backoff 2 ms ×1.5, capped at 20 ms) until ready_timeout (30 s default). A protocol-version mismatch is fatal. Failure destroys the handle.
  8. 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 unless allow_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; crabd is bind-mounted read-only from the host, never baked into the image.
  • Workspace roots are re-verified with verify_workspace_root before the bind mount is built.

crates/sandcrab-backend-docker/src/backend.rs:339

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.
  • crabd is PID 1; the host sends InitConfig over vsock control port 1 (init.configure), and init starts crabd serve on port 1024 as the sandbox user.

crates/sandcrab-backend-firecracker/src/backend.rs:203

crates/sandcrab-backend-firecracker/src/backend.rs:203 · spawn_vmRust · trimmed
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.

crates/sandcrab-core/src/manager.rs:471Rust
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

Tide clock. Default TTL is 30 min (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 entered
BackendStartedcontainer started / InstanceStart
Readyfirst hello parsed
FirstCallfirst tool response
TeardownStarteddestroy entered
TeardownFinishedresources released

Custom marks: Docker image_verified; Firecracker rootfs_ready, ws_attach_start, ws_attach_done, vmm_started, ws_sync_done, vmm_exited, cleanup_done.

05

Workspaces

A crab's burrow under the sand, with crates of files stored below while crabs come and go above
Burrow: sandboxes come and go above; the files stay below.

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.

Window vs. door. ro is a window (look, don't touch: the kernel enforces it on the bind mount or the drive is attached read-only); rw is a door, and only one sandbox may hold it at a time.

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 openat2 with RESOLVE_BENEATH | RESOLVE_NO_SYMLINKS | RESOLVE_NO_MAGICLINKS; elsewhere, or when openat2 is unavailable, one openat(O_DIRECTORY | O_NOFOLLOW) per component.
  • Writes go to a fresh O_CREAT | O_EXCL temp file in the target dir fd, then renameat within that fd; deletes use unlinkat on the parent fd.
  • Any symlink on the path, even one pointing inside the workspace, is refused with PathEscape.
crates/sandcrab-core/src/fsx.rs:170 · open_dirRust · trimmed
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 / with O_NOFOLLOW | O_DIRECTORY per component and compares; a root replaced by a symlink or another directory fails with WorkspaceRootChanged. Backends call verify_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).

  1. Pack (pack_dir, crates/sandcrab-backend-firecracker/src/workspace.rs:54): a sandcrab-tar-v1-style tar. Symlinks are stored, not followed; special files skipped; setuid/setgid dropped; ownership normalised to the guest user.
  2. Image (build_image, :224): mke2fs -d turns the tar into ext4. Read-only images are cached per (generation, tree fingerprint, owner) by cached_ro_image (:281) and shared by every sandbox mounting that generation.
  3. Export: at teardown the guest's init.export acks with format sandcrab-tar-v1 and streams the rw tree over vsock.
  4. 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.
  5. Commit (commit, :433): a ManagedDir is swapped atomically (RENAME_EXCHANGE where available); a HostDir is mirror-applied in place, which is not atomic (documented V1 trade-off). A failed sync-back preserves the guest image and returns an error.
Hermit handoff. Because the workspace outlives the sandbox, a turn in 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.
06

Security model & invariants

A crab sealed inside its own glass jar beside crabs sharing one tide pool
Sealed jar (Firecracker microVM, own kernel) vs. shared tide pool (Docker, shared host kernel).

Declared capabilities

CapabilityDockerFirecracker (V1)Meaning
hardware_isolatedfalsetrueGuest behind a virtualization boundary, not a shared kernel.
multi_tenant_safefalsefalseFirecracker stays false until jailer confinement lands (design §8).
supports_snapshotsfalsefalseNot in V1.
supports_host_dir_mountstruefalseLive sharing vs. copy-in + sync-back.
network policies enforceddisabled, unrestricteddisabled, unrestrictedegress_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.

SituationWhereResult
No backend chosen in the buildersandcrab-sdk/src/lib.rs:248InvalidConfig: "Sandcrab never picks or falls back to a backend"
require_hardware_isolation on DockerSDK builder and spawnHardwareIsolationRequired
egress_restricted on Dockerbackend-docker/src/spec.rs:88PolicyUnenforceable: "docker cannot enforce network policy `egress_restricted`…"
Any secretsspawn + each backend's reject_secretsPolicyUnenforceable (Phase 3)
Template image ID ≠ this host's pinDocker verify_imagerefused unless allow_unpinned_images / --allow-unpinned
No /dev/kvmcheck_kvm in FirecrackerBackend::newerror; 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:

crates/sandcrab-backend-docker/src/spec.rs:265Rust · trimmed
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:

RoundFindingsFix commits (branch feat/phase-1)
11 HIGH (symlink / rename TOCTOU in host workspace ops) + 5 MEDIUM + 5 LOW6abe868 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
21 new HIGH: nested-registration root swap9305037 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_HOME can 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 crabd dev/ino check after start.
07

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).

TemplateBuilt fromContents
basedebian:trixie-20261104-slim@sha256:…Debian 13 + core utilities
python-devsandcrab/base:0.1.0 (+ uv stage pinned by digest)Python 3.15, uv, ruff, pytest, mypy
ts-devsandcrab/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)
rendersandcrab/base:0.1.0 (+ Node and typst stages)Chromium, Playwright, ffmpeg, ImageMagick, Typst
templates/python-dev/sandcrab.tomlTOML
[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)

docs/design/firecracker-backend.md §2pipeline
sandcrab/<tpl>:0.1.0 ─docker create+export─▶ rootfs.tar ─augment─▶ rootfs+crabd.tar ─mke2fs -d─▶ rootfs.ext4 (ro, shared)
  • rootfs::augment appends /sbin/crabd (static musl, sha-pinned) and the needed empty dirs; ownership stays root.
  • rootfs::mkfs runs mke2fs -t ext4 -d <tar> (rootless; strategies native | container | fakeroot).
  • Cached at ~/.sandcrab/cache/rootfs/<key>/{rootfs.ext4, manifest.json} with key = sha256(image_id ‖ crabd_sha256 ‖ PIPELINE_VERSION) (crates/sandcrab-backend-firecracker/src/rootfs/mod.rs:48); the recorded rootfs_sha256 is 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 (or sandcrab doctor --fix).
  • Entry points: scripts/build-rootfs.sh (a thin wrapper), the sandcrab-rootfs binary and sandcrab rootfs.
08

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 model claude-sonnet-5-5 (--model / CRABAGENT_MODEL).
  • agent: the tool-use loop, running parallel tool calls through Sandbox::tool_dispatch.
  • session: workspace resolution (-w, --mount, --mount-host), sandbox lifecycle, REPL or one-shot -p (with --keep-alive SECS to hold published ports after the task); template default ts-dev. With a managed workspace at the cwd, npm / pip / Playwright caches go to <cwd>/.cache so installs survive sessions.
  • media: images returned by download (or a binary file_read) reach the model as image blocks, 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 / /proc sampling, 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 unavailable on hosts without /dev/kvm, never substituted.
09

Where to start

Build, test, lint

shellfrom the repo root
# 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

  1. sandcrab-protocol/src/framing.rs and rpc.rs: the wire, in about 600 lines.
  2. sandcrab-guest/src/tools/exec.rs: the module doc is the bash contract.
  3. sandcrab-core/src/backend.rs then manager.rs: the trait and the lifecycle.
  4. registry.rs (module doc) and fsx.rs: the security-critical host side.
  5. sandcrab-core/src/testing.rs: FakeBackend and the mock crabd (feature test-util), the fastest way to test lifecycle changes.
  6. 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 BackendCapabilities and refuses what it cannot enforce.
  • New tools go in crabd, native Rust (no shelling out to sed/grep/find), with params/results in sandcrab-protocol so the schema reaches LLMs and MCP.
  • Host-side code that touches a workspace goes through fsx; never canonicalize and re-walk.
  • Conventional Commits with crate scope, atomic commits, no .sandcrab/ state committed.

See also 3D kit · roadmap