MOAT

One microVM per task. Never reused. Burned when the task ends.

Moat is a Go control plane that starts, isolates, and reaps Firecracker microVMs as disposable, hardware-isolated sandboxes. This guide works from the isolation boundary outward: first the mechanism, then each package, then the supply chain, the build, the API, and how to run moatd in your own environment.

module: github.com/M30W-M1X/moat go 1.27.0 kernel: vmlinux 6.1.182 (pinned) base: alpine@sha256:c64c687c…

01Architecture at a glance

A single daemon, moatd, owns the control plane: authentication, concurrency quotas, templates, a TTL janitor, Prometheus metrics, and structured request logs. Everything that touches an untrusted workload lives behind it — the warm pool, the Firecracker driver, the egress proxy — and each running sandbox is one microVM with its own kernel, network namespace, and cgroup.

CLIENT agent / CI / SDK HTTP + bearer token POST /v1/sandboxes · /exec HOST — CONTROL PLANE moatd internal/server auth · quota template · TTL janitor internal/pool — warm running VMs internal/vm — Firecracker + jailer internal/egress — domain policy acquire cold boot HTTP(S)_PROXY vsock :5252 · gRPC ONE MICROVM — ONE TASK SESSION guest/agent — PID 1 Exec · WriteFile · ReadFile · Info netns + TAP /30 · nftables cgroup v2 cpu · mem · pids rootfs.ext4 (ro) + vmlinux · scratch
Fig 1 The daemon is the only thing a client talks to. The pool, the driver, and the proxy sit behind it, and every workload runs inside one short-lived microVM reached only over vsock.

The lifecycle of one request

A create then exec then destroy moves through the daemon, the boot path, the network setup, and the guest agent. The audit log records each boundary crossing.

client moatd pool / vm netconf guest agent POST /v1/sandboxes auth · quota reserve · resolve template Acquire or Boot Apply Plan — netns · TAP · /30 · nft dial vsock · Info readiness 201 { id } POST /v1/sandboxes/{id}/exec Exec stream (argv · env · stdin · timeout) NDJSON: started · stdout/stderr · exit DELETE (or TTL janitor · shutdown) Stop — kill VMM · remove cgroup Destroy Plan · quota release 204
Fig 2 Teal arrows are the client-visible request and response. Grey arrows are internal calls. The exec stream stays open for the life of the process.

02Repository layout

internal/ is a Go internal tree — nothing outside the module imports it. External code uses internal/moatapi or the HTTP API.

Path~LinesResponsibility
cmd/moat1540host CLI: demo run snapshot restore bench reap doctor template audit
cmd/moatd690the northbound HTTP daemon and its config loader
cmd/moat-mcp440Model Context Protocol server (stdio) for AI agents
cmd/moat-uffd290userfaultfd page-fault handler for restore -uffd
guest/agent470the in-VM agent: PID 1, mounts pseudo-fs, reaps children, serves gRPC over vsock
internal/vm1225Firecracker driver: Boot, Restore, snapshot + diff, Reconcile
internal/agentclient410host-side gRPC client for the guest agent
internal/vsockconn190host→guest dial through Firecracker's vsock mux socket
internal/config380Machine config, kernel args, run + data directory resolution
internal/netconf920per-VM netns + veth + TAP + /30 IPAM + nftables rules
internal/cgroup230cgroup v2 cpu.max / memory.max / pids.max on the VMM
internal/pool450warm pool of running microVMs, leases with TTL + idle timeout
internal/server3000the HTTP API, auth, quotas, templates, janitor, metrics, the image check
internal/egress800forward + transparent egress proxy with a domain policy
internal/secretscan470ingress secret firewall — vendored Gitleaks rules, in-repo evaluator
internal/audit2100append-only, hash-chained audit log: writer, reader, per-sandbox report
internal/imagelock290load and verify images.lock at daemon startup
internal/moatapi490Go client for the moatd HTTP API
build/—fetch-kernel.sh, build-rootfs.sh, sbomgen, gen-images-lock.sh, images-verify.sh
proto/agent/v1—the guest-agent protobuf; gen/ holds committed generated code

03The security model

Moat runs code it does not trust. The isolation is layered so a break in one layer still meets another. Read the diagram from the untrusted centre outward.

HOST KERNEL · KVM · moatd (trusted) egress proxy — domain allow / deny · transparent DNAT stops: exfiltration to an arbitrary domain netns + veth + TAP + nftables stops: reaching the host, other VMs, 169.254/16, RFC-1918 cgroup v2 caps + Firecracker rate limiters stops: CPU / memory / PID / bandwidth starvation KVM + Firecracker VMM — minimal device model stops: a guest-kernel exploit reaching the host kernel jailer — chroot · seccomp · dropped caps · own uid stops: a VMM compromise acting with privilege untrusted guest process every command · every byte written · every packet files reach it only through vsock RPCs — there is no shared mount
Fig 3 Each band names its mechanism and what it stops. The vermilion box is the only untrusted element inside the host boundary. A caller's files reach it only through vsock RPCs.

Threat model

  • Trusted: the host kernel, KVM, Firecracker and the jailer, moatd, the guest agent binary, the pinned kernel and base image.
  • Untrusted: every process the guest runs, every byte it writes, every packet it sends, and every file a caller asks to put into a sandbox.
  • Out of scope: a KVM or hardware (microcode, speculative execution) vulnerability, a malicious host operator, GPU workloads (Firecracker has no VFIO — DD-11).
Known gap · G-19 The cold-boot rootfs is read-write. vm.Boot attaches the root drive with IsReadOnly: false, and coldBoot points the machine straight at the template rootfs.ext4. Only the warm pool copies the rootfs per member, so a non-pooled sandbox writes into the shared template image for the life of that boot. The fix — attach the root drive read-only, or copy per sandbox — is a planned VM-driver change.
Also The jailer path (-jail) and real-uplink NAT need a root host. UFFD restore needs read access to /dev/userfaultfd or vm.unprivileged_userfaultfd=1 (G-14).

04Firecracker driver — internal/vm

Boot(ctx, m config.Machine, log) (*Instance, error) builds a firecracker.Config — one root drive, one vsock device, and a network interface when m.Net is set — then startMachine applies either the jailer (cfg.JailerCfg) or a plain unprivileged process, starts the VMM, and waits for the guest agent on vsock. Instance holds the VMM pid so internal/cgroup can cap it.

Cold boot versus snapshot restore

COLD BOOT · moat run / coldBoot baseConfig + jailer start VMM kernel handoffinit=/sbin/guest-agent mount fs · vsock listenInfo OK ≈ 1.1 s to a ready agent SNAPSHOT RESTORE · moat restore fresh VMM · snapshot/loadsnapshot.bin + mem.bin resume paused guestclock resync agent answers ≈ 25 ms to a ready agent Diff snapshot: sparse mem.bin, only changed pages, rebased onto a base copy (RebaseMemory).
Fig 4 The difference the two paths turn on: cold boot pays for a full kernel handoff and userland init; restore starts a process and resumes an already-initialised guest.
CallWhat it does
CreateSnapshot(ctx, dir)pause the VM, write snapshot.bin + mem.bin, leave it paused
Restore(ctx, m, dir, log)fresh VMM from a full snapshot
RestoreForDiff → CreateSnapshotDiffrestore with dirty-page tracking, then write a sparse mem.bin
RestoreDiffrebase the sparse diff onto a base-memory copy (SEEK_DATA/SEEK_HOLE), restore from the merge
RestoreUFFD + cmd/moat-uffdraw snapshot/load with mem_backend; a handler streams pages on demand via userfaultfd
Reconcile(runRoot, keep, log)read every firecracker.pid, kill the processes a crash left behind
Gotcha · G-12 PauseVM/ResumeVM on the same VMM process breaks the guest vsock on this Firecracker build. The warm pool keeps members running, not paused. Snapshot restore starts a fresh process and is unaffected.

05The guest agent & vsock

The agent is a static (CGO_ENABLED=0) binary. The kernel runs it as PID 1 through init=/sbin/guest-agent. As PID 1 it must never return — the kernel panics if init exits — so every fatal path calls haltForever. On start it mounts /proc, /sys, /dev (tolerating EBUSY), /dev/pts, /dev/shm, a tmpfs /run; sets a base PATH and /etc/resolv.conf; installs a SIGCHLD reaper; and serves gRPC on AF_VSOCK port 5252.

The vsock handshake

Firecracker multiplexes guest vsock connections over one host Unix socket. To open a guest connection the host connects to that socket, writes CONNECT <port>\n, reads OK <hostport>\n, and then the stream is a raw pipe to the guest listener. internal/vsockconn implements it; internal/agentclient wraps it in a gRPC ClientConn with a custom dialer. Host CID is 2. The first guest is CID 3.

RPCShape
Infoagent version, pid, uname -r, uptime — the host's readiness check
Execrequest: argv, env, dir, stdin, timeout_ms, tty+size. Stream: Started{pid}, then stdout/stderr chunks, then one Exit{code, signal, timed_out}. Timeout kills the process group.
WriteFilefirst chunk sets path+mode; every chunk carries data. Response: bytes_written + hex SHA-256.
ReadFiledata chunks, then a final chunk with eof, size, sha256, no data.

Files move only through WriteFile / ReadFile over vsock. There is no shared mount.

06Networking — internal/netconf

Apply Plan / Destroy Plan need CAP_NET_ADMIN and CAP_SYS_ADMIN — real root, or unshare --user --map-root-user --mount --net. A Plan (from BuildPlan(lease, uplink)) describes a named netns, a veth pair, a TAP inside the netns, a static /30 guest address from the 10.62.0.0/16 pool, and the kernel ip= argument so the guest configures the NIC at boot with no DHCP.

VM NETNS guest NIC10.62.x.2/30 TAP10.62.x.1/30 nft: DNAT 80/443 veth pair HOST NETNS nftables — chain forward DROP → host · other VMs DROP → link-local · RFC-1918 chain postroutingmasquerade oif veth transparent egress proxy SO_ORIGINAL_DST · SNI / Host allowed only forward proxydomain allow / deny internet
Fig 5 Everything private is dropped in the forward chain first. Only the point-to-point links and established flows pass, then the host masquerades toward the proxy. The DNAT rule (dashed) forces guest web traffic through the transparent proxy even if the guest ignores HTTP(S)_PROXY.
chain forward {
  type filter hook forward priority 0; policy accept;
  ct state established,related accept
  ip daddr { <tap /30>, <veth /30> } accept
  ip daddr 169.254.0.0/16 drop        # link-local + cloud metadata
  ip daddr 127.0.0.0/8   drop
  ip daddr 10.0.0.0/8    drop          # RFC-1918
  ip daddr 172.16.0.0/12 drop
  ip daddr 192.168.0.0/16 drop
}

07Resource limits & the warm pool

cgroup.Apply(name, pid, Limits) (remove func(), error) writes cpu.max, memory.max, pids.max into a new leaf under this process's delegated systemd subtree (…/user@<uid>.service/microvm/mvm-<id>). It needs no root when systemd delegation is in effect. Instance.Stop calls the returned remove after the VMM exits. Limits is {CPUCores float64, MemBytes int64, PIDs int64}; a zero field means no cap. Firecracker's own per-VM token-bucket rate limiters cap the rootfs block device and the network interface (one-second refill).

The pool — internal/pool

pool.New(ctx, Options{Size}, base, log) starts Size microVMs from a copy of the base rootfs and keeps them running and idle. Acquire(ctx) returns a *Lease — p50 about 1 ms — carrying a TTL and an idle timeout. Lease.Touch() resets the idle clock; a background sweep force-releases a straggler. Lease.Release() discards the member (one VM per session) and refill starts a replacement. moatd -pool N turns it on; it serves only non-networked sandboxes.

08The northbound API — internal/server

server.New(cfg, log) validates config, builds the template map, runs the image check, builds the secret scanner, registers metrics. Start(ctx) starts the pool, writes daemon.start, starts the TTL janitor. Shutdown(ctx) writes daemon.stop, destroys every sandbox, waits for in-flight teardowns.

Method + pathHandler
GET /healthzliveness, no auth
GET /metricsPrometheus text, no auth
POST /v1/sandboxescreate — quota check, template resolve, boot
GET /v1/sandboxeslist the caller's sandboxes
GET /v1/sandboxes/{id}one sandbox
DELETE /v1/sandboxes/{id}destroy
POST /v1/sandboxes/{id}/execstream a command as NDJSON
PUT /v1/sandboxes/{id}/files/{path...}write a file (scanned)
GET /v1/sandboxes/{id}/files/{path...}read a file, X-Sha256 trailer
GET /v1/sandboxes/{id}/reportper-sandbox audit rollup
GET /v1/auditthe audit stream (NDJSON), per-token scope

Auth is a bearer token. Config.Tokens maps id → secret; Config.Policies maps id → TokenPolicy (template allowlist, per-token concurrency, TTL cap, deny_network, allow_secret_override, audit_read: "all"). Quotas — registry.reserve/release enforce GlobalMax and the per-token cap; a block gets 429 and a quota.reject event.

09Egress & the ingress secret firewall

Egress proxy — internal/egress

One Proxy serves two listeners. Forward: handles CONNECT (filtered by requested host name, no TLS interception) and absolute-URI HTTP; a networked sandbox gets HTTP(S)_PROXY pointed here. Transparent: takes DNAT-redirected raw connections, recovers the pre-DNAT address with SO_ORIGINAL_DST, reads the host from the request line or the TLS SNI, applies the same policy, and splices.

Policy{Allow, Deny []string}. A host is allowed when it matches no Deny entry and (Allow is empty or it matches an Allow entry). Matching is case-insensitive on the exact name or any parent domain. Each decision is an egress.allow / egress.deny audit event with host, port, method, matched rule, the via listener, and the resolved sandbox and token. Both go on the async audit path so a guest cannot flood the writer with denials.

Secret firewall — internal/secretscan

secretscan.New() loads the vendored Gitleaks rule set (gitleaks.toml, MIT). The Gitleaks module itself is not imported — it pulls 200+ dependencies. A slim in-repo evaluator runs a keyword prefilter, the regex, an optional Shannon-entropy floor, then the allowlists.

moatd scans every -env value, every stdin, and every file body on the way in. A hit returns 409, unless the token has allow_secret_override and the request sets allow_secrets: true (audited), or -secret-redact is on (a marker replaces the secret). secret.block / allow / redact events record only the target, the deduped rule ids, and a count — the matched value never leaves the scanner. A failed secret.allow or secret.redact audit write returns 503: the content does not enter with no durable record.

10The audit log — internal/audit

An append-only JSONL log with a SHA-256 hash chain. Each event's hash is the SHA-256 of its canonical form (keys sorted at every level, hash omitted, ts in RFC3339Nano UTC). Each event's prev is the previous event's hash. The first event's prev is 64 zeros.

TWO WRITE PATHS RecordSync + fsync sandbox · daemon · quota · secret Record → bounded queue exec · file · egress — batched fsync full queue → drop the event + moat_audit_dropped_total sync-write failure → roll back seq · truncate · return the error the chain never forks HASH CHAIN — audit-YYYY-MM-DD.NNNNN.jsonl event N-1 prev = … hash = H1 event N prev = H1 hash = H2 event N+1 prev = H2 Verify: recompute every hash · check prev links · check seq a corrupt non-final line → moatd will not start a crash-truncated final line is tolerated Retention: remove by age, then total size — never the current file. Read scope: audit_read "all" sees all — otherwise own sandboxes + own token.
Fig 6 Boundary events block until durable. Hot events never block — a full queue drops and meters. Either way, each event's hash is the next event's prev, so a single altered byte breaks the chain at that point.

11The image pipeline

make images runs four steps: kernel, rootfs, sbom, lock. The result is a byte-identical rootfs.ext4 on one toolchain, a pinned + hash-checked kernel, a CycloneDX SBOM, and images.lock. moatd verifies the kernel and rootfs against the lock at startup and fails closed on a mismatch.

BUILD · make images fetch-kernel.sh pinned snapshot + sha256 build-rootfs.sh SOURCE_DATE_EPOCH · fixed UUID guest-agent · -trimpath sbomgen (go run) debugfs · go version -m sbom.cdx.json CycloneDX 1.5 gen-images-lock.sh sha256(kernel · rootfs · sbom) + provenance → images.lock images.lock — repo root checked in images.lock — release tarball + /var/lib/moat RUNTIME moatd · verifyImages (server.New) digests == images.lock · enforce | warn | off make images-verify: rebuild → assert byte-identical + matches the lock
Fig 7 The lock is the single source of truth. The build writes it, a canonical copy is committed, a copy ships with the release, and moatd enforces it before the first sandbox boots.

Rootfs determinism controls

Non-determinism sourceControl
the alpine:3.20 tag movespin BASE_IMAGE=…@sha256:c64c687c…
podman export file times & orderfind "$root" -exec touch --date=@$SOURCE_DATE_EPOCH
the agent binary embeds paths + a build idgo build -trimpath -buildvcs=false -ldflags='-s -w -buildid=', toolchain go1.27.0
mkfs.ext4 UUID, hash seed, times, lazy initE2FSPROGS_FAKE_TIME=… mkfs.ext4 -U <fixed> -E hash_seed=<fixed>,lazy_itable_init=0,lazy_journal_init=0
callers disagreed on sizeROOTFS_SIZE frozen at 256M
Scope of the guarantee Byte-identical holds for a fixed toolchain (same podman, e2fsprogs, tar, go). On a different e2fsprogs the package set and the SBOM still match, but the ext4 byte layout can shift. moatd enforces the digest from the lock that shipped with that image, so the runtime check is unaffected.

Bumping the kernel or base image

  1. Resolve the new pin values (commands in the plan).
  2. Edit the constants in build/fetch-kernel.sh, build/build-rootfs.sh, and the Makefile.
  3. make images && make images-verify.
  4. cp build/artifacts/images.lock images.lock and commit.
  5. Re-sign images.lock.sig at release time.

Extra userlands — build/templates/

The default rootfs is the reference image and the only one in images.lock. For a language runtime or a demo shell, add a template: a build/templates/<name>/ directory with a Dockerfile and a template.env. build/build-template.sh runs podman build, then the same rootless export + timestamp-normalise + mkfs.ext4 path as build-rootfs.sh, and writes build/artifacts/<name>-rootfs.ext4.

make template NAME=python        # copy build/templates/_skeleton
make template-image NAME=python  # build build/artifacts/python-rootfs.ext4
make demo-image                  # the dev-shell toolchain image
make minimal-image               # the small test image

Templates are byte-stable within a day only — apk add tracks the live Alpine index — so they are not pinned in images.lock. moatd selects one by the rootfs path in each moatd.json template entry; a client asks for it with {"template":"<name>"}. See build/templates/README.md.

Import an existing image — moat template import

moat template import <ref> (or --from-archive <file>) builds a template rootfs straight from a container image: podman pull / podman load → record the @sha256 digest → read the image config → podman export → inject /sbin/guest-agent → auto-size → mkfs.ext4 -d. The pipeline is internal/imgimport. The image's ENV / WORKDIR / ENTRYPOINT become the template's env / workdir / default_argv, which moatd applies to every exec — a request value always wins. linux/amd64 only. Not in images.lock; the source digest is the record. Without --config the command writes <data>/<name>.template.json and prints the moatd.json snippet.

12Building & testing

Toolchain

  • Go 1.27.0 exactly — go.mod declares toolchain go1.27.0; the Makefile exports GOTOOLCHAIN=local. A reproducible agent needs this version.
  • podman, e2fsprogs (mkfs.ext4, debugfs), tar, curl for the image pipeline.
  • firecracker and jailer on PATH (tested against v1.16.1). /dev/kvm readable + writable.
  • buf, protoc-gen-go, protoc-gen-go-grpc only to regenerate gen/ — make tools installs them into $GOBIN, no root.
TargetEffect
make allbuild every binary into bin/
make imageskernel → rootfs → sbom → lock into build/artifacts/
make images-verifyrebuild + assert byte-for-byte reproducible
make testgo test ./... — unit, no VM, fast (the gate)
make test-integration-tags integration — boots real microVMs; needs /dev/kvm + make images
make test-integration-fastthe same suite against the small minimal rootfs; skips make images
make test-netnetwork isolation test, rootless in a user+net namespace
make template-image NAME=x / make demo-imagebuild a rootfs template (build/templates/)
make protoregenerate gen/ from proto/
make distassemble dist/moat_<ver>_linux_amd64.tar.gz + checksums

A cold boot attaches the rootfs read-write, so coldBoot and the warm pool give every sandbox a private sparse copy of the template rootfs in its run directory, removed on destroy. Sandboxes never share one ext4 file (G-19).

13Using it

The moat CLI

CommandPurpose
moat demostart a microVM, run the agent readiness check, stop it
moat run [flags] -- CMDstart a one-shot microVM, run a command, tear it down
moat snapshot / restorecapture and reload a warmed VM (-diff, -uffd)
moat benchwarm-pool acquire / release benchmark
moat reapkill Firecracker processes a crash left behind
moat doctorpreflight KVM, firecracker, cgroup delegation, nft, userfaultfd, images, images.lock
moat template listshow the templates this host knows
moat template import <ref>build a template from a container image (--from-archive, --name, --config)
moat template show <name>print a template's rootfs, digest, and exec defaults
moat audit {tail,query,report,verify}read the audit log, offline (-dir) or over the API
moat run -net -put ./main.go:/work/main.go -get /work/out:./out -timeout 60s -- \
  sh -c 'cd /work && go build -o out ./main.go'

Template exec defaults. moatd applies a template's env and workdir to every exec in a sandbox from that template, and runs default_argv when a request sends no argv. A request env key, dir, or argv always wins. moat template import fills these from the image config; the exec audit event records argv_source and the union of template and request env-key names.

The HTTP API — a walkthrough

MOAT_TOKENS=ci:s3cr3t moatd -pool 4

H='-H Authorization: Bearer s3cr3t'
id=$(curl -s $H -XPOST localhost:8080/v1/sandboxes -d '{"ttl_seconds":120}' | jq -r .id)

# NDJSON: a started frame, stdout/stderr frames, one exit frame
curl -s $H -XPOST localhost:8080/v1/sandboxes/$id/exec \
  -d '{"argv":["sh","-c","echo hi; uname -r"]}'

curl -s $H -XPUT --data-binary @main.go \
  localhost:8080/v1/sandboxes/$id/files/work/main.go

curl -s $H localhost:8080/v1/sandboxes/$id/report | jq
curl -s $H -XDELETE localhost:8080/v1/sandboxes/$id

Full request and response shapes are in docs/api.md.

MCP server & the Go client

moat-mcp is a Model Context Protocol server over stdio exposing moat_create, moat_list, moat_destroy, moat_exec, moat_write_file, moat_read_file. Point it at a running moatd with MOAT_ADDR and MOAT_TOKEN. A secret block comes back as an IsError result that tells the agent to ask the user. internal/moatapi is the Go client — Create, List, Destroy, Exec, PutFile (*SecretBlockedError on 409), GetFile, Audit, Report.

The demo — demo/run.sh

A scripted, self-checking walk-through: it starts moatd with a template store (dev-shell, rhel9, and an imported container), creates sandboxes over the HTTP API, runs a real Go build in one, copies the binary out, runs a RHEL 9 sandbox, and checks each isolation property (own kernel, private rootfs, secret firewall, hash-chained audit, imported-image exec defaults). Needs /dev/kvm, curl, jq, and podman. It exits non-zero on the first failed check. Step table in demo/README.md.

14Deploying moatd

Host requirements

  • Linux / x86-64 with nested or bare-metal KVM. Bare metal for production; GCP nested virtualization works for dev.
  • /dev/kvm accessible to the moatd user.
  • firecracker + jailer on PATH.
  • An uncompressed vmlinux and a rootfs.ext4 — from make images, the release tarball, or install.sh.
  • cgroup v2 with a delegated systemd subtree for rootless resource caps. Without it, the caps need root.
  • For networked sandboxes: nft on PATH and CAP_NET_ADMIN + CAP_SYS_ADMIN.

Run moat doctor on the target host — one line per check.

Installer

curl -fsSL https://raw.githubusercontent.com/M30W-M1X/moat/main/install.sh | sh

Checks Linux / x86-64 / KVM, resolves the latest GitHub release, verifies SHA-256 (and cosign when configured), installs binaries to /usr/local/bin and images + images.lock + sbom.cdx.json to /var/lib/moat, writes a starter moatd.json, installs deploy/moatd.service. Flags: --user --prefix --data --version --no-service --dry-run.

systemd unit

deploy/moatd.service sets DeviceAllow=/dev/kvm rw, NoNewPrivileges, ProtectSystem=strict, ProtectHome=read-only, PrivateTmp, and a read-write path list of /var/lib/moat and /run/moat. For networked sandboxes add AmbientCapabilities=CAP_NET_ADMIN CAP_SYS_ADMIN. Then systemctl enable --now moatd.

Directory resolution

  • data (vmlinux, rootfs.ext4, images.lock, audit): $MOAT_DATA → $XDG_DATA_HOME/moat → ~/.local/share/moat → /var/lib/moat. In a checkout: <repo>/build/artifacts.
  • run (sockets, pid files, scratch): $MOAT_RUN → $XDG_RUNTIME_DIR/moat → /run/moat → a temp dir.
Rootless vs root Rootless covers cold-boot sandboxes, exec, file I/O, resource caps (with delegation), the audit log, the egress proxy in HTTP_PROXY mode, and snapshots. Root or unshare is needed for the network namespace path, the transparent DNAT, the jailer, real-uplink NAT, and UFFD restore without /dev/userfaultfd.

15Configuration reference

Key moatd flags

FlagDefaultMeaning
-addr:8080API listen address
-config FILE—JSON: templates, tokens, per-token policy, defaults
-tokens—id:secret,… (else $MOAT_TOKENS)
-pool N0warm non-networked sandboxes to keep ready
-global-max / -token-max64 / 16concurrency caps
-default-ttl / -max-ttl15m / 1hsandbox lifetime and its cap
-cpu-max / -mem-max / -pids-max0per-sandbox cgroup caps
-disk-bw / -net-bw0per-sandbox bandwidth, bytes/sec
-net-pool / -uplink10.62.0.0/16 / nonenetworked addressing + NAT parent
-egress-allow / -egress-deny—domain policy for the proxy
-egress-transparent ADDR—second listener + the namespace DNAT
-audit-dirdata /audit"" = default, "off" disables
-secret-scan / -secret-redacttrue / falseingress firewall behaviour
-image-verifyenforceenforce / warn / off
-cosign-identity / -cosign-issuer—verify images.lock.sig

moatd.json

Top-level: templates, tokens, defaults, audit, image_verify, cosign_identity, cosign_issuer. Unknown keys are rejected.

  • template: name kernel rootfs vcpus mem_mib cpu_max mem_max_mib pids_max disk_bw net_bw
  • token: id secret templates max_concurrent max_ttl deny_network allow_secret_override audit_read
  • defaults: global_max token_max default_ttl max_ttl pool net_pool uplink
  • audit: dir max_file_mb max_total_mb max_age fsync_batch fsync_interval

Environment

MOAT_TOKENS, MOAT_DATA, MOAT_RUN, MOAT_IMAGE_VERIFY, MOAT_COSIGN_IDENTITY, MOAT_COSIGN_ISSUER, MOAT_ADDR, MOAT_TOKEN. Image-setting precedence: flag → env → file → default.

16Operations

Metrics — GET /metrics

moat_sandboxes_active{template}          moat_audit_events_total{type,result}
moat_sandboxes_created_total{template,source}   moat_audit_dropped_total
moat_sandbox_create_seconds{source}      moat_audit_write_seconds{path}
moat_exec_total{outcome}                 moat_audit_queue_depth
moat_file_bytes_total{direction}         moat_egress_requests_total{decision}
moat_secret_findings_total{rule,action}  moat_http_requests_total{route,status}
moat_quota_rejects_total                 moat_http_request_seconds{route}
moat_pool_ready

The audit log

moat audit tail -dir /var/lib/moat/audit follows. moat audit query -dir … -since -15m -type exec filters offline. moat audit verify -dir … recomputes the chain and exits non-zero on a break. Over the API, add -addr and -token (the token needs audit_read: "all" for an unfiltered pull).

Crash recovery

moatd runs vm.Reconcile at startup and kills orphan Firecracker processes, one orphan.reap event each. If moatd refuses to start with an audit error, run moat audit verify -dir <dir>, move the named file aside, and restart.

Every footgun that cost real debugging time is a numbered G-N entry in the project "Gotchas" note (G-1 … G-19), in a symptom → cause → fix shape. Read it before a deep change to the kernel args, the image pipeline, the netns path, or the audit writer.

17Limits & roadmap

  • Cold-boot rootfs is read-write (G-19). Fix: attach the root drive read-only, or copy per sandbox.
  • No snapshot-templated warm pool — the pool cold-boots its members.
  • A gRPC northbound surface alongside REST is planned.
  • A template registry (moat template pull python) is a deferred CDN job. moat template import <ref> already covers the common case.
  • CI — the repo has none yet. make images-verify is the exact check a CI job would run.
  • Signing images.lock in an automated release is manual today.
  • GPU workloads are out of scope for Firecracker (DD-11). A parallel gVisor / Cloud Hypervisor backend would keep the VM-driver interface abstract.

Style: all comments and log / error strings follow ASD-STE100. Durable decisions go to the agentcairn vault; full write-ups to ClaudeVault/projects/microvm-controller/; every footgun to the G-N log. Non-trivial work goes through a spec in docs/superpowers/specs/ and a plan in docs/superpowers/plans/ before implementation. No new Go module dependency without a strong reason.