mirror of
https://github.com/devvmhq/devvm.git
synced 2026-12-01 06:23:17 -10:00
refactor(backend): remove the smolvm backend
Lima is devvm's only backend. The backend architecture stays (Backend, Caps, Features, Review/Require, the registry, backendtest.Fake), so another backend is an addition. State from a smolvm VM reads as an unknown backend (backend_unknown_vm, gc_orphans_unknown); nothing migrates it. The image keys of layers/docker.sh, layers/nix.sh and features/desktop.sh change, so images rebuild once. Lima's port forwarder moves off smolvm's files first: newForwarderCmd and forwarderMain from internal/cli/smolvmports.go to limaports.go, and assets/container/ports.sh to assets/guest/ports.sh (sent by the forwarder at run time, so no image key changes). Removed: - internal/backend/smolvm (4,070 lines with tests), _smolvm-ports, its registry entry, registry.Experimental and backend_experimental. - The decider: backend.Decider/UsesDecider, Confinement.Decider and DeciderToken, internal/proxy/decider.go and its test, the proxy's -decider, -decider-to and -decider-token-file, netpolicy's KeyDeciderPort, KeyDeciderToken and deciderToken, the decider port in vm's forwarding and UsedPorts. - backend.AgentStarter/AgentUnchosen, vm's checkAgentStart and agent_unchosen_stop. - vmssh/key.go (EnsureKey, Public, HostKey, ServicesArgs, Capped). - paths.Smolvm/SmolvmImage and space's smolvm folders; paths.VM's Record, Key, KnownHosts and ProxyURL; project.Detect, which nothing called (a test helper now). - ubuntu.ContainerRepo/ContainerDigest/ContainerRef/ContainerOrigin and bump.sh's ubuntu_image, with its part of bump.txtar. - assets/smolvm/ and assets/container/; the no-init-system branches of layers/docker.sh, layers/nix.sh and guest/sync.sh, and the notes in features/desktop.sh and guest/ca.sh. - Messages: smolvm_* (14), vm_no_ssh, vm_no_sshd, ports_no_ssh, creating_from_image, packing_image, pack_failed, backend_experimental, agent_unchosen_stop; descriptions naming smolvm reworded. - Tests: smolvm.txtar, the smolvm stub, registry, decider, netpolicy and sshagent cases; gc_backend, gc_skipped, gc_orphans and space test a failing or hanging Lima listing instead (the limactl stub's list-fails and list-hangs); the --backend smolvm examples; e2e's --backend smolvm and its section (about 1,130 lines), the smol_* helpers and the link section's backend switch. - Coverage: internal/backend/smolvm's lines in both baselines. - Docs: backends/smolvm.md, internals/smolvm.md, design.md's smolvm notes (Ports on Lima now holds the forwarder's description), the backends table's smolvm column, every page naming smolvm, the README, the home page's backends art, and AGENTS.md's smolvm rows and gotchas (and the Docker bind-mount gotcha, which nothing refers to). Kept: the docker layer, on Lima; --from's local Docker; --backend, the BACKEND column and setup's backend choice, which the next commit removes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
162 files changed
+590
-8375
No files matched your search
@@ -1,13 +1,13 @@
|
||||
# AGENTS.md
|
||||
|
||||
devvm: one isolated VM per project folder, cloned from a base image, with toolchains and agents shared read-only between VMs. It's a Go CLI with swappable VM backends: Lima, the default, and smolvm, experimental. Read [README.md](README.md) for what it is, and the [docs site](docs/content/docs/) for how each part works; [Contributing](docs/content/docs/contributing/_index.md) covers building, the tools, testscript and writing docs.
|
||||
devvm: one isolated VM per project folder, cloned from a base image, with toolchains and agents shared read-only between VMs. It's a Go CLI that runs its VMs on Lima, behind a backend interface another backend could implement. Read [README.md](README.md) for what it is, and the [docs site](docs/content/docs/) for how each part works; [Contributing](docs/content/docs/contributing/_index.md) covers building, the tools, testscript and writing docs.
|
||||
|
||||
## Layout
|
||||
|
||||
| Path | What |
|
||||
| --- | --- |
|
||||
| `cmd/devvm/` | the entry point: `ui.Main` makes the run's UI and runs the root command with it; the only `os.Exit` |
|
||||
| `internal/cli/` | Cobra commands, one file each (root = up, `build`/`rebuild`, `images`, `gc`, `space`, `retention`, `layer`, `setup`, `restart`, `tools`, `adopt`, `rm`, `stop`, `history`, `ls`, `network` (its rules and log too), `doctor`, `secret`, `link` (its add, rm, publish and unpublish too), `group` (join, leave), `ssh-agent`, `host`, `code`, `desktop`, `limactl`, `ports`, `size`, `git-protect`, `completion`, hidden `version`, `_msg`, `_qemu`, `_proxy`, `_lima-ports`, `_smolvm-ports`, `_links`, `_refresh-tools`); `args.go` checks arguments and flags (usage errors), `flags.go` the flags several commands share, `word.go` refuses devvm WORD and help's unknown words (a part's name points to its flag; did-you-mean over commands, `msg.Closest`); `help.go` the help's groups, `Example`s and docs links (`msg.CommandDocURL`); `json.go`: `--json` (`printJSON`, `"version": 1`), its shapes in `json_test.go`; `script_test.go` runs testscript; `docgen/` writes the CLI reference |
|
||||
| `internal/cli/` | Cobra commands, one file each (root = up, `build`/`rebuild`, `images`, `gc`, `space`, `retention`, `layer`, `setup`, `restart`, `tools`, `adopt`, `rm`, `stop`, `history`, `ls`, `network` (its rules and log too), `doctor`, `secret`, `link` (its add, rm, publish and unpublish too), `group` (join, leave), `ssh-agent`, `host`, `code`, `desktop`, `limactl`, `ports`, `size`, `git-protect`, `completion`, hidden `version`, `_msg`, `_qemu`, `_proxy`, `_lima-ports` (its `newForwarderCmd` too), `_links`, `_refresh-tools`); `args.go` checks arguments and flags (usage errors), `flags.go` the flags several commands share, `word.go` refuses devvm WORD and help's unknown words (a part's name points to its flag; did-you-mean over commands, `msg.Closest`); `help.go` the help's groups, `Example`s and docs links (`msg.CommandDocURL`); `json.go`: `--json` (`printJSON`, `"version": 1`), its shapes in `json_test.go`; `script_test.go` runs testscript; `docgen/` writes the CLI reference |
|
||||
| `internal/vm/` | `Env` (`env.go`: shared dependencies, finding and starting the folder's VM); `Launch`: a new VM (`up.go`; `parts.go`: its toolchains, agents and layers, the picker, setup's agents), an existing one (`existing.go`), `ssh.go`, agents' mounts; `Lifecycle` (`lifecycle.go`); `Tools` (`tools.go`: a VM's shared tools); `Settings` (`settings.go`, `size.go`, `ports.go`, `sshagent.go`); `Net` (`network.go`, `secret.go`); `Links` (`links.go`: links between VMs, published ports), `Groups` (`groups.go`: the links a group makes); `--clone` (`clone.go`); a devcontainer.json's mapping and commands (`devcontainer.go`); the setup it sends (`sync.go`) |
|
||||
| `internal/shell/`, `internal/vmname/` | stdlib leaves: quoting for a POSIX shell (`Quote`, `QuoteJoin`) and its variables' names (`EnvName`); a project VM's name grammar (`Prefix`, `HashLen`, `IsVM`, `HashOf`, `SlugOf`) |
|
||||
| `internal/project/`, `internal/gitprotect/`, `internal/hostgit/` | a project folder (VM name, unsafe folders, detection, set-id files); `.git` protection; every host git command devvm runs (no fsmonitor, hooks or filters, ssh only, no `GIT_*` of the environment, no prompts) |
|
||||
@@ -22,13 +22,13 @@ devvm: one isolated VM per project folder, cloned from a base image, with toolch
|
||||
| `internal/proxy/` | the proxy, run as `devvm _proxy`; see its `README.md` |
|
||||
| `internal/daemon/` | devvm's background processes (stdlib only): detached starts, pid files checked against the process's arguments, stopping (TERM, then KILL), readiness by status file, the lifeline; the only place a process is signalled by pid (forbidigo) |
|
||||
| `internal/desktop/` | devvm desktop's relay on the host: VNC's password checked here, then an ssh channel to the VM's socket, the viewer's clipboard dropped; passwords |
|
||||
| `internal/backend/` | `Backend`, `Caps`, `Require`, the registry; `backendtest/` (fake), `registry/` (every backend's), `lima/`, `smolvm/` (experimental), `vmssh/` (their ssh: VMs' keys, the port forwarder, links' sessions) |
|
||||
| `internal/backend/` | `Backend`, `Caps`, `Require`, the registry; `backendtest/` (fake), `registry/` (every backend's), `lima/`, `vmssh/` (over a VM's ssh: the port forwarder, links' sessions) |
|
||||
| `internal/ui/` | the only package that prints: `ui.UI` (messages, prompts, status line, run log, cleanups), `ui.Main` (signals); no package state |
|
||||
| `internal/msg/`, `locales/` | messages: `en.toml`, the generated functions, doc links (`docs.go`), the generator (`gen/`) |
|
||||
| `internal/paths/`, `internal/state/` | every folder and file devvm uses, a VM's in its folder (`Dirs.VM`: `vms/<hash>/`); every file written whole (`WriteFile`, `WriteFileMode`: forbidigo bans `os.WriteFile`, `os.Create` and `O_TRUNC` elsewhere but the proxy), private folders (`PrivateDir`) |
|
||||
| `internal/settings/` | the defaults (`Defaults`, `Read`, `Save`): `config.toml` (yours, strict) over `settings.json` (devvm's), each value's check (`ParsePorts`, `ParseCPUs`, `ParseGiB`, the retention settings) |
|
||||
| `internal/platform/`, `internal/ubuntu/`, `internal/testbuild/` | build-tagged OS code; finding and verifying Ubuntu's cloud image (never downloads); whether this is a test build (ldflags: only it reads the test overrides, `cli`'s `readOverrides`) |
|
||||
| `assets/` | the files devvm ships, embedded (`assets.FS`, passed to constructors by `cli`): `base.yaml`, `layers/` (base's Lima template and scripts; the built-in layers, `docker` and `nix`, each with its policy), `features/` (base's optional ones), `shared-tools/` (`mise.toml`, `build.sh`, `*.policy`), `guest/` (in-VM scripts sent on every launch), `oci/` (`--from`'s conversion; see its `README.md`), `container/` (smolvm's scripts in containers), `smolvm/` (smolvm's own) |
|
||||
| `assets/` | the files devvm ships, embedded (`assets.FS`, passed to constructors by `cli`): `base.yaml`, `layers/` (base's Lima template and scripts; the built-in layers, `docker` and `nix`, each with its policy), `features/` (base's optional ones), `shared-tools/` (`mise.toml`, `build.sh`, `*.policy`), `guest/` (in-VM scripts sent on every launch, and the port forwarder's `ports.sh`), `oci/` (`--from`'s conversion; see its `README.md`) |
|
||||
| `internal/structure/` | the structure test (tests only) |
|
||||
| `internal/stubtest/` | Go tests' stubs on `PATH` (tests only): their folder, calls and files, `ExecRunner`; `msg.Recorder` and `msg.NamesOf` are tests' too, `backendtest.Stored` a fake with disks |
|
||||
| `testdata/` | `script/*.txtar` (CLI tests), `stubs/` (host commands; see each header), `mise.lock` (fixture), `coverage/<os>.txt` (each package's coverage baseline, per system), `lint/` (a line breaking each forbidigo rule, which `lint:code` checks) |
|
||||
@@ -109,8 +109,8 @@ Still to come: the release keys (`packaging/minisign.pub`, `packaging/release-si
|
||||
|
||||
- **Unit tests** are Go table tests next to the code; **CLI tests** are testscript against the built binary in a `/tmp` sandbox in names mode, stubs first on `PATH` (`stub_calls`, `stub_reset`), with `project`, `vm_name`, `catg` and `$DATA`/`$VMS`/`$RUN`/`$CFG`; the binary has `assets/` embedded (no override: scripts read `$DEVVM_REPO/assets/`; rebuild before a manual run after editing them). New logic needs a test. Neither touches the Keychain, real VMs or the user's folders; state-writing tests point the XDG folders at `t.TempDir()`. Go tests never run up: scripts do.
|
||||
- **Never touch VMs, images or containers devvm's tests didn't make:** your own stay as they are. Manual runs: `DEVVM_LIMA_HOME=~/.lt LIMA_HOME=~/.lt XDG_DATA_HOME=/tmp/x/data XDG_CONFIG_HOME=/tmp/x/config DEVVM_SECRET_SERVICE=devvm-sandbox-test` (devvm's Lima home is `$XDG_DATA_HOME/devvm/lima` unless `DEVVM_LIMA_HOME`; `LIMA_HOME` is for your `limactl`). Add a `config.toml` with `features = []` and pass `--network-policy`/`--no-network-policy` so nothing prompts. Delete test Keychain items. Never use your own tokens or logins: a network-policy VM reads its agent's login file from `HOME`, so give it its own (the Keychain needs the real `HOME`: test it apart).
|
||||
- **End-to-end:** `tests/e2e.sh` builds devvm from the checkout and drives real VMs in its sandbox (`~/.lt-e2e-go`, `/tmp/devvm-go-e2e`, service `devvm-go-e2e`), deleting only what it made; images stay cached (`--clean`). `tools` first resolves the newest tool versions. Run it in the background. Sections: `images`, `project`, `clone` (a throwaway repo, its own `HOME`), `gc` (an `img-*` folder's VM, a stale fixture), `tools` (a node VM), `network` (a VM with Claude Code and Codex), `desktop` (base with the desktop feature, devvm desktop), `nix` (a node VM with the nix layer and a flake), `from` (Debian 12, Alpine and Ubuntu bases, a docker that isn't running), `link` (two targets and a client, then the three in a group, the design note's threat check; `--backend smolvm` runs it too). Tiers: none (all but `desktop` and `from`, no features); `--from` (everything, every feature; before merging `assets/` or `--from` changes); `--only a,b` (with `from`: every feature). Hosted CI can't run it on macOS.- **Linux hosts:** `LIMA_HOME=~/.lt-linux-go`, VM `linuxhost` (nested virtualization, the repo read-only, copied to `~/devvm`), set up as [testing.md](docs/content/docs/contributing/testing.md) says, apart from any Lima home of your own.
|
||||
- **`tests/e2e.sh --backend smolvm`** runs only the `smolvm` section (after touching `internal/backend/smolvm` or shared code); it acts only on machines with its sandbox's label. Unreviewed emulations are checked through `DEVVM_UNREVIEWED=backend:feature`, which only test builds (e2e's, the CLI tests', by ldflags) read.
|
||||
- **End-to-end:** `tests/e2e.sh` builds devvm from the checkout and drives real VMs in its sandbox (`~/.lt-e2e-go`, `/tmp/devvm-go-e2e`, service `devvm-go-e2e`), deleting only what it made; images stay cached (`--clean`). `tools` first resolves the newest tool versions. Run it in the background. Sections: `images`, `project`, `clone` (a throwaway repo, its own `HOME`), `gc` (an `img-*` folder's VM, a stale fixture), `tools` (a node VM), `network` (a VM with Claude Code and Codex), `desktop` (base with the desktop feature, devvm desktop), `nix` (a node VM with the nix layer and a flake), `from` (Debian 12, Alpine and Ubuntu bases, a docker that isn't running), `link` (two targets and a client, then the three in a group, the design note's threat check). Tiers: none (all but `desktop` and `from`, no features); `--from` (everything, every feature; before merging `assets/` or `--from` changes); `--only a,b` (with `from`: every feature). Hosted CI can't run it on macOS.- **Linux hosts:** `LIMA_HOME=~/.lt-linux-go`, VM `linuxhost` (nested virtualization, the repo read-only, copied to `~/devvm`), set up as [testing.md](docs/content/docs/contributing/testing.md) says, apart from any Lima home of your own.
|
||||
- **Unreviewed emulations** are checked through `DEVVM_UNREVIEWED=backend:feature`, which only test builds (e2e's, the CLI tests', by ldflags) read.
|
||||
- **Delete test VMs and temp files afterwards.** Long builds run in the background. Tests that `chflags` real files unlock them (`chflags -R nouchg`), only in their own temp folders.
|
||||
- **The testscript runner stops the sandbox's proxies** (`pkill -f` on `-lifeline`): the stub hostagent is gone before they look, so they'd wait 15 minutes.
|
||||
- **`limactl shell` reads stdin:** give it none unless the input is meant for it.
|
||||
@@ -123,14 +123,9 @@ Still to come: the release keys (`packaging/minisign.pub`, `packaging/release-si
|
||||
- **`limactl list --json` fills in the config:** mounts get `mountPoint`, port forwards a `guestIP` (`127.0.0.1`) and host side; compare only what devvm set. `--set` applies after `--mount-none`. `limactl create` downloads the image at once (no dry run).
|
||||
- **`limactl shell` quotes each argument for the guest's shell**, so `Exec` passes `sh -c` and one `shell.QuoteJoin` string. QEMU's guestfwd command goes through `/bin/sh -c` too, commas doubled.
|
||||
- **The ssh socket path limit (104 characters)** bounds VM names (`NameMax`).
|
||||
- **Linux hosts (QEMU):** mounts are 9p, and a 9p share mounts once per guest. Docker writes bind-mounted files as root, so containers that write host files `chown` them back. Debian's tmpfs `/tmp` hides anything mounted below it during boot. Project VMs' qcow2 disks are overlays of their image's, so never start an image VM or write its disk after it's built.
|
||||
- **Linux hosts (QEMU):** mounts are 9p, and a 9p share mounts once per guest. Debian's tmpfs `/tmp` hides anything mounted below it during boot. Project VMs' qcow2 disks are overlays of their image's, so never start an image VM or write its disk after it's built.
|
||||
- **Shared tools:** mise rewrites `latest`/`24`/`lts` links in a tool's folder after any install, so those folders are local in the VM; only version folders are mounted.
|
||||
- **Linux's `pgrep -f` matches the shell running it** (procps), so e2e's patterns are written `[_]proxy`. mise skips minisign on linux/arm64 (no build).
|
||||
- **smolvm runs an image as a container in an Alpine microVM:** no init system, `exec` enters the container as root with only `HOME` set (no `USER`, no `/etc/environment`), `/dev` has no loop nodes (`mknod`), its EROFS mounts only uncompressed images, Docker needs `-v /var/lib/docker` and installs `systemctl` (tell systemd by `/run/systemd/system`). virtiofs shows host files as the host's uid, so the VM's user has it.
|
||||
- **smolvm packs carry their build VM's network, CPUs and memory;** `--block-private` can't be removed. `update --storage` breaks a registry-image machine, and a pack machine whose pack (stub and `.smolmachine`) is gone. `--state-dir` is Linux only: run it with `SMOLVM_USAGE=0`. On macOS it shares the user's machines (kept under `HOME`: a devvm run with another `HOME` sees others): touch only those with devvm's label.
|
||||
- **smolvm's network:** allow lists are per address (the gateway `100.96.0.1` is every host loopback port), DNS answers any name under them; its own forwards (devvm uses one, for the VM's sshd) reach only servers on `0.0.0.0` and take a host port another program has on `*` (`SO_REUSEADDR`, as Go's `net.Listen`: devvm's forwarder uses `platform.ListenExclusive`).
|
||||
- **smolvm reads `SSH_AUTH_SOCK` only at `machine start`,** and a machine made with `--ssh-agent` won't start without one (a missing path is accepted): e2e's direct starts pass `/dev/null/...`.
|
||||
- **smolvm base's packages before `assets/layers/base.sh`** come from Ubuntu's live archive, then base.sh pins a snapshot: anything pulling systemd libraries (openssh-server) goes after base's scripts (`sshd.sh`), or Docker's packages can't be installed. Under mediated egress a refused connection still opens in the guest, then resets (test with data, not a connect); TCP and UDP to any port 53 go to its resolver; `--dns` is create-only; a machine once started mediated won't start without a decider until `--no-egress-interceptor`.
|
||||
- **Lima writes `lima.REJECTED.yaml` into the current folder** on an invalid config: run `limactl` outside the repo (devvm runs it from its data folder).
|
||||
|
||||
## Commits and tasks
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
One VM for every project: an isolated sandbox with your project's toolchain, ready for you or an agent to start coding.
|
||||
|
||||
Each project folder gets a VM of its own. devvm detects the project's toolchain from its files, so a folder with `package.json` gets node, and the VM mounts only the project folder, at the same path as on your machine. New VMs get network policy by default, so they reach only the hosts you allow, and your secrets, such as your GitHub token and Claude Code token, stay on your machine. Claude Code, Codex and opencode run in the VM, with your settings, skills and MCP servers, and you start them in the VM's shell. devvm runs its VMs on [Lima](https://lima-vm.io) by default, or on the experimental smolvm backend.
|
||||
Each project folder gets a VM of its own. devvm detects the project's toolchain from its files, so a folder with `package.json` gets node, and the VM mounts only the project folder, at the same path as on your machine. New VMs get network policy by default, so they reach only the hosts you allow, and your secrets, such as your GitHub token and Claude Code token, stay on your machine. Claude Code, Codex and opencode run in the VM, with your settings, skills and MCP servers, and you start them in the VM's shell. devvm runs its VMs on [Lima](https://lima-vm.io).
|
||||
|
||||
## Install
|
||||
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
#!/bin/sh
|
||||
# Run as root in base's build machine or container, before assets/layers/base.sh: a container image
|
||||
# has what Lima's cloud images bring (sudo, CA certificates, bash) and the VM's user, as the host's:
|
||||
# its name and uid (virtiofs and bind mounts show the project folder as the host user's), and with
|
||||
# GID its group too (a Linux host's bind mounts keep it); home /home/NAME.guest. The user's password
|
||||
# is * (none matches), not locked: sshd without PAM refuses a locked account's keys too. sshd comes
|
||||
# after base's scripts (sshd.sh).
|
||||
# prepare.sh NAME UID [GID]
|
||||
set -eu
|
||||
name=$1 uid=$2 gid=${3:-} home=/home/$1.guest
|
||||
# group: the group with GID, made (named NAME) when there's none; "" without GID.
|
||||
group() {
|
||||
[ -n "$gid" ] || return 0
|
||||
g=$(getent group "$gid" | cut -d: -f1 || true)
|
||||
if [ -z "$g" ]; then
|
||||
if getent group "$name" >/dev/null; then groupmod -g "$gid" "$name"; else groupadd -g "$gid" "$name"; fi
|
||||
g=$name
|
||||
fi
|
||||
echo "$g"
|
||||
}
|
||||
# owned: the group with GID that was the removed user's own (Ubuntu's ubuntu) is renamed NAME.
|
||||
owned() {
|
||||
[ -n "$gid" ] && [ -n "$other" ] && [ "$other" != "$name" ] || return 0
|
||||
if [ "$(getent group "$gid" | cut -d: -f1)" = "$other" ] && ! getent group "$name" >/dev/null; then
|
||||
groupmod -n "$name" "$other"
|
||||
fi
|
||||
}
|
||||
# shellcheck source=/dev/null
|
||||
. /etc/os-release
|
||||
case " $ID ${ID_LIKE:-} " in
|
||||
*" ubuntu "*|*" debian "*)
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends ca-certificates sudo bash passwd
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
# Another user with the uid (Ubuntu's own ubuntu, 1000) goes: files are told apart by uid.
|
||||
other=$(getent passwd "$uid" | cut -d: -f1 || true)
|
||||
if [ -n "$other" ] && [ "$other" != "$name" ]; then userdel -r "$other" 2>/dev/null || userdel "$other"; fi
|
||||
owned
|
||||
g=$(group)
|
||||
if ! id "$name" >/dev/null 2>&1; then
|
||||
if [ -n "$g" ]; then
|
||||
useradd --create-home --home-dir "$home" --uid "$uid" --gid "$g" --shell /bin/bash "$name"
|
||||
else
|
||||
useradd --create-home --home-dir "$home" --uid "$uid" --shell /bin/bash "$name"
|
||||
fi
|
||||
fi
|
||||
;;
|
||||
*" alpine "*)
|
||||
# OpenRC and ssh's client too, which Alpine's container image lacks: base.sh adds an OpenRC
|
||||
# service (enabled only: no init system runs it) and writes /etc/ssh/ssh_known_hosts.
|
||||
apk add --no-cache ca-certificates sudo bash shadow openrc openssh-client
|
||||
other=$(getent passwd "$uid" | cut -d: -f1 || true)
|
||||
if [ -n "$other" ] && [ "$other" != "$name" ]; then deluser --remove-home "$other"; fi
|
||||
owned
|
||||
g=$(group)
|
||||
if ! id "$name" >/dev/null 2>&1; then
|
||||
if [ -n "$g" ]; then
|
||||
adduser -D -h "$home" -u "$uid" -G "$g" -s /bin/bash "$name"
|
||||
else
|
||||
adduser -D -h "$home" -u "$uid" -s /bin/bash "$name"
|
||||
fi
|
||||
fi
|
||||
;;
|
||||
*) echo "prepare.sh: unsupported distro '$ID' (supported: Debian/Ubuntu and Alpine families)" >&2; exit 1 ;;
|
||||
esac
|
||||
usermod -p '*' "$name"
|
||||
echo "$name ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/90-devvm
|
||||
chmod 440 /etc/sudoers.d/90-devvm
|
||||
@@ -1,122 +0,0 @@
|
||||
#!/bin/sh
|
||||
# Run as root in a machine or container after each start, for what base's services do at boot on
|
||||
# Lima: an image run as a container (smolvm's machines) runs no init system. Its /dev has no loop
|
||||
# devices, which the shared tools' images are mounted with, so they're made first; then the tools
|
||||
# are mounted (devvm-tools, once assets/guest/sync.sh installed it; one that fails is the launch's
|
||||
# to report), the VM's sshd started when it's asked for, Nix's daemon started in the background
|
||||
# where the VM has it (the nix layer), and Docker's where the VM has it (the docker layer).
|
||||
# A pid file whose process isn't dockerd (one an image kept, or a start before this one) doesn't
|
||||
# count, and Docker's run folder goes before dockerd starts, as a boot would leave it.
|
||||
# services.sh [ssh USER KEY [VAR...]]
|
||||
# ssh: devvm's sshd for ssh and editors, on a config of its own: new host keys (ed25519) at each
|
||||
# start, so no two VMs made from one image share them; USER alone may log in, with KEY (the VM's
|
||||
# own, an authorized_keys line) alone; local forwarding, to IPv4 or IPv6, and remote forwards of TCP
|
||||
# ports only on 127.77.0.0/16, the addresses of the VM's links, as layers/base.sh allows them on
|
||||
# Lima; no remote socket forwards, tunnels or X11 (a safeguard for an honest VM: root here can change
|
||||
# it, and the boundary is the host's ssh, which asks for no other remote forward and accepts a
|
||||
# channel only for a forward it asked for); its sessions get /etc/environment and each
|
||||
# VAR from this script's environment (the proxy's under network policy), as devvm's own commands
|
||||
# do. The config holds them, so it's root's alone. devvm asks for it only once it found sshd there.
|
||||
set -eu
|
||||
i=0
|
||||
while [ "$i" -lt 64 ]; do
|
||||
[ -e "/dev/loop$i" ] || mknod -m 660 "/dev/loop$i" b 7 "$i"
|
||||
i=$((i + 1))
|
||||
done
|
||||
[ -e /dev/loop-control ] || mknod -m 660 /dev/loop-control c 10 237
|
||||
# A tool it can't mount doesn't stop the start: the launch's setup runs devvm-tools again and fails.
|
||||
if [ -x /usr/local/sbin/devvm-tools ] && [ -d /mnt/devvm-tools ]; then /usr/local/sbin/devvm-tools || true; fi
|
||||
if [ "${1:-}" = ssh ]; then
|
||||
user=$2 key=$3
|
||||
shift 3
|
||||
sshd=$(command -v sshd || echo /usr/sbin/sshd)
|
||||
[ -x "$sshd" ] || { echo "services.sh: no sshd" >&2; exit 1; }
|
||||
rm -f /etc/ssh/ssh_host_*
|
||||
mkdir -p /etc/ssh
|
||||
ssh-keygen -q -t ed25519 -N '' -C '' -f /etc/ssh/ssh_host_ed25519_key
|
||||
umask 022
|
||||
mkdir -p /etc/devvm/ssh /run/sshd
|
||||
chmod 755 /etc/devvm/ssh /run/sshd
|
||||
printf '%s\n' "$key" > /etc/devvm/ssh/authorized_keys
|
||||
# SetEnv's entries, each once, quoted: values with a quote, a backslash or a newline are left out.
|
||||
nl='
|
||||
'
|
||||
setenv="" seen=" "
|
||||
add() {
|
||||
case " $seen " in *" $1 "*) return 0 ;; esac
|
||||
case $2 in *'"'*|*\\*|*"$nl"*) return 0 ;; esac
|
||||
setenv="$setenv \"$1=$2\"" seen="$seen$1 "
|
||||
}
|
||||
if [ -r /etc/environment ]; then
|
||||
while IFS= read -r line || [ -n "$line" ]; do
|
||||
k=${line%%=*} v=${line#*=}
|
||||
case $k in ''|*[!A-Za-z0-9_]*|[0-9]*) continue ;; esac
|
||||
[ "$k" != "$line" ] || continue
|
||||
v=${v#\"} && v=${v%\"}
|
||||
add "$k" "$v"
|
||||
done < /etc/environment
|
||||
fi
|
||||
for k in "$@"; do
|
||||
case $k in ''|*[!A-Za-z0-9_]*|[0-9]*) continue ;; esac
|
||||
v=$(printenv "$k") || continue
|
||||
add "$k" "$v"
|
||||
done
|
||||
conf=/etc/devvm/ssh/sshd_config
|
||||
umask 077
|
||||
{
|
||||
echo "# devvm's sshd for ssh and editors, written at each start (services.sh)."
|
||||
# IPv4 alone to listen on; both to connect to, so forwarding every port reaches servers on ::1.
|
||||
echo "ListenAddress 0.0.0.0:22"
|
||||
echo "AddressFamily any"
|
||||
echo "HostKey /etc/ssh/ssh_host_ed25519_key"
|
||||
echo "PidFile /run/devvm-sshd.pid"
|
||||
echo "AllowUsers $user"
|
||||
echo "PermitRootLogin no"
|
||||
echo "AuthenticationMethods publickey"
|
||||
echo "PubkeyAuthentication yes"
|
||||
echo "PasswordAuthentication no"
|
||||
echo "KbdInteractiveAuthentication no"
|
||||
echo "HostbasedAuthentication no"
|
||||
echo "AuthorizedKeysFile /etc/devvm/ssh/authorized_keys"
|
||||
echo "AuthorizedKeysCommand none"
|
||||
echo "AuthorizedPrincipalsFile none"
|
||||
echo "PermitUserEnvironment no"
|
||||
# Remote forwards bind the address asked for, which PermitListen matches as text: 0.0.0.0,
|
||||
# 127.0.0.1, ::1 and localhost are refused.
|
||||
echo "AllowTcpForwarding all"
|
||||
echo "AllowStreamLocalForwarding local"
|
||||
echo "GatewayPorts clientspecified"
|
||||
echo "PermitListen 127.77.*:*"
|
||||
echo "X11Forwarding no"
|
||||
echo "PermitTunnel no"
|
||||
echo "AllowAgentForwarding yes"
|
||||
echo "PrintMotd no"
|
||||
echo "Subsystem sftp internal-sftp"
|
||||
[ -z "$setenv" ] || echo "SetEnv$setenv"
|
||||
} > "$conf"
|
||||
umask 022
|
||||
"$sshd" -t -f "$conf"
|
||||
"$sshd" -f "$conf" -E /var/log/devvm-sshd.log
|
||||
fi
|
||||
# Nix's daemon where the VM has it (the nix layer), with its settings (/etc/conf.d/nix-daemon:
|
||||
# guest/sync.sh's proxy under network policy), unless it runs; its pid file counts as Docker's does.
|
||||
nixd=/nix/var/nix/profiles/default/bin/nix-daemon
|
||||
pid=$(cat /run/nix-daemon.pid 2>/dev/null || true)
|
||||
if [ -x "$nixd" ] && ! { [ -n "$pid" ] && [ "$(cat "/proc/$pid/comm" 2>/dev/null)" = nix-daemon ]; }; then
|
||||
(
|
||||
# shellcheck source=/dev/null
|
||||
[ ! -f /etc/conf.d/nix-daemon ] || . /etc/conf.d/nix-daemon
|
||||
mkdir -p /var/log
|
||||
nohup "$nixd" --daemon >/var/log/nix-daemon.log 2>&1 </dev/null &
|
||||
echo $! > /run/nix-daemon.pid
|
||||
)
|
||||
fi
|
||||
pid=$(cat /run/docker.pid 2>/dev/null || true)
|
||||
if command -v dockerd >/dev/null 2>&1 &&
|
||||
! { [ -n "$pid" ] && [ "$(cat "/proc/$pid/comm" 2>/dev/null)" = dockerd ]; }; then
|
||||
# /run outlives a stop here, unlike a boot's: its pid files name processes long gone, whose pids
|
||||
# this start's may have, and dockerd refuses to start its containerd over one.
|
||||
rm -rf /run/docker.pid /run/docker 2>/dev/null || true
|
||||
mkdir -p /var/log
|
||||
nohup dockerd -p /run/docker.pid >/var/log/dockerd.log 2>&1 </dev/null &
|
||||
fi
|
||||
@@ -1,23 +0,0 @@
|
||||
#!/bin/sh
|
||||
# Run as root in a build machine or container: around devvm's scripts, which enable services the way
|
||||
# Lima's guests boot them (systemctl, rc-update). An image run as a container (smolvm's machines)
|
||||
# runs no init system, so while they run, those commands are stand-ins that do
|
||||
# nothing, and devvm starts the services itself after each start. Only a command the image lacks
|
||||
# gets one, and only devvm's stand-ins are removed.
|
||||
# shims.sh on|off
|
||||
set -eu
|
||||
mark="# devvm build stand-in"
|
||||
for c in systemctl rc-update; do
|
||||
f=/usr/local/sbin/$c
|
||||
case $1 in
|
||||
on)
|
||||
command -v "$c" >/dev/null 2>&1 && continue
|
||||
mkdir -p /usr/local/sbin
|
||||
printf '#!/bin/sh\n%s: no init system runs here\nexit 0\n' "$mark" > "$f"
|
||||
chmod 755 "$f"
|
||||
;;
|
||||
off)
|
||||
if [ -f "$f" ] && grep -qx "$mark: no init system runs here" "$f"; then rm -f "$f"; fi
|
||||
;;
|
||||
esac
|
||||
done
|
||||
@@ -1,18 +0,0 @@
|
||||
#!/bin/sh
|
||||
# Run as root in base's build machine or container after its scripts: sshd, for devvm's ssh for editors
|
||||
# (services.sh starts it). After them, as it comes from the archive they left (Ubuntu's, pinned to a
|
||||
# snapshot), so it fits what they installed: from the live archive, before them, its systemd
|
||||
# libraries were newer than the snapshot's, which packages layers install (Docker's) then couldn't
|
||||
# match. The package lists stay, the snapshot's, for layers' apt-get install. The host keys its
|
||||
# package made go: each VM makes its own at each start.
|
||||
set -eu
|
||||
if command -v apt-get >/dev/null 2>&1; then
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends openssh-server
|
||||
elif command -v apk >/dev/null 2>&1; then
|
||||
apk add --no-cache openssh-server openssh-keygen
|
||||
else
|
||||
echo "sshd.sh: no apt-get or apk" >&2; exit 1
|
||||
fi
|
||||
rm -f /etc/ssh/ssh_host_*
|
||||
+3
-4
@@ -1,14 +1,13 @@
|
||||
// Package assets embeds the files devvm ships in its binary: base's Lima
|
||||
// template (base.yaml), base's scripts and policy (layers/), its optional
|
||||
// features (features/), the shared tools' config, build script and
|
||||
// policies (shared-tools/), the scripts sent into every VM (guest/),
|
||||
// --from's conversion (oci/), the scripts smolvm runs in its containers
|
||||
// (container/), and the smolvm backend's own scripts (smolvm/).
|
||||
// policies (shared-tools/), the scripts sent into every VM and its port
|
||||
// forwarder's (guest/), and --from's conversion (oci/).
|
||||
package assets
|
||||
|
||||
import "embed"
|
||||
|
||||
// FS holds devvm's files, by their paths in assets/.
|
||||
//
|
||||
//go:embed base.yaml layers features shared-tools guest oci container smolvm
|
||||
//go:embed base.yaml layers features shared-tools guest oci
|
||||
var FS embed.FS
|
||||
@@ -17,7 +17,7 @@ fi
|
||||
# the socket, and its relay is the VM's only way in. The clipboard is on or off as asked, changed
|
||||
# in place (vncconfig) on a desktop that runs; devvm's relay keeps the viewer's clipboard from the
|
||||
# VM when it's off whatever the server says. Then an Xfce session on it, in a D-Bus session of
|
||||
# its own (no init system starts one on smolvm and Docker). A run that started nothing prints
|
||||
# its own. A run that started nothing prints
|
||||
# nothing; its own log is ~/.cache/devvm-desktop.log.
|
||||
sudo install -m 755 /dev/stdin /usr/local/bin/devvm-desktop <<'S'
|
||||
#!/bin/sh
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
set -eu
|
||||
src=${1:-}
|
||||
r=${DEVVM_CA_ROOT:-}
|
||||
# update-ca-certificates is in sbin, which a machine's exec may leave out (smolvm's).
|
||||
# update-ca-certificates is in sbin, which a user's PATH may leave out.
|
||||
[ -n "$r" ] || PATH=$PATH:/usr/local/sbin:/usr/sbin:/sbin
|
||||
dir=$r/usr/local/share/ca-certificates
|
||||
bundle=$r/etc/ssl/certs/ca-certificates.crt
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/bin/sh
|
||||
# Run as the VM's user by its port forwarder on the host (devvm _lima-ports, _smolvm-ports), over
|
||||
# Run as the VM's user by its port forwarder on the host (devvm _lima-ports), over
|
||||
# devvm's ssh, for forwarding its ports: the TCP sockets listening in the VM, as /proc/net/tcp and tcp6 have
|
||||
# their local addresses (ADDRESS:PORT, in hex), one per line, each list ended by a line ".". A list
|
||||
# goes out when it changes, and every 10 s all the same, so the script ends soon after the
|
||||
+3
-25
@@ -24,7 +24,7 @@ host_home=$(cat "$s/host_home")
|
||||
|
||||
# shellcheck source=/dev/null
|
||||
. "$s/vm"
|
||||
# Running systemd, else OpenRC (Alpine) or none (smolvm, which may have systemctl installed).
|
||||
# Running systemd, else OpenRC (Alpine).
|
||||
systemd=false; [[ -d /run/systemd/system ]] && systemd=true
|
||||
if [[ -n "$DEVVM_HOSTNAME" && "$(hostname)" != "$DEVVM_HOSTNAME" ]]; then
|
||||
if $systemd; then sudo hostnamectl set-hostname "$DEVVM_HOSTNAME"
|
||||
@@ -44,7 +44,7 @@ link_hosts() {
|
||||
}
|
||||
link_hosts /etc/hosts "$s/hosts"
|
||||
# A link listens on its target's own port, so one below 1024 needs them open to the VM's user, whose
|
||||
# sshd binds it. 1024 is the kernel's default (Lima's Alpine VMs, smolvm); Lima's Ubuntu and Debian
|
||||
# sshd binds it. 1024 is the kernel's default (Lima's Alpine VMs); Lima's Ubuntu and Debian
|
||||
# VMs have 0.
|
||||
ports=/proc/sys/net/ipv4/ip_unprivileged_port_start
|
||||
if [[ "$(cat "$ports" 2>/dev/null)" == 1024 ]]; then
|
||||
@@ -219,7 +219,7 @@ docker_proxies() { # docker_proxies CONFIG [sudo]: set (or remove) the proxy f
|
||||
rm -f "$tmp"
|
||||
}
|
||||
# nix-daemon (the nix layer) does Nix's downloads, and gets nothing of /etc/environment: under systemd
|
||||
# a drop-in with the proxy, else its settings file, devvm's alone (services.sh reads it), both removed
|
||||
# a drop-in with the proxy, else its settings file, devvm's alone (OpenRC reads it), both removed
|
||||
# when network policy is off.
|
||||
nixd=/nix/var/nix/profiles/default/bin/nix-daemon
|
||||
nix_conf=/etc/systemd/system/nix-daemon.service.d/devvm-proxy.conf
|
||||
@@ -251,16 +251,6 @@ fi
|
||||
if [[ "$nix_before" != "$(cat "$nix_conf" "$nix_cache" 2>/dev/null || true)" ]]; then
|
||||
if $systemd; then sudo systemctl daemon-reload && sudo systemctl try-restart nix-daemon.service
|
||||
elif [[ -x $nixd && -e /run/openrc/softlevel ]]; then sudo rc-service nix-daemon restart >/dev/null
|
||||
elif [[ -x $nixd ]]; then
|
||||
# No init system (smolvm): stopped, then started as assets/container/services.sh starts it.
|
||||
sudo sh -c 'pid=$(cat /run/nix-daemon.pid 2>/dev/null || true)
|
||||
if [ -n "$pid" ] && [ "$(cat "/proc/$pid/comm" 2>/dev/null)" = nix-daemon ] && kill "$pid"; then
|
||||
i=0; while kill -0 "$pid" 2>/dev/null && [ "$i" -lt 30 ]; do sleep 1; i=$((i + 1)); done
|
||||
fi
|
||||
[ ! -f /etc/conf.d/nix-daemon ] || . /etc/conf.d/nix-daemon
|
||||
mkdir -p /var/log
|
||||
nohup /nix/var/nix/profiles/default/bin/nix-daemon --daemon >/var/log/nix-daemon.log 2>&1 </dev/null &
|
||||
echo $! > /run/nix-daemon.pid'
|
||||
fi
|
||||
fi
|
||||
dropin=/etc/systemd/system/docker.service.d/devvm-proxy.conf
|
||||
@@ -358,18 +348,6 @@ if command -v dockerd >/dev/null; then
|
||||
if [[ "$before" != "$(sudo cat "$dropin" 2>/dev/null || true)" ]]; then
|
||||
if $systemd; then sudo systemctl daemon-reload && sudo systemctl restart docker
|
||||
elif [[ -e /run/openrc/softlevel ]]; then sudo rc-service docker restart >/dev/null
|
||||
else
|
||||
# No init system (smolvm): stopped, then started as assets/container/services.sh starts it, with
|
||||
# Docker's settings read (devvm's block) and the proxy variables sudo keeps. A pid file whose
|
||||
# process isn't dockerd (a pid reused since) names nothing to stop, and Docker's run folder goes.
|
||||
sudo sh -c 'pid=$(cat /run/docker.pid 2>/dev/null || true)
|
||||
if [ -n "$pid" ] && [ "$(cat "/proc/$pid/comm" 2>/dev/null)" = dockerd ] && kill "$pid" 2>/dev/null; then
|
||||
i=0; while kill -0 "$pid" 2>/dev/null && [ "$i" -lt 30 ]; do sleep 1; i=$((i + 1)); done
|
||||
fi
|
||||
rm -rf /run/docker.pid /run/docker
|
||||
[ ! -f /etc/conf.d/docker ] || . /etc/conf.d/docker
|
||||
mkdir -p /var/log
|
||||
nohup dockerd -p /run/docker.pid >/var/log/dockerd.log 2>&1 </dev/null &'
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
@@ -53,13 +53,8 @@ else
|
||||
sudo usermod -aG docker "$USER"
|
||||
fi
|
||||
|
||||
# Running now too, for the rest of the build: systemd started it with the package; OpenRC
|
||||
# starts it here; with no init system (smolvm), devvm starts it after each start
|
||||
# (assets/container/services.sh), and here.
|
||||
if [[ -d /run/systemd/system ]]; then
|
||||
:
|
||||
elif [[ -d /run/openrc ]]; then
|
||||
# Running now too, for the rest of the build: systemd started it with the package, and OpenRC
|
||||
# starts it here.
|
||||
if [[ -d /run/openrc ]]; then
|
||||
sudo rc-service docker start
|
||||
else
|
||||
sudo sh -c 'mkdir -p /var/log && nohup dockerd -p /run/docker.pid >/var/log/dockerd.log 2>&1 </dev/null &'
|
||||
fi
|
||||
@@ -50,10 +50,10 @@ if [[ -n $(sudo find /nix/store -mindepth 1 -maxdepth 1 ! -user root -print -qui
|
||||
echo "devvm: Nix's store isn't root's after its install" >&2
|
||||
exit 1
|
||||
fi
|
||||
# Running now too, for the rest of the build: systemd started it; OpenRC (Alpine) gets a service
|
||||
# of devvm's, started at each boot and now; with no init system, devvm starts it after each start
|
||||
# (assets/container/services.sh), and here. Without systemd, its settings are /etc/conf.d/nix-daemon
|
||||
# (guest/sync.sh's: the proxy under network policy), which OpenRC reads for its service.
|
||||
# Running now too, for the rest of the build: systemd started it, and OpenRC (Alpine) gets a
|
||||
# service of devvm's, started at each boot and now. Under OpenRC, its settings are
|
||||
# /etc/conf.d/nix-daemon (guest/sync.sh's: the proxy under network policy), which OpenRC reads
|
||||
# for its service.
|
||||
if [[ -d /run/systemd/system ]]; then
|
||||
sudo systemctl is-active --quiet nix-daemon.socket
|
||||
elif [[ -d /run/openrc ]]; then
|
||||
@@ -71,11 +71,6 @@ RC
|
||||
sudo chmod 755 /etc/init.d/nix-daemon
|
||||
sudo rc-update add nix-daemon default
|
||||
sudo rc-service nix-daemon start
|
||||
else
|
||||
sudo sh -c '[ ! -f /etc/conf.d/nix-daemon ] || . /etc/conf.d/nix-daemon
|
||||
mkdir -p /var/log
|
||||
nohup /nix/var/nix/profiles/default/bin/nix-daemon --daemon >/var/log/nix-daemon.log 2>&1 </dev/null &
|
||||
echo $! > /run/nix-daemon.pid'
|
||||
fi
|
||||
|
||||
# sudo nix: sudo's secure_path, with Nix's default profile last.
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
#!/bin/sh
|
||||
# Run as root in the tools build machine after assets/shared-tools/build.sh: smolvm's kernel
|
||||
# mounts only uncompressed EROFS, so each image build.sh made is unpacked and made again without compression,
|
||||
# its owners all root as build.sh has them. Unpacked on the machine's own disk: the host folder
|
||||
# the images are in keeps no modes.
|
||||
# plain.sh DIR FILE...
|
||||
set -eu
|
||||
dir=$1; shift
|
||||
tree=/var/tmp/devvm-plain
|
||||
for file in "$@"; do
|
||||
img=$dir/$file
|
||||
rm -rf "$tree"
|
||||
fsck.erofs --extract="$tree" "$img"
|
||||
mkfs.erofs --all-root "$img.plain" "$tree" >/dev/null
|
||||
mv "$img.plain" "$img"
|
||||
rm -rf "$tree"
|
||||
done
|
||||
@@ -490,15 +490,6 @@ html.dark .highlight .chroma .go {
|
||||
shape-rendering: crispEdges;
|
||||
}
|
||||
|
||||
/* Dashed borders (the experimental backends): 1px, on half-pixel coordinates so they stay sharp. */
|
||||
.devvm-art .dash {
|
||||
fill: var(--devvm-surface);
|
||||
stroke: var(--devvm-blue);
|
||||
stroke-width: 1;
|
||||
stroke-dasharray: 4 3;
|
||||
shape-rendering: crispEdges;
|
||||
}
|
||||
|
||||
/* The art's animations, slow and in the palette's colors, each marked by a class in the SVG:
|
||||
.pulse dims and brightens a lime arrow every 3 s, .pulse-2 and .pulse-3 a step later, so the pulse runs
|
||||
along it; .pulse-slow does the same every 4 s; .lit (a text's fill) and .lit-chip (a chip's opacity) light
|
||||
|
||||
@@ -1,21 +1,10 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 224 70" role="img" aria-labelledby="art-backends">
|
||||
<title id="art-backends">Three backends, each running a VM: Lima, the default, then smolvm and Docker, both experimental.</title>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 224 28" role="img" aria-labelledby="art-backends">
|
||||
<title id="art-backends">Lima, running a VM.</title>
|
||||
<!-- Lima: a solid lime border. -->
|
||||
<rect class="a" x="7" y="7" width="126" height="14"/>
|
||||
<rect class="s" x="8" y="8" width="124" height="12"/>
|
||||
<text class="t" x="14" y="18">Lima</text>
|
||||
<rect class="f" x="91" y="9" width="35" height="10"/>
|
||||
<text class="t" x="98" y="18">VM</text>
|
||||
<text class="a pulse-slow" x="140" y="18">default</text>
|
||||
<!-- smolvm and Docker: dashed borders. -->
|
||||
<rect class="dash" x="7.5" y="28.5" width="125" height="13"/>
|
||||
<text class="t" x="14" y="39">smolvm</text>
|
||||
<rect class="f" x="91" y="30" width="35" height="10"/>
|
||||
<text class="t" x="98" y="39">VM</text>
|
||||
<text class="d" x="140" y="39">experimental</text>
|
||||
<rect class="dash" x="7.5" y="49.5" width="125" height="13"/>
|
||||
<text class="t" x="14" y="60">Docker</text>
|
||||
<rect class="f" x="91" y="51" width="35" height="10"/>
|
||||
<text class="t" x="98" y="60">VM</text>
|
||||
<text class="d" x="140" y="60">experimental</text>
|
||||
<text class="a pulse-slow" x="140" y="18">backend</text>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 1.1 KiB After Width: | Height: | Size: 517 B |
@@ -78,7 +78,7 @@ Claude Code, Codex and opencode run in the VM. Check one in the list when devvm
|
||||
|
||||
{{< feature title="Backends" icon="cube" level="3" art="backends" >}}
|
||||
|
||||
[Lima](https://lima-vm.io/) runs the VMs by default, and [smolvm](https://smolmachines.com/) is an {{< experimental >}} backend ([backends](docs/backends/_index.md)).
|
||||
[Lima](https://lima-vm.io/) runs the VMs, with Apple's Virtualization framework on macOS and QEMU on Linux ([backends](docs/backends/_index.md)).
|
||||
|
||||
{{< /feature >}}
|
||||
|
||||
@@ -145,7 +145,7 @@ Claude Code, Codex and opencode run in the VM. Check one in the list when devvm
|
||||
|
||||
### What does it run on?
|
||||
|
||||
`devvm` runs on macOS 13 or newer and on Linux, on arm64 or x86_64. It needs one of the supported [backends](docs/backends/_index.md): Lima 2.0 or newer, the default, which Homebrew installs along with devvm and which on Linux also needs QEMU and access to `/dev/kvm`, or smolvm, which is {{< experimental >}}. [Installing](docs/getting-started/install.md) lists every requirement, and [known limits](docs/using/limits.md#linux-hosts) lists what Linux hosts lack, such as `.git` protection.
|
||||
`devvm` runs on macOS 13 or newer and on Linux, on arm64 or x86_64. It needs [Lima](docs/backends/_index.md) 2.0 or newer, which Homebrew installs along with devvm and which on Linux also needs QEMU and access to `/dev/kvm`. [Installing](docs/getting-started/install.md) lists every requirement, and [known limits](docs/using/limits.md#linux-hosts) lists what Linux hosts lack, such as `.git` protection.
|
||||
|
||||
### Does the agent run on my machine?
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ The docs are in the order you'll need them: getting devvm running, using it day
|
||||
{{< section-card path="getting-started" >}}Installing devvm, making your first VM, and the commands you use most.{{< /section-card >}}
|
||||
{{< section-card path="using" >}}Images and toolchains, ports and size, coding agents, editors, settings, and what to do when something fails.{{< /section-card >}}
|
||||
{{< section-card path="safety" >}}The habits that keep you safe, network policy, `.git` protection, and what devvm does about each attack.{{< /section-card >}}
|
||||
{{< section-card path="backends" >}}What runs the VMs: Lima by default, and smolvm, which is experimental.{{< /section-card >}}
|
||||
{{< section-card path="backends" >}}What runs the VMs: Lima.{{< /section-card >}}
|
||||
{{< section-card path="cli" >}}Every command, with its arguments and flags.{{< /section-card >}}
|
||||
{{< section-card path="internals" >}}How devvm builds images, forwards ports, enforces network policy and protects `.git`, on each backend.{{< /section-card >}}
|
||||
{{< section-card path="contributing" >}}Building, testing and writing docs, other hosts, and releases.{{< /section-card >}}
|
||||
|
||||
@@ -3,42 +3,32 @@ title: Backends
|
||||
weight: 40
|
||||
---
|
||||
|
||||
A backend is the program that runs devvm's VMs and builds their images. devvm decides what goes into a VM, such as its image, its folders, its size and its network policy, and the backend runs it. [Lima](lima.md) is the default backend, and [smolvm](smolvm.md) is experimental.
|
||||
A backend is the program that runs devvm's VMs and builds their images. devvm decides what goes into a VM, such as its image, its folders, its size and its network policy, and the backend runs it. [Lima](lima.md) is devvm's backend.
|
||||
|
||||
## Comparing the backends
|
||||
## What Lima gives you
|
||||
|
||||
| | Lima | smolvm {{< experimental >}} |
|
||||
| --- | --- | --- |
|
||||
| Each project gets | a full VM with a kernel of its own | a microVM that runs the image as a container, with no init system |
|
||||
| Hosts | macOS 13 or newer, or Linux, on arm64 or x86_64 | an arm64 Mac, or Linux on arm64 or x86_64, but only the Mac is tested |
|
||||
| You need | Lima 2.0 or newer, and on Linux QEMU and access to `/dev/kvm` ([requirements](lima.md#requirements)) | smolvm 1.32 or newer, and on Linux access to `/dev/kvm` ([requirements](smolvm.md#requirements)) |
|
||||
| Network policy | {{< yes >}} yes | {{< yes >}} yes |
|
||||
| The docker layer | {{< yes >}} yes | {{< yes >}} yes |
|
||||
| The nix layer | {{< yes >}} yes | {{< yes >}} yes |
|
||||
| Limits | paths with commas, and shrinking a disk ([limits](lima.md#limits)) | paths with colons, and with SSH agent forwarding on, the agent is in the VM the whole time it runs ([what's different](smolvm.md#whats-different)) |
|
||||
| | Lima |
|
||||
| --- | --- |
|
||||
| Each project gets | a full VM with a kernel of its own |
|
||||
| Hosts | macOS 13 or newer, or Linux, on arm64 or x86_64 |
|
||||
| You need | Lima 2.0 or newer, and on Linux QEMU and access to `/dev/kvm` ([requirements](lima.md#requirements)) |
|
||||
| Network policy | {{< yes >}} yes |
|
||||
| The docker layer | {{< yes >}} yes |
|
||||
| The nix layer | {{< yes >}} yes |
|
||||
| Limits | paths with commas, and shrinking a disk ([limits](lima.md#limits)) |
|
||||
|
||||
`.git` protection uses your machine's file flags, so it works the same on every backend.
|
||||
`.git` protection uses your machine's file flags, so it doesn't depend on the backend.
|
||||
|
||||
Each backend has its own images. An image's key includes its backend, so one backend never uses another's images.
|
||||
An image's key includes its backend, so a backend never uses an image another backend built.
|
||||
|
||||
`devvm doctor` lists each backend's features, which are what the backend does itself, what devvm builds from other parts of it, and what it can't do. These are backend features, not the base image features you choose with `devvm setup`, even though `devvm doctor` calls both "features". [How it works › Backends](../internals/backends.md) explains them, backend by backend.
|
||||
|
||||
## Choosing a backend
|
||||
|
||||
To choose, follow the comparison above:
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
start{{"fine with an<br>experimental backend?"}} -- "no" --> lima["Lima, the default"]
|
||||
start -- "yes" --> arm{{"an arm64 Mac,<br>or Linux?"}}
|
||||
arm -- "yes" --> smolvm["smolvm"]
|
||||
arm -- "no" --> lima
|
||||
```
|
||||
|
||||
A new VM gets the first of:
|
||||
Lima is the only backend, so every choice below is `lima`. A new VM gets the first of:
|
||||
|
||||
1. `--backend`.
|
||||
2. `backend` in [`config.toml`](../using/settings.md#configtoml), such as `backend = "smolvm"`.
|
||||
2. `backend` in [`config.toml`](../using/settings.md#configtoml), such as `backend = "lima"`.
|
||||
3. The default that `devvm setup` saved.
|
||||
4. `lima`.
|
||||
|
||||
@@ -49,7 +39,7 @@ devvm setup # asks, then for base's features and new VMs' size
|
||||
devvm setup --backend NAME # without asking; the features, size and network policy stay as they are
|
||||
```
|
||||
|
||||
In a terminal, `devvm setup` lists every backend, with the experimental ones marked, starting from the current default. The up and down keys (or `k` and `j`) move, and Enter confirms. devvm saves and prints the choice, then asks for [base's features](../using/customizing.md#choosing-features), for the [CPUs and memory](../using/ports-size.md#choosing-new-vms-size) that new VMs get and for their network policy ([devvm setup](../using/settings.md#devvm-setup)). With `--features` alone, or without a terminal, it doesn't ask for the backend. When `config.toml` sets `backend`, `devvm setup` doesn't ask for it, and `devvm setup --backend` refuses and names the file, so edit `config.toml` instead ([where a default comes from](../using/settings.md#where-a-default-comes-from)). `devvm doctor` names the file that sets the backend it checks, and its `--json` says where it came from in `backend_source`.
|
||||
In a terminal, `devvm setup` lists every backend, starting from the current default. The up and down keys (or `k` and `j`) move, and Enter confirms. devvm saves and prints the choice, then asks for [base's features](../using/customizing.md#choosing-features), for the [CPUs and memory](../using/ports-size.md#choosing-new-vms-size) that new VMs get and for their network policy ([devvm setup](../using/settings.md#devvm-setup)). With `--features` alone, or without a terminal, it doesn't ask for the backend. When `config.toml` sets `backend`, `devvm setup` doesn't ask for it, and `devvm setup --backend` refuses and names the file, so edit `config.toml` instead ([where a default comes from](../using/settings.md#where-a-default-comes-from)). `devvm doctor` names the file that sets the backend it checks, and its `--json` says where it came from in `backend_source`.
|
||||
|
||||
A VM's state records its backend, and the VM stays on that backend, so devvm ignores `--backend` on an existing VM. When `config.toml`, the saved default or a VM's state names a backend devvm doesn't have, devvm stops and lists the ones it has.
|
||||
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
---
|
||||
title: smolvm (experimental)
|
||||
weight: 2
|
||||
---
|
||||
|
||||
{{< experimental >}}
|
||||
|
||||
[smolvm](https://github.com/smol-machines/smolvm) is an experimental backend. Each project gets a microVM that runs its image as a container, with no init system, so devvm starts the VM's services itself after each start. You choose it for one VM with `--backend smolvm`, or for every new VM with `devvm setup --backend smolvm`.
|
||||
|
||||
Network policy, `devvm host`, `devvm code`, `--clone`, forwarding ports and turning SSH agent forwarding on or off after a VM is made all work as they do on Lima. smolvm lacks some of these, so devvm builds them from other parts of smolvm, and [How it works › smolvm](../internals/smolvm.md) explains how.
|
||||
|
||||
## Requirements
|
||||
|
||||
- smolvm 1.32 or newer, with `smolvm` on your `PATH`. With Homebrew, run `brew install smol-machines/tap/smolvm`.
|
||||
- An arm64 Mac, or Linux on arm64 or x86_64 with a `/dev/kvm` you can read and write. Only the Mac is tested.
|
||||
|
||||
`devvm doctor --backend smolvm` checks both, and when you have Homebrew it shows the command that installs smolvm.
|
||||
|
||||
## What's different
|
||||
|
||||
- **devvm's machines are next to yours.** On macOS, `smolvm machine ls` shows devvm's machines along with your own. Each of devvm's carries the label `devvm.data=<devvm's data folder>`, and devvm touches only the machines with its label.
|
||||
- **Docker in a VM works.** The [docker layer](../using/images.md#built-in-layers) runs Docker's engine in the VM, as on Lima, and you can add it to an existing VM.
|
||||
- **Nix works.** The [nix layer](../using/images.md#nix) runs Nix's daemon in the VM, with each build in Nix's sandbox, as on Lima.
|
||||
- **The SSH agent is in the VM the whole time it runs.** With [SSH agent forwarding](../using/ssh.md#agent-forwarding) on, smolvm forwards the agent into the VM for as long as the VM runs, whether or not you're connected, and not only during your ssh sessions as on Lima.
|
||||
- **File watchers see your edits, but not your deletions.** A dev server or a file watcher in the VM sees the files you make on this machine, and it sees a file you change here when it watches that file itself. A watcher that watches only the file's folder learns that the folder changed, but not which file, and no watcher sees the files you delete here. A watcher that needs deletions, or one that watches only folders, can poll the project folder instead, with the settings on the [Lima page](lima.md#file-watchers).
|
||||
- **Paths can't contain colons.** smolvm splits mounts on colons, so devvm refuses a folder whose path has one.
|
||||
- **Start VMs with devvm, not `smolvm machine start`.** A VM started outside devvm gets the SSH agent your shell has, whatever you chose for it, and devvm's ssh doesn't run in it. When devvm finds such a VM running, it stops the VM and says so, unless the VM uses your agent anyway, and the next devvm starts it again with its own choice.
|
||||
|
||||
## Looking inside
|
||||
|
||||
When a build fails, devvm keeps its machine, stopped. To look inside, run `smolvm machine start --name devvm-img-<key>`, then `smolvm machine shell --name devvm-img-<key>`, which gives you a root shell. The next build, or `devvm gc`, deletes the machine.
|
||||
|
||||
## Cleaning smolvm's caches
|
||||
|
||||
Each of devvm's smolvm images is a full pack, and `base`'s is about 450 MB. When you stop using smolvm, `devvm gc --backend smolvm` deletes all of devvm's packs and the shared tools built for smolvm that no VM has and that aren't current, except a pack that a VM was made from ([cleaning up](../using/images.md#cleaning-up)). smolvm also keeps caches of its own (`~/Library/Caches/smolvm` on macOS), which also hold your own machines and packs. The largest part is the disk smolvm unpacks of each pack that a machine is made from, which stays after the pack is gone. `devvm gc --caches` frees those of devvm's packs that no VM of devvm's was made from, after listing them and asking ([what devvm keeps](../using/space.md#smolvm)). devvm never runs `smolvm pack prune` or `smolvm machine prune`, because they also clean what belongs to your own packs and machines. Before a build or a new VM, devvm checks the free space on the disk of its data folder, and on macOS also on that of your home folder, where smolvm keeps machines ([free space](../using/ports-size.md#free-space)).
|
||||
@@ -16,9 +16,8 @@ devvm build IMAGE [flags]
|
||||
## Examples
|
||||
|
||||
```text
|
||||
devvm build docker # build base and the docker layer on it
|
||||
devvm build foo+bar # build base, foo and foo+bar
|
||||
devvm build base --backend smolvm # build base on the smolvm backend
|
||||
devvm build docker # build base and the docker layer on it
|
||||
devvm build foo+bar # build base, foo and foo+bar
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
@@ -16,9 +16,8 @@ devvm doctor [flags]
|
||||
## Examples
|
||||
|
||||
```text
|
||||
devvm doctor # check the backend new VMs get
|
||||
devvm doctor --backend smolvm # check the smolvm backend
|
||||
devvm doctor --json # the same as JSON, for scripts
|
||||
devvm doctor # check the backend new VMs get
|
||||
devvm doctor --json # the same as JSON, for scripts
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
@@ -19,7 +19,6 @@ devvm gc [--tool-images [--recent] [TOOL...]] [flags]
|
||||
devvm gc # delete stale images and unused tools, after asking
|
||||
devvm gc --tool-images # also the current shared tool images no VM has
|
||||
devvm gc --history --older-than 30d # also the history exports 30 days old or more
|
||||
devvm gc --backend smolvm # delete every image and unused tool of the smolvm backend
|
||||
devvm gc --force # delete without asking, as a script must
|
||||
```
|
||||
|
||||
|
||||
@@ -17,7 +17,6 @@ devvm setup [flags]
|
||||
|
||||
```text
|
||||
devvm setup # answer every question
|
||||
devvm setup --backend smolvm # make smolvm the default backend, without asking
|
||||
devvm setup --features omb,fzf # give base oh-my-bash and fzf, without asking
|
||||
devvm setup --features none # give base no features
|
||||
devvm setup --agents claude,codex # give new VMs Claude Code and Codex, without asking
|
||||
|
||||
@@ -16,9 +16,8 @@ devvm space [flags]
|
||||
## Examples
|
||||
|
||||
```text
|
||||
devvm space # show what devvm keeps and what frees it
|
||||
devvm space --backend smolvm # only the smolvm backend's
|
||||
devvm space --json # the same as JSON, for scripts
|
||||
devvm space # show what devvm keeps and what frees it
|
||||
devvm space --json # the same as JSON, for scripts
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
@@ -95,7 +95,7 @@ The layers:
|
||||
|
||||
- Only `cmd/devvm` and `internal/cli` import `internal/ui`; only `internal/cli` imports `internal/vm`; only `cmd/devvm` imports `internal/cli`.
|
||||
- `internal/backend/...` imports none of `internal/vm`, `build`, `tools`, `netpolicy`, `secrets`, `project`, `gitprotect`, `sshconfig` or `sshagent`.
|
||||
- Only `internal/backend/registry` and `internal/cli` import a backend (`lima`, `smolvm`); only tests import `backendtest` and `internal/stubtest`, and `internal/stubtest` imports only `internal/msg`.
|
||||
- Only `internal/backend/registry` and `internal/cli` import a backend (`lima`); only tests import `backendtest` and `internal/stubtest`, and `internal/stubtest` imports only `internal/msg`.
|
||||
- `internal/proxy` imports no other devvm package but `internal/daemon`.
|
||||
- `assets`, `locales`, `internal/platform`, `internal/msg/gen`, `internal/testbuild`, `internal/hostgit`, `internal/shell`, `internal/vmname`, `internal/daemon` and `internal/fetch` import no devvm package; `internal/msg` only `locales`; `internal/paths` only `internal/msg`; `internal/state` only `internal/msg` and `internal/paths`; `internal/image` only `assets`, `internal/msg` and `internal/paths`; `internal/devcontainer` only `internal/image`, `internal/msg` and `internal/shell`.
|
||||
|
||||
@@ -285,7 +285,6 @@ tests/e2e.sh # every section but from
|
||||
tests/e2e.sh --from # every section, from too: the longest
|
||||
tests/e2e.sh --only images # just these sections
|
||||
tests/e2e.sh --clean # delete the sandbox's cached images and tool images first
|
||||
tests/e2e.sh --backend smolvm # the smolvm section alone (needs smolvm, not Lima)
|
||||
```
|
||||
|
||||
The sections so far:
|
||||
@@ -296,10 +295,9 @@ The sections so far:
|
||||
- `tools`: first, the shared tools resolve to upstream's newest versions, with devvm's pinned mise (downloaded once), each download with its checksum; the rest of the run doesn't check again (`DEVVM_NO_TOOL_CHECK`). Then a node project's VM: node, npm, pnpm, bun and yarn at the locked versions, each a read-only EROFS image, the share read-only even for root, `npm i -g` into the VM's home, a non-login shell over SSH, an `.nvmrc`'s own version, the tools mounted at boot without devvm, and a second node VM that builds nothing.
|
||||
- `network`: a VM with Claude Code and Codex and `--network-policy`, a fake token in devvm's environment and a fake `~/.claude.json` and Codex login in a home of its own. Its proxy runs and the self-check passed; its password was in no host process's arguments while devvm launched it (`ps`, sampled), and the guest has it; `ssh devvm-net` reaches it; direct connections fail, even as root, to an address and to other ports; an allowed host works and others, or other ports, are blocked; a line in the VM's policy file that reads as a deny but isn't a rule makes the running proxy refuse an allowed host, with no allow command in `devvm network log --blocked`, `devvm network rm` warns of it, and the host works again once it's gone; DNS fails at once; the host's loopback services are out of reach, directly or through the proxy; the proxy refuses requests without the VM's password; the token is nowhere in the VM, which has devvm's CA, its own placeholder and logins' copies with placeholders only; the proxy puts the token in for its host (for the VM's own placeholder only), an MCP server's header and Codex's key for theirs, over TLS the VM verifies; the host's login files are unchanged. `devvm secret set github --stdin` saves a fake token (in the Keychain on macOS, under the run's service, found through a link to `~/Library/Keychains` in the VM's home) and `secret get` reads it back; `secret use github` binds it to the running proxy at once, and on the next launch the VM has its own placeholder in `GH_TOKEN`, never the token, which the proxy puts in for `api.github.com`; `secret unuse` and `rm` take the binding and the token away. `TestE2ESelfCheck` in `internal/netpolicy` runs the self-check on the VM: it passes, then, once the VM is started outside devvm, it fails and stops the VM. `devvm stop` stops the VM and its proxy at once. `devvm network off` makes its next start direct, without a proxy; `on` while it runs shows it `unenforced` until `devvm restart` starts it confined; `off` while it runs confined keeps it on its proxy until it next starts.
|
||||
- `nix`: the nix layer. A copy of `assets/layers/nix.sh` as a layer of the run's own, built behind a company proxy of the run's own, reaches Nix's releases through it and leaves no proxy settings for `nix-daemon` (and not the company proxy's password) anywhere on its image's disk. Then a folder with `package.json`, `flake.nix` and `.envrc` gets a VM with node on the nix layer (`--layers nix`) and network policy: Nix and direnv at their pins, a store that's root's, `sandbox` on with no fallback, `trusted-users` root alone and an untrusted user's `--option substituters` ignored, `nix-daemon` with the VM's own proxy in devvm's drop-in alone, `nix run nixpkgs#hello` from Nix's cache, a build in Nix's sandbox, `sudo nix` and `nix` over ssh, the flake's dev shell (nixpkgs at a pinned revision) loaded by direnv in an interactive shell, its `node` ahead of the shared node prompt after prompt and gone outside the folder, nix-direnv's cache in the VM's home with no `.direnv` in the folder, a fixed-output download from a host that isn't allowed refused with `403` and named by `devvm-why`, and after `devvm network off` and `devvm restart`, no drop-in and no proxy for the daemon.
|
||||
- `smolvm` (`--backend smolvm`): the [smolvm backend](../backends/smolvm.md) on smolvm's own machines, which on macOS share yours: the run looks only at machines with its sandbox's label, deletes only those it made, and checks every other machine is as it was. base and a fixture layer built as packs, a rebuild, `images rm`, and a failed script's machine kept stopped; a project VM with its size, the folder read-write and files the VM makes yours, the tools read-only even for root, its hostname, `TestE2EExecQuoting` in `internal/backend/smolvm` (arguments, folder, input, the VM's user and login environment), no Docker (no docker layer), a listed port on the host's loopback, a server on the VM's loopback alone reaching it, an unlisted port not forwarded, smolvm publishing none of the ports, a port added to a running VM reaching this machine at once and gone once removed, the VM never restarted, a new size applied on restart and new ports at once, a listed port a host program has on every address left to it until it's freed, stop, start and rm; a `--ssh-agent` VM using a throwaway agent, and none once turned off and restarted; ssh for editors' emulation ([its checks](../internals/design.md#ssh-for-editors-on-smolvm)): pinned host keys of each VM's own, its own key alone, no forwarding out even past a hostile sshd, `devvm host` and `code`, a VM `--from alpine:3` reached over ssh, a `--clone` VM's push and fetch; network policy's emulation, on a docker VM (no agent's login read): the VM behind its proxy and decider, the proxy's password in no host process's arguments while devvm launched it and in the guest's environment from its proxy file and Docker's daemon, Docker pulling through the proxy, its allow list and closed DNS, allowed and blocked hosts, direct connections failing even as root (to the host's loopback too), DNS failing at once and every probe query (TXT, ANY, AAAA, HTTPS, EDNS0, under `devvm.invalid`) refused in smolvm's decision log with no flow beyond the host's loopback (nettop, macOS), `devvm.invalid` as the log's control, UDP and ICMP getting nowhere, the decider's token nowhere in the VM or a process's arguments, `devvm network log`, `network allow` and `rm` at once, an allow list widened while it runs making it `unenforced`, nothing out with the proxy gone or a decider that answers garbage or nothing, no start without a decider, a start with someone else's decider stopped, and `network off` and `on`, where the direct, DNS and UDP probes get out (their controls); a docker VM `--from alpine:3` with network policy, its Docker restarted by devvm's setup and pulling through the proxy, and a restart over a stale pid file stopping no process but Docker's daemon; a node VM's uncompressed tool images; a nix VM with network policy, whose `nix-daemon` devvm starts with the VM's proxy in `/etc/conf.d/nix-daemon`, running `nix run nixpkgs#hello` through the proxy and a build in Nix's sandbox, then after `devvm network off` and `devvm restart` a daemon without the proxy.
|
||||
- `from`: run with a `docker` that isn't running, so nothing comes from Docker. A VM from `node:24` with node, python and Claude Code on the docker and nix layers (Debian 12, in a home of its own) boots, with its base keyed by the registry's digest, its node, python and claude at the locked versions, the docker layer's Docker from Docker's Debian repository, and the nix layer's Nix under systemd running `nix run nixpkgs#hello` and a build in Nix's sandbox; a VM from `alpine:3` with node on the docker and nix layers runs node and pnpm from musl tool images, the docker layer's Docker on OpenRC, with no crashed services, and the nix layer's Nix as an OpenRC service, with `nix run nixpkgs#hello` and a sandboxed build, then after `devvm network on` and `devvm restart` a download only its daemon makes from a host that isn't allowed refused with the proxy's `403`; base builds from `ubuntu:26.04`; and the build VM and its temporary folders are gone.
|
||||
|
||||
- `link`: links between VMs, each check the end-to-end proof of a row of the threat check in [the design note](../internals/design.md#links-between-vms). It runs devvm with a soft limit of 256 open files, macOS's default, as the link sessions it starts get that limit too, and it makes two small targets without network policy, each forwarding no port and running servers on its own `127.0.0.1` (`/var/tmp/e2e-link.pl`, in perl, which every base has), and a client that forwards every port. `sshd -T` in each VM shows remote forwards allowed on `127.77.*:*` alone, at the address the host asks for, and on Lima the client's own rules ignore every port. A port the target doesn't publish is refused by `devvm link add`, and once a port is published, `devvm link add` on the running client reaches it within seconds as `NAME:PORT` and `NAME.devvm.internal:PORT`, by curl and by a raw TCP client (bash's `/dev/tcp`), while with `--as NAME` the target's folder name doesn't resolve. Two targets on one port are each reached by their own name, port 80 is linked on port 80, `devvm link` and `devvm link publish` list what they hold with `"version": 1` in their `--json`, and `devvm network on` is refused for the client while it links to targets without network policy. A published port that isn't linked has nothing listening for it, `devvm link unpublish` refuses the link's next connection, logs it and names the client, and `devvm link rm` takes the listener away within seconds. In the client, sshd listens only on its own port and the links' addresses, and nothing from a link listens on `127.0.0.1`, `::1` or every address, so this machine gets no forward of a link, while a server of the client's own on `127.0.0.1` with a link's port is forwarded as usual. Each link's socket is mode 600 in the run folder of mode 700, and the link session and every process it starts listen on no TCP port and connect only to the VMs' ssh ports. `ssh -R` into the client binds nothing outside `127.77.0.0/16` (`rfwd_links`). A program in the client that holds a link's address first fails that link alone with `link_port_taken`, 256 connections at once, past the socket's backlog of 128 on macOS, are all carried, and a 257th is refused and logged as `link_limit`. Root in the client then loosens its sshd and the link session connects again: with `PermitListen any` the client binds only the links' addresses, because the host asks for nothing else, and with `GatewayPorts yes` too, the link session still listens on no TCP port of this machine and connects only to the VMs' sshd. `devvm network log` shows the links' connections and refusals. A stopped target refuses the connection, logs `link_target_stopped` and stays stopped, and the client's launch warns of it. Once it's restarted, the link works again, with the target's new host key on smolvm. `devvm rm` of the target removes the client's link, names the client and removes its sockets, and a VM made again in that folder isn't linked. Then the client and one target get network policy, the target while it runs. Until the target restarts, `devvm ls` shows it `unenforced`, the client's next connection is refused and logged as `unenforced` while the target's server runs, and `devvm link add` and the client's launch warn of it (`link_target_unenforced`). Once both have restarted, the client reaches its link by curl through its proxy settings and by a raw TCP client while a direct connection fails. A link added while the client runs is reached at once by curl through its proxy, by `GET` and `CONNECT`, with no link name in `NO_PROXY` and the client's boot and host keys unchanged, and the client's proxy refuses names, ports and addresses that aren't on its own list, while the target's proxy refuses the client's link name. `devvm link add` refuses a target without network policy, `devvm network off` is refused for the target, and with the rule broken by hand in the target's state the next connection is refused and the client's launch warns and runs without the link until the rule holds again. In the `--from` tier, an Alpine client reaches its link to port 80. `devvm rm` of the client leaves no link session, socket, pid file, log or link state. `--backend smolvm` runs the same checks.
|
||||
- `link`: links between VMs, each check the end-to-end proof of a row of the threat check in [the design note](../internals/design.md#links-between-vms). It runs devvm with a soft limit of 256 open files, macOS's default, as the link sessions it starts get that limit too, and it makes two small targets without network policy, each forwarding no port and running servers on its own `127.0.0.1` (`/var/tmp/e2e-link.pl`, in perl, which every base has), and a client that forwards every port. `sshd -T` in each VM shows remote forwards allowed on `127.77.*:*` alone, at the address the host asks for, and on Lima the client's own rules ignore every port. A port the target doesn't publish is refused by `devvm link add`, and once a port is published, `devvm link add` on the running client reaches it within seconds as `NAME:PORT` and `NAME.devvm.internal:PORT`, by curl and by a raw TCP client (bash's `/dev/tcp`), while with `--as NAME` the target's folder name doesn't resolve. Two targets on one port are each reached by their own name, port 80 is linked on port 80, `devvm link` and `devvm link publish` list what they hold with `"version": 1` in their `--json`, and `devvm network on` is refused for the client while it links to targets without network policy. A published port that isn't linked has nothing listening for it, `devvm link unpublish` refuses the link's next connection, logs it and names the client, and `devvm link rm` takes the listener away within seconds. In the client, sshd listens only on its own port and the links' addresses, and nothing from a link listens on `127.0.0.1`, `::1` or every address, so this machine gets no forward of a link, while a server of the client's own on `127.0.0.1` with a link's port is forwarded as usual. Each link's socket is mode 600 in the run folder of mode 700, and the link session and every process it starts listen on no TCP port and connect only to the VMs' ssh ports. `ssh -R` into the client binds nothing outside `127.77.0.0/16` (`rfwd_links`). A program in the client that holds a link's address first fails that link alone with `link_port_taken`, 256 connections at once, past the socket's backlog of 128 on macOS, are all carried, and a 257th is refused and logged as `link_limit`. Root in the client then loosens its sshd and the link session connects again: with `PermitListen any` the client binds only the links' addresses, because the host asks for nothing else, and with `GatewayPorts yes` too, the link session still listens on no TCP port of this machine and connects only to the VMs' sshd. `devvm network log` shows the links' connections and refusals. A stopped target refuses the connection, logs `link_target_stopped` and stays stopped, and the client's launch warns of it. Once it's restarted, the link works again. `devvm rm` of the target removes the client's link, names the client and removes its sockets, and a VM made again in that folder isn't linked. Then the client and one target get network policy, the target while it runs. Until the target restarts, `devvm ls` shows it `unenforced`, the client's next connection is refused and logged as `unenforced` while the target's server runs, and `devvm link add` and the client's launch warn of it (`link_target_unenforced`). Once both have restarted, the client reaches its link by curl through its proxy settings and by a raw TCP client while a direct connection fails. A link added while the client runs is reached at once by curl through its proxy, by `GET` and `CONNECT`, with no link name in `NO_PROXY` and the client's boot and host keys unchanged, and the client's proxy refuses names, ports and addresses that aren't on its own list, while the target's proxy refuses the client's link name. `devvm link add` refuses a target without network policy, `devvm network off` is refused for the target, and with the rule broken by hand in the target's state the next connection is refused and the client's launch warns and runs without the link until the rule holds again. In the `--from` tier, an Alpine client reaches its link to port 80. `devvm rm` of the client leaves no link session, socket, pid file, log or link state.
|
||||
|
||||
base, the `--from` bases and the shared tool images stay cached between runs, except what a rebuild or gc deletes: every stale image in the sandbox (other selections' bases, whose features differ, among them) and every unused tool image (an earlier `from` run's musl ones); every other VM a run makes is deleted at its end, and its project folders are unlocked and deleted. Each check prints `[n/N]`, how long it took and the time left as the last complete run measured it, and a heartbeat every minute shows the latest output. A check a run has nothing for is counted as `SKIP`: base's features, with base cached. A run with fewer checks than the last complete one of the same selection fails, as a section ended early. Checks look for devvm's messages with `devvm _msg`, never by their wording.
|
||||
|
||||
@@ -441,7 +439,7 @@ The site is [Hugo](https://gohugo.io) with the [Hextra](https://imfing.github.io
|
||||
- **Section cards** on the docs' first page are Hextra's `{{</* cards */>}}` holding a `{{</* section-card path="getting-started" */>}}` for each section, with its one-line description inside, closed with `{{</* /section-card */>}}`. The shortcode takes the section's title and link from its page under `docs/`, and its icon from `sections.yaml`, and the build fails when there's no such page. Hextra's card takes an icon only from Hextra's own set, so the shortcode puts ours in the card's title, at 24px. It's dimmed as Hextra dims its own cards' icons, and it turns lime on hover.
|
||||
- **The sidebar's top-level items** show their section's icon at 12px, in the link's color, so it's gray, and lime for the section you're in. Hextra's sidebar has no icons, so `docs/layouts/_partials/custom/head-end.html` writes a CSS rule for each section when the site builds, keyed to the section page's address, with the icon from `docs/assets/icons/` as a mask. Nothing is generated into the repo, so there's no step to rerun.
|
||||
- **The OS tabs** of `install` and `os-tabs` show the Apple icon before macOS and the penguin before Linux, which `docs/layouts/_partials/os-tab-name.html` adds to each tab's name.
|
||||
- **The experimental badge**, `{{</* experimental */>}}`, is the flask icon and the word experimental in Departure Mono at 11px, in the site's blue, in a rounded box. It reads as the word, so it can take the word's place in a sentence, as on the home page's Backends card. The smolvm page shows it above its first line, and the backends' comparison table beside its name.
|
||||
- **The experimental badge**, `{{</* experimental */>}}`, is the flask icon and the word experimental in Departure Mono at 11px, in the site's blue, in a rounded box. It reads as the word, so it can take the word's place in a sentence. It marks what's experimental.
|
||||
- **✓ and ✗** go before a table cell's word: `{{</* yes */>}} yes` puts a lime check before it, and `{{</* no */>}} doesn't` a gray cross. They go only in cells that are a plain yes or no, or what stands for one, such as the install script's offers it, never in cells that are sentences, and the word stays, because screen readers skip the icon. Icons in tables are 12px, because a table's text is smaller than 16px.
|
||||
- **Buttons** take an icon before their text: `docs/layouts/_shortcodes/hextra/hero-button.html` is Hextra's `hero-button` with an `icon` parameter, as in `{{</* hextra/hero-button text="Install" link="docs/getting-started/install/" icon="download" */>}}`, drawn at 24px like the headings' icons. The 404 page's two buttons have their icons in its layout, a rocket for Getting started and the open book for the docs, as the home page's Read the docs has it.
|
||||
- **The navbar's GitHub link** uses Dinkie's GitHub icon, which `docs/data/icons.yaml` adds to Hextra's own icons as `dinkie-github`, and `hugo.yaml`'s menu names. Hextra's icon partial reads only that data, so an icon for the navbar goes there as its SVG, not in `docs/assets/icons/`.
|
||||
|
||||
@@ -7,8 +7,8 @@ For maintainers: version bumps and releases. Run the scripts with mise, which pu
|
||||
|
||||
## Updating pinned versions
|
||||
|
||||
- `scripts/bump.sh --check` lists every pin against upstream; `scripts/bump.sh [tool...]` rewrites the pins (all tools by default) and prints a summary for the commit message. It writes a value only if it has the shape of a pin (a version, a 64-hex checksum, an image digest, a dated release, a commit), since some of the edited files run on the host, and edits nothing unless every value is good. It needs `curl` and `jq`, and `apt` needs `gpgv`.
|
||||
- The tools: `apt`, `docker`, `mise`, `rustup`, `crane`, `omb`, `eza`, `tealdeer`. `apt` moves `apt_snapshot` (base's packages) to today, and with it the images base starts from, all in `internal/ubuntu/ubuntu.go`: the digest of Ubuntu's container image, smolvm's (`ContainerDigest`), refusing an image built after the snapshot, whose packages would be newer than the snapshot's (try the next day); and Ubuntu's cloud image, Lima's (`CloudRelease`, `CloudSHA256Arm64`, `CloudSHA256Amd64`): the newest dated release before the snapshot's date on cloud-images.ubuntu.com, with its images' SHA-256s from its `SHA256SUMS`, which `gpgv` must find signed by `assets/layers/ubuntu-cloud.gpg` (it refuses when no release is old enough, or the signature fails). Ubuntu removes dated releases after a few months, and the pinned one going stops Lima's base builds: bump `apt` well before that; `docker` moves Docker's packages (`assets/layers/docker.sh`), read from its repository for base's Ubuntu release, and its signing key. Packages added to `assets/layers/base.sh` or `assets/features/` need no pin of their own: the snapshot covers them.
|
||||
- `scripts/bump.sh --check` lists every pin against upstream; `scripts/bump.sh [tool...]` rewrites the pins (all tools by default) and prints a summary for the commit message. It writes a value only if it has the shape of a pin (a version, a 64-hex checksum, a dated release, a commit), since some of the edited files run on the host, and edits nothing unless every value is good. It needs `curl` and `jq`, and `apt` needs `gpgv`.
|
||||
- The tools: `apt`, `docker`, `mise`, `rustup`, `crane`, `omb`, `eza`, `tealdeer`. `apt` moves `apt_snapshot` (base's packages) to today, and with it the image base starts from, in `internal/ubuntu/ubuntu.go`: Ubuntu's cloud image (`CloudRelease`, `CloudSHA256Arm64`, `CloudSHA256Amd64`), the newest dated release before the snapshot's date on cloud-images.ubuntu.com, with its images' SHA-256s from its `SHA256SUMS`, which `gpgv` must find signed by `assets/layers/ubuntu-cloud.gpg` (it refuses when no release is old enough, or the signature fails). It takes a release from before the snapshot because an image with packages newer than the snapshot's leaves apt unable to install what depends on their exact versions. Ubuntu removes dated releases after a few months, and the pinned one going stops base's builds: bump `apt` well before that; `docker` moves Docker's packages (`assets/layers/docker.sh`), read from its repository for base's Ubuntu release, and its signing key. Packages added to `assets/layers/base.sh` or `assets/features/` need no pin of their own: the snapshot covers them.
|
||||
- `mise` moves base's mise (`assets/layers/base.sh`) and devvm's host mise (`internal/tools/mise.go`) together: the host one writes the lock base's installs from.
|
||||
- The shared tools aren't pinned: holds go in `assets/shared-tools/mise.toml` (`node = "24"` stays on that major). `testdata/mise.lock` is a fixed lock for the tests.
|
||||
- `assets/layers/ubuntu-cloud.gpg` is Ubuntu's cloud image signing key (fingerprint `D2EB44626FDDC30B513D5BB71A5D6C4C7DB87C81`), from keyserver.ubuntu.com. If Ubuntu changes it, base builds stop with `ubuntu_bad_signature`: fetch the new key, check its fingerprint against Ubuntu's announcement, and replace the file (`gpg --export FPR`).
|
||||
|
||||
@@ -90,7 +90,7 @@ The settings that the [environment table](../using/settings.md#environment) list
|
||||
devvm refuses an emulated feature until its review passes, yet the review needs end-to-end checks of it. In a [test build](#test-builds), `DEVVM_UNREVIEWED` lets the ones it names through, as `backend:feature` pairs, comma-separated, each time with a warning (`backend_unreviewed_used`). A release ignores it:
|
||||
|
||||
```sh
|
||||
DEVVM_UNREVIEWED=smolvm:ports-all devvm --backend smolvm
|
||||
DEVVM_UNREVIEWED=lima:ports-all devvm
|
||||
```
|
||||
|
||||
It's for tests only, of an emulation before its review: none needs it now, as every emulation is reviewed. It never makes a feature a backend lacks usable, and `devvm doctor` still shows the feature `unreviewed`.
|
||||
@@ -130,10 +130,8 @@ TZ=Australia/Lord_Howe mise run test
|
||||
|
||||
What `tests/e2e.sh` leaves out, as it would change something of yours or needs something it doesn't have:
|
||||
|
||||
- **smolvm's DNS, from outside:** e2e watches smolvm's own decision log and this machine's flows, not the network. With a domain whose authoritative nameserver's queries you can watch (a canary zone), resolve a new name under it from a smolvm VM without network policy (`getent hosts <new>.canary.example`): the nameserver sees it. Then from one with network policy, through its resolver and straight to `1.1.1.1`, a new name under the zone, also as TXT: the nameserver sees none of them.
|
||||
|
||||
- **Screen Sharing on `devvm desktop`:** e2e speaks VNC itself (`TestE2EDesktop`), because it can't drive a window. In a VM whose base has the `desktop` feature, run `devvm desktop`. Screen Sharing opens and asks for the password devvm shows, and the Xfce desktop answers the mouse and keys. A wrong password gets refused. With Edit > Use Shared Clipboard on, text you copy on this machine doesn't paste in the VM, and with `devvm desktop --clipboard` it does. `~/.local/share/devvm/logs/runs/` has no line saying the relay doesn't know a message (`which the relay doesn't know`).
|
||||
|
||||
- **A VM's clock after this machine sleeps:** e2e can't sleep a Mac, and hosted CI can't either. With a Lima VM without network policy, a Lima VM with network policy and a smolvm VM running, compare each VM's `date +%s.%N` over ssh with this machine's clock, halfway through the ssh round trip. Then sleep the Mac for over 30 minutes and compare again right after it wakes and 2 minutes later. Each VM stays within about 0.1 s of this machine, the same as before the sleep, and the clock catches up without NTP: chrony in a VM with network policy has never synced, and smolvm runs no time sync, yet both stay right, while chrony in Lima's VMs logs `Forward time jump detected!` after the wake. Before you sleep the Mac, check that `pmset -g assertions` shows `PreventSystemSleep 0`. An app running `caffeinate -s` on AC power turns a sleep into a dark wake where the CPU keeps running, so the VMs never pause and the check proves nothing. In a real sleep, a measurement you run every few minutes in the background leaves a gap.
|
||||
- **A VM's clock after this machine sleeps:** e2e can't sleep a Mac, and hosted CI can't either. With a VM without network policy and a VM with network policy running, compare each VM's `date +%s.%N` over ssh with this machine's clock, halfway through the ssh round trip. Then sleep the Mac for over 30 minutes and compare again right after it wakes and 2 minutes later. Each VM stays within about 0.1 s of this machine, the same as before the sleep, and the clock catches up without NTP: chrony in a VM with network policy has never synced, yet it stays right, while chrony in each VM logs `Forward time jump detected!` after the wake. Before you sleep the Mac, check that `pmset -g assertions` shows `PreventSystemSleep 0`. An app running `caffeinate -s` on AC power turns a sleep into a dark wake where the CPU keeps running, so the VMs never pause and the check proves nothing. In a real sleep, a measurement you run every few minutes in the background leaves a gap.
|
||||
|
||||
- **`--from` an image only Docker has** (built locally, never pushed): it would build an image in your Docker. Build a small one (`docker build -t devvm-local-test .` from a `Dockerfile` with `FROM alpine:3`), run `devvm --from devvm-local-test` in a new folder, check the VM boots from it, then `devvm rm` and `docker image rm devvm-local-test`.
|
||||
@@ -60,7 +60,7 @@ devvm runs its VMs on [Lima](../backends/lima.md#requirements), its default [bac
|
||||
{{< /os-tab >}}
|
||||
{{< /os-tabs >}}
|
||||
|
||||
The Homebrew formula installs Lima along with devvm. ssh and editors reach VMs through devvm's ssh config, and OpenSSH versions older than 8.7 refuse its `PermitRemoteOpen` ([SSH access by name](../using/ssh.md#ssh-access-by-name)). Docker on this machine is optional, because only `--from` with an [image only Docker has](../using/from.md#images-only-docker-has) needs it. The experimental [smolvm](../backends/smolvm.md#requirements) backend has requirements of its own.
|
||||
The Homebrew formula installs Lima along with devvm. ssh and editors reach VMs through devvm's ssh config, and OpenSSH versions older than 8.7 refuse its `PermitRemoteOpen` ([SSH access by name](../using/ssh.md#ssh-access-by-name)). Docker on this machine is optional, because only `--from` with an [image only Docker has](../using/from.md#images-only-docker-has) needs it.
|
||||
|
||||
devvm also runs on a smaller machine, because it fits base to the machine. Base asks for 4 CPUs and 8 GiB of memory. On a machine with fewer than 4 CPUs, base gets as many CPUs as the machine has, and when 8 GiB would leave the machine less than 2 GiB of its own, base gets half of the machine's memory, which is 4 GiB on an 8 GiB machine. The VMs made from base get the same unless you give them a size, as [size and ports](../using/ports-size.md#size-and-ports) explains. When devvm builds base on such a machine, it says how many CPUs and how much memory base gets. `devvm size -g` sets the size that new VMs get instead, and `devvm doctor` warns when this machine has less than 8 GiB of memory or fewer than 4 CPUs.
|
||||
|
||||
@@ -111,7 +111,7 @@ Images whose inputs changed are built again the next time you use them. Existing
|
||||
|
||||
1. Delete your VMs: `devvm ls`, then `devvm rm` in each folder. For a `--clone` VM, this also removes the `devvm` git remote from the repo.
|
||||
2. Delete the images: `devvm gc`, then `devvm images rm` with every name `devvm images` lists. Images built `--from` a container image need the same `--from`: `devvm images rm --from node:24 base`.
|
||||
3. Free the backends' caches. In a terminal, `devvm gc --caches` frees devvm's share of them, after asking for each backend. If you don't use a backend yourself, you can also empty its cache: Lima keeps Ubuntu's cloud images in `~/Library/Caches/lima` on macOS and `~/.cache/lima` on Linux, and `limactl prune` deletes that whole cache. On macOS, smolvm keeps its caches and its machines in `~/Library/Caches/smolvm`, so delete that folder only once `smolvm machine ls` lists no machine you want to keep ([what devvm keeps](../using/space.md#smolvm)).
|
||||
3. Free Lima's cache. In a terminal, `devvm gc --caches` frees devvm's share of it, after asking. If you don't use Lima yourself, you can also empty its cache: Lima keeps Ubuntu's cloud images in `~/Library/Caches/lima` on macOS and `~/.cache/lima` on Linux, and `limactl prune` deletes that whole cache.
|
||||
4. Delete your saved secrets: `devvm secret rm NAME` for each one `devvm secret` lists. On macOS they're in the Keychain under the service `devvm`, and on Linux in `~/.local/share/devvm/secrets/`.
|
||||
5. Remove devvm itself, with the command for the way you installed it:
|
||||
|
||||
|
||||
@@ -15,5 +15,4 @@ These pages explain how devvm does what the other sections describe, for readers
|
||||
- [Security model](security.md): what devvm protects on your machine and how, and what it doesn't protect.
|
||||
- [Backends](backends.md): each backend's features, native or emulated, and what happens when one is missing.
|
||||
- [Lima](lima.md): devvm's Lima home, confinement, clones and port forwarding on Lima.
|
||||
- [smolvm](smolvm.md): how devvm builds and runs VMs on smolvm, and what it emulates there.
|
||||
- [Design notes](design.md): why devvm is built this way, what failed, and what's still open.
|
||||
@@ -3,7 +3,7 @@ title: Backends
|
||||
weight: 8
|
||||
---
|
||||
|
||||
This page explains how each backend gives devvm what it needs to run a VM, what devvm does when a backend lacks something, and how devvm names VMs. [Backends](../backends/_index.md) compares the backends to help you choose one.
|
||||
This page explains how a backend gives devvm what it needs to run a VM, what devvm does when a backend lacks something, and how devvm names VMs. devvm runs its VMs on [Lima](../backends/lima.md), and another backend plugs in the same way, through the features below.
|
||||
|
||||
## Features
|
||||
|
||||
@@ -19,35 +19,31 @@ devvm uses an emulation only once its review has passed, and until then it refus
|
||||
|
||||
### The feature table
|
||||
|
||||
| Feature | What it is | Lima | smolvm (experimental) |
|
||||
| --- | --- | --- | --- |
|
||||
| `build-image` | build images from the layer and feature scripts | native | native: a machine from Ubuntu's container image runs the scripts, and devvm then packs it (`pack create --from-vm`). Each image is a full pack, about 450 MB for `base` ([details](smolvm.md#building-images)) |
|
||||
| `build-confinement` | builds reach the internet but not the host's loopback, or nothing | native: Seatbelt on macOS. On Linux, QEMU's `restrict=on` confines a build with no network, but a build with the internet reaches the host's loopback ([details](lima.md#confinement)) | native: its default network refuses the host's loopback, and a build that reaches nothing gets no network |
|
||||
| `from` | `base` from a container image (`--from`) | native: devvm converts the image to a disk | native: smolvm boots registry images, by digest |
|
||||
| `clone` | a project VM from an image | native: an APFS copy-on-write copy on macOS, and a qcow2 overlay on Linux ([details](lima.md#clones-and-overlays)) | native: a machine from the image's pack ([details](smolvm.md#its-machines)) |
|
||||
| `project-mount` | the project folder, read-write | native: virtiofs on macOS, and 9p on Linux | native: virtiofs. Files the VM makes are the user's on the host, with mode 0600 |
|
||||
| `agent-folders` | agents' host folders, read-only | native: read-only mounts, enforced by the host | native: read-only mounts, enforced by the host |
|
||||
| `tools-share` | the shared tools, read-only | native: a read-only mount, enforced by the host | native: a read-only mount, enforced by the host. The tool images are uncompressed, because its kernel's EROFS has no compression |
|
||||
| `egress-proxy` | network traffic only through devvm's proxy | native: Seatbelt on macOS, and on Linux QEMU's `restrict=on` with a `guestfwd` to the proxy ([details](lima.md#confinement)) | emulated (reviewed): an allow list of the host alone, DNS closed but for one name, and devvm's proxy deciding each connection ([details](smolvm.md#network-policy)) |
|
||||
| `ssh` | ssh for editors | native: Lima's ssh forward and config | emulated (reviewed): an sshd of devvm's on a port forwarded from the host's loopback, started after each start with new host keys and the VM's own key alone. Its ssh config entries ask for no forwarding out ([details](smolvm.md#ssh-for-editors)) |
|
||||
| `ports` | the listed ports forwarded to the host's loopback | emulated (reviewed): devvm's forwarder over Lima's ssh, for the listed ports alone, with Lima's own forwards off ([details](lima.md#ports)) | emulated (reviewed): devvm's forwarder over the VM's ssh, for the listed ports alone. smolvm forwards nothing itself but the VM's ssh ([details](smolvm.md#ports)) |
|
||||
| `ports-all` | every port forwarded, servers on the VM's loopback included | emulated (reviewed): the same forwarder, for whatever listens in the VM from port 1024 up, and never a port the host has ([details](lima.md#ports)) | emulated (reviewed): the same forwarder, for whatever listens in the VM from port 1024 up, and never a port the host has ([details](smolvm.md#ports)) |
|
||||
| `agent-forwarding` | ssh-agent forwarding, chosen when the VM is made | native | native |
|
||||
| `agent-toggle` | turning a VM's ssh-agent forwarding on or off later | native | emulated (reviewed): every VM is made forwarding, and each start gives it your agent, devvm's, or none, which is a path where no socket can be. devvm stops a VM that was started outside devvm ([details](smolvm.md#ssh-agent-forwarding)) |
|
||||
| `cpus` | a VM's CPUs | native | native |
|
||||
| `memory` | a VM's memory | native | native |
|
||||
| `disk` | a VM's disk size | native: it grows but never shrinks | native: it grows but never shrinks |
|
||||
| `docker-layer` | the [docker layer](../using/images.md#built-in-layers): Docker's engine running in the VM | native | native: devvm starts its daemon after each start |
|
||||
| `nix-layer` | the [nix layer](../using/images.md#nix): Nix's daemon and its store in the VM, with builds in Nix's sandbox | native ([details](images.md#the-nix-layer)) | native: devvm starts its daemon after each start |
|
||||
| `link` | links between VMs: a program in one VM reaches a port another VM publishes, by name | native: a link session of devvm's own over Lima's ssh, with remote forwards to `127.77.0.0/16` alone ([details](ports.md#links-between-vms)) | native: the same link session, over the VM's own ssh ([details](ports.md#links-between-vms)) |
|
||||
|
||||
The backends also differ in isolation, which [Backends](../backends/_index.md#comparing-the-backends) compares.
|
||||
| Feature | What it is | Lima |
|
||||
| --- | --- | --- |
|
||||
| `build-image` | build images from the layer and feature scripts | native |
|
||||
| `build-confinement` | builds reach the internet but not the host's loopback, or nothing | native: Seatbelt on macOS. On Linux, QEMU's `restrict=on` confines a build with no network, but a build with the internet reaches the host's loopback ([details](lima.md#confinement)) |
|
||||
| `from` | `base` from a container image (`--from`) | native: devvm converts the image to a disk |
|
||||
| `clone` | a project VM from an image | native: an APFS copy-on-write copy on macOS, and a qcow2 overlay on Linux ([details](lima.md#clones-and-overlays)) |
|
||||
| `project-mount` | the project folder, read-write | native: virtiofs on macOS, and 9p on Linux |
|
||||
| `agent-folders` | agents' host folders, read-only | native: read-only mounts, enforced by the host |
|
||||
| `tools-share` | the shared tools, read-only | native: a read-only mount, enforced by the host |
|
||||
| `egress-proxy` | network traffic only through devvm's proxy | native: Seatbelt on macOS, and on Linux QEMU's `restrict=on` with a `guestfwd` to the proxy ([details](lima.md#confinement)) |
|
||||
| `ssh` | ssh for editors | native: Lima's ssh forward and config |
|
||||
| `ports` | the listed ports forwarded to the host's loopback | emulated (reviewed): devvm's forwarder over Lima's ssh, for the listed ports alone, with Lima's own forwards off ([details](lima.md#ports)) |
|
||||
| `ports-all` | every port forwarded, servers on the VM's loopback included | emulated (reviewed): the same forwarder, for whatever listens in the VM from port 1024 up, and never a port the host has ([details](lima.md#ports)) |
|
||||
| `agent-forwarding` | ssh-agent forwarding, chosen when the VM is made | native |
|
||||
| `agent-toggle` | turning a VM's ssh-agent forwarding on or off later | native |
|
||||
| `cpus` | a VM's CPUs | native |
|
||||
| `memory` | a VM's memory | native |
|
||||
| `disk` | a VM's disk size | native: it grows but never shrinks |
|
||||
| `docker-layer` | the [docker layer](../using/images.md#built-in-layers): Docker's engine running in the VM | native |
|
||||
| `nix-layer` | the [nix layer](../using/images.md#nix): Nix's daemon and its store in the VM, with builds in Nix's sandbox | native ([details](images.md#the-nix-layer)) |
|
||||
| `link` | links between VMs: a program in one VM reaches a port another VM publishes, by name | native: a link session of devvm's own over Lima's ssh, with remote forwards to `127.77.0.0/16` alone ([details](ports.md#links-between-vms)) |
|
||||
|
||||
### What each backend emulates
|
||||
|
||||
On Lima, devvm emulates forwarding ports, both the listed ones and every one, through its forwarder, and the emulation is reviewed, so devvm forwards ports by the same rules on every backend ([port forwarding](ports.md)). Everything else on Lima is Lima's own.
|
||||
|
||||
The smolvm column is tested with smolvm 1.32.2 on an arm64 Mac, and Linux hosts are untested. On smolvm, devvm emulates network policy, ssh for editors, forwarding ports (the listed ones and every one) and turning agent forwarding on or off, and each of these emulations is reviewed.
|
||||
On Lima, devvm emulates forwarding ports, both the listed ones and every one, through its forwarder, and the emulation is reviewed ([port forwarding](ports.md)). Everything else on Lima is Lima's own.
|
||||
|
||||
## Missing and unreviewed features
|
||||
|
||||
|
||||
@@ -9,186 +9,49 @@ For contributors: why devvm is built the way it is, what was tried and dropped,
|
||||
|
||||
When devvm builds a backend feature from other parts of the backend, the feature is [emulated](backends.md#features), and it gets a note here before its review. The note says what the feature is built from, the guarantee it keeps, what could break it, and which end-to-end checks prove it. The threat check comes next, and only then is the feature marked reviewed. Every feature Lima has is native except its ports, which devvm's forwarder emulates ([below](#ports-on-lima)).
|
||||
|
||||
### Network policy on smolvm
|
||||
### ssh into VMs
|
||||
|
||||
**The guarantee:** as on Lima, a VM with network policy reaches nothing but its own proxy, even as root, and a refused DNS query never leaves the host, but for one narrow channel, a query for `devvm.invalid` (the DNS channel, under Not covered below). Reviewed: the threat check's findings are fixed or listed below, and the end-to-end checks prove the rest.
|
||||
**What it's built from**, all set by `Start` while the machine is stopped:
|
||||
ssh for editors is native on Lima, so it isn't an emulation, but its sessions keep a guarantee of devvm's own: ssh and editors reach a VM by name through the entries devvm writes ([security model](security.md#ssh-into-vms)), and a session gives the VM no way out it doesn't already have, with network policy nothing past its proxy, whatever the VM runs as sshd.
|
||||
|
||||
- **An allow list of the gateway alone** (`--reset-allow-list --allow-cidr 100.96.0.1/32`): smolvm refuses TCP to any other address, IPv6 included, and UDP but DNS. The gateway is every port of the host's loopback, so the allow list alone isn't enough.
|
||||
- **DNS closed** (`--allow-host-pattern devvm.invalid`): smolvm's resolver, which takes every DNS query on port 53 whatever its address (UDP or TCP), answers NXDOMAIN itself for any other name, without asking anyone. `--dns` would be simpler, but `machine update` can't change it.
|
||||
- **devvm's proxy as the decider** (`machine start --mediated-egress --egress-interceptor 127.0.0.1:PORT`, its token in `SMOLVM_INTERCEPTOR_TOKEN`): before smolvm connects anywhere, it sends the proxy's decider (`devvm _proxy -decider`, on a host loopback port of its own) the connection's destination and first bytes. The decider takes over only connections to the proxy's own address in the VM (`100.96.0.1:<proxy port>`): the same connection then carries it, and the proxy serves it as any other, password and policy included. It refuses every other connection the allow list lets through (another port of the host's), logged as `blocked` (`TCP`, refused). smolvm connects nowhere itself for a VM's TCP.
|
||||
- **The token**: 32 random bytes, new at each start, kept in the VM's state and a file of the proxy's (mode 600), never in a process's arguments, never in the VM. It goes one way only: smolvm sends it to the decider at the start of each connection, and the decider proves nothing back. So it protects the decider from others: a program on the host that connects to the decider's port without it gets no answer, and can't have the proxy take over a connection of its own as the VM's (the decider reads nothing past the token without it, and at most 8 KiB of first bytes with it). It doesn't protect smolvm from a fake decider (below). A proxy restarted while the VM runs gets the same port and token.
|
||||
- **Confined** compares the machine's `agent.pid` (its process and start time) with the one recorded after devvm's start through the decider, checks that process runs, and that the allow lists smolvm reports are still the ones above: smolvm changes them on a running machine (`smolvm machine update --allow-cidr`), which makes the VM `unenforced`, and its next launch stops it. A start without network policy removes the allow list and the decider requirement (`--net --reset-allow-list --no-egress-interceptor`).
|
||||
|
||||
**What it relies on:** smolvm's virtio-net gateway enforcing the allow list, the mediated-egress decision (protocol version 2) before any upstream connection and failing closed when the decider is gone or answers badly, its resolver's hostname filter, and the requirement it records: once a machine started through a decider, smolvm refuses a start without one (`smolvm machine start` by itself fails). None of it is in the VM, so root there can't change it.
|
||||
|
||||
**What could break it:** a smolvm release that changes the protocol, stops recording the requirement, or lets a connection through before the decision (each fails the end-to-end checks); a program on the host that takes the decider's port while the proxy is down: smolvm sends it the token and lets it decide. Protocol version 2 has a third verdict, `0`, allow direct, which a squatter could give, but smolvm refuses a direct connection to the host (`direct_target_policy`), and the allow list admits nothing else; what a squatter can do is take connections over (`2`) and carry them anywhere itself (checked: such a decider answers the probe), as on Lima a program that takes the proxy's port gets the VM's traffic. A decider that answers garbage, or nothing, refuses (checked). It starts before the VM, so it's down only while it's restarted (new rules, a new devvm) or once it fails; a start that finds a port taken, or fails, stops the VM (`net_proxy_down_stopped`), on Lima too, but whatever took the port meanwhile decided for it until then. Someone on the host who starts the machine with a decider of their own isn't confined: devvm reports it `unenforced` and stops it.
|
||||
|
||||
**Not covered:**
|
||||
|
||||
- smolvm's JSON (`machine ls`, `machine status`) shows only the allowed CIDRs and host patterns, not its UDP allows (`--allow-udp`), deny lists or egress rules (API only), and `--reset-allow-list` leaves UDP allows in place (`--remove-allow-udp` needs each one by name). Someone on the host who adds a UDP allow, live or not, lets the VM send UDP there, past the decider, and devvm can't see it (checked: one added live lets an NTP request out). Only the host's user can. A UDP allow of the gateway still doesn't reach the host's loopback.
|
||||
- ICMP to the gateway (ping) passes; to anywhere else it gets no answer (checked; smolvm's own network doesn't forward ICMP either, so that check has no control).
|
||||
- **A DNS channel:** a query for `devvm.invalid` itself is forwarded to smolvm's upstream resolver, by default the host's first nameserver, usually on the network. The name is fixed, but the VM chooses when to ask, the query type, the name's case and EDNS options: a narrow way out to whoever sees that resolver's traffic. It can't be closed from here: smolvm takes only valid DNS names as patterns and forwards every allowed one, `localhost` included (with a black-hole upstream, `devvm.invalid`, `localhost`, `localhost.localdomain` and `local` all waited on it), and the upstream is set only by `machine create --dns`, for every query, with policy or without. Closing it would take `--dns` at create pointing at a resolver devvm runs (port 53 on the host's loopback, which only root can take; `0.0.0.0:53` is open to users but to the network too), or a VM's network policy fixed when it's made.
|
||||
- The proxy's own limits ([Not covered](../safety/network.md#not-covered)). Linux hosts are untested.
|
||||
|
||||
**End-to-end checks** (`tests/e2e.sh --backend smolvm`):
|
||||
|
||||
- the VM runs behind its proxy and decider and passes the self-check; its allow list and DNS are as above; an allowed host works through the proxy, others get `403`;
|
||||
- direct connections fail even as root (an address, a port of an allowed host, IPv6, a service on the host's loopback through the gateway); on smolvm's own network the same probes get out, their control;
|
||||
- DNS fails at once. While the VM resolves names of its own (through its resolver, and straight to the gateway's resolver and `1.1.1.1` over UDP and TCP: A, TXT, ANY, AAAA, HTTPS, EDNS0, a name under `devvm.invalid`), smolvm's process has no flow beyond the host's loopback (nettop, macOS), and smolvm's own decision log (`egress-decisions.jsonl`) refuses every name; `DEVVM.INVALID`, sent too, is the channel's own name and is let through, as nothing but `devvm.invalid` is. nettop is blind to queries smolvm forwards under a hostname filter (it asks through the system's resolver), so the log is the detector, and a query for `devvm.invalid`, which it does forward, is the control that the log sees one. On smolvm's own network, nettop sees the probe's queries leave;
|
||||
- UDP and ICMP: datagrams to a host loopback listener through the gateway, to `1.1.1.1` on 443 and 123, and an NTP request reach nothing, and a ping to `1.1.1.1` gets no answer; a UDP allow added live lets the NTP request out, and on smolvm's own network nettop sees the datagrams leave (their controls);
|
||||
- the token is in no host process's arguments and nowhere in the VM, and the proxy's password in no host process's arguments; `devvm network log` shows the proxy's blocks and the refused connections to the host; `devvm network allow` and `rm` apply at once;
|
||||
- an allow list widened while the VM runs makes it `unenforced`, and devvm stops it, then starts it confined;
|
||||
- with the proxy gone, or a decider of nobody's that answers garbage, nothing or allow direct, nothing gets out (the host's loopback listener included), while one that takes connections over answers the probe (its control), and `smolvm machine start` refuses the machine; started with someone else's decider, devvm stops it; `devvm network off` and `on` switch it to smolvm's own network and back.
|
||||
|
||||
### ssh for editors on smolvm
|
||||
|
||||
**The guarantee:** as on Lima, ssh and editors reach a smolvm VM by name, that VM alone (host keys of its own, read through smolvm and pinned), only as the VM's user and only with that VM's own key; and an ssh session devvm's entry makes gives the VM no way out it doesn't already have (with network policy, nothing past its proxy), whatever the VM runs as sshd: the host's ssh asks for nothing that would carry it, and the entry pins the options that could. Reviewed, in two rounds: the threat check's findings are fixed or listed below (the entry's options, a key per VM, no host keys read before sshd runs, ports that never collide, an image without sshd), and the end-to-end checks prove the rest.
|
||||
**What it's built from:**
|
||||
|
||||
- **sshd in base:** `sshd.sh`, as root after base's scripts, installs `openssh-server` from the archive they left (Ubuntu's snapshot: from the live archive, before them, its systemd libraries were newer than the snapshot's packages layers install, Docker's, could match), keeps the snapshot's package lists for layers, and deletes the host keys its package made; `prepare.sh` sets the user's password to `*` (none matches; sshd without PAM refuses a locked `!` account's keys too). Both are in base's key.
|
||||
- **Only when asked for:** the caller sets `Confinement.SSH` at each start of a project VM when `Require` lets `ssh` through (always: it's reviewed); builds never ask. Without it the start removes the forward and runs no sshd, `SSH` answers `vm_no_ssh`, and the ssh config skips any backend whose `ssh` isn't usable (`Review.Allowed`).
|
||||
- **The forward:** `machine update -p PORT:22` while the machine is stopped. `PORT` is `Confinement.SSHPort`, the `ssh_port` devvm records in the VM's state with or without network policy. Without one, it's the port the machine had while that's free on `127.0.0.1` and `::1`, else a new one. It's never one of the VM's listed ports: `ssh_port` avoids every VM's listed ports and is picked again when it's one of the VM's, and the backend refuses one that is anyway (`smolvm_ssh_port_forwarded`). smolvm binds it on the host's loopback alone, and its forwards reach only servers on all addresses, so sshd listens on `0.0.0.0:22` (IPv4). It's the only forward of smolvm's a VM has, because devvm's forwarder forwards the VM's own ports ([ports](#ports-on-smolvm)).
|
||||
- **sshd, after each start** (`services.sh`, as root): every host key deleted and a new ed25519 one made, so no two VMs from one pack share one, nor a VM's starts; devvm's public key as the only authorized key (`/etc/devvm/ssh/authorized_keys`, root's); a config of devvm's own (`/etc/devvm/ssh/sshd_config`, mode 600, `sshd -f`, checked with `sshd -t` first), whatever the image's says: `AllowUsers` the VM's user, `PermitRootLogin no`, `AuthenticationMethods publickey`, passwords and keyboard-interactive off, `AllowTcpForwarding all`, `AllowStreamLocalForwarding local`, `GatewayPorts clientspecified`, `PermitListen 127.77.*:*`, `X11Forwarding no`, `PermitTunnel no`, `PermitUserEnvironment no`, `AllowAgentForwarding yes`; it listens on IPv4 alone (`ListenAddress 0.0.0.0:22`) and connects local forwards to IPv4 or IPv6 (`AddressFamily any`, for [the forwarder](#ports-on-smolvm)'s servers on `::1`). A failure stops the VM, but an image without sshd (made before devvm installed one; asked first, with a probe of its own, so no other failure reads as it) starts without ssh, warned (`vm_no_sshd`; a VM made after `devvm rebuild` has it). The record says the start's sshd runs (`ssh_up`, cleared before each start, set once `services.sh` is done), and `SSH` answers only then: a devvm that runs meanwhile can't read, and pin, the host keys this start is about to replace.
|
||||
- **The sessions' environment:** sshd on its own config runs without PAM, so `SetEnv` gives sessions `/etc/environment` (`BASH_ENV`) and the variables `Start` names (the proxy's, `NO_PROXY`, the CA files'), whose values `services.sh` reads from its own environment: the proxy file's (`--secret-file`) and the machine's, never in arguments. Login shells also read `/etc/profile.d`, as devvm's do.
|
||||
- **The VM's key:** ed25519, made in Go in OpenSSH's format at the VM's first start with ssh, `key` in the VM's backend folder, `~/.local/share/devvm/vms/<hash>/backend/` (mode 600, one file written whole; its public half is read back from it, never kept apart), deleted with the VM. Its public half, passed to `services.sh`, is that VM's only authorized key: one VM's key logs in to no other. `SSH` returns `127.0.0.1`, the port, the user, and `IdentityFile` with `IdentitiesOnly yes` and `PreferredAuthentications publickey`: the user's agent keys aren't offered to the VM.
|
||||
- **Pinning** is the shared code's, as on Lima: a VM's keys are forgotten before each start and read after it with `cat /etc/ssh/ssh_host_*_key.pub` through `Exec` (smolvm's `machine exec`, which reaches the VM itself, not over the network), and entries check them (`HostKeyAlias`, `StrictHostKeyChecking yes`).
|
||||
|
||||
**What keeps a session from carrying the VM out.** An ssh session can carry the VM's traffic only through channels the host's ssh asks for: remote forwards (`-R`, `RemoteForward`, a remote SOCKS forward), X11, a tunnel and the agent; OpenSSH's client refuses a channel the server opens unasked. Root in the VM runs whatever sshd it likes, so the guarantee is the host's ssh's: devvm's entry (first in `~/.ssh/config`, so its options win over a `Host *`) sets `ForwardX11 no`, `ForwardX11Trusted no`, `Tunnel no`, `PermitRemoteOpen none` (so devvm needs OpenSSH 8.7 or newer; no `IgnoreUnknown` for older ones, as its first value wins and would replace a user's `Host *` one, such as macOS's for `UseKeychain`), `ForwardAgent` as the agent choice the VM's current start was made with says ([below](#ssh-agent-toggling-on-smolvm)), `AddKeysToAgent no` (no key of the host's lands in an agent the session forwards), `ProxyJump none` and `ProxyCommand none` (no hop through something else), `UpdateHostKeys no` (the VM can't add host keys; devvm reads them itself) and `HashKnownHosts no`. Shared with Lima. A `RemoteForward` can't be turned off without refusing `ssh -R` on the command line too, so it isn't (Not covered). VS Code's Remote-SSH uses local and dynamic forwards (`-L`, `-D`) and is unaffected. Then sshd's own settings, a defence for an honest VM, and the same on Lima (`assets/layers/base.sh`, `/etc/ssh/sshd_config.d/00-devvm.conf`, first so it wins; Lima's own forwards are local; it applies only where the image's `sshd_config` includes `sshd_config.d`, as Ubuntu's and Debian's do, so for some `--from` images not at all, which only an honest VM's defence loses):
|
||||
**What keeps a session from carrying the VM out.** An ssh session can carry the VM's traffic only through channels the host's ssh asks for: remote forwards (`-R`, `RemoteForward`, a remote SOCKS forward), X11, a tunnel and the agent; OpenSSH's client refuses a channel the server opens unasked. Root in the VM runs whatever sshd it likes, so the guarantee is the host's ssh's: devvm's entry (first in `~/.ssh/config`, so its options win over a `Host *`) sets `ForwardX11 no`, `ForwardX11Trusted no`, `Tunnel no`, `PermitRemoteOpen none` (so devvm needs OpenSSH 8.7 or newer; no `IgnoreUnknown` for older ones, as its first value wins and would replace a user's `Host *` one, such as macOS's for `UseKeychain`), `ForwardAgent` as the agent choice the VM's current start was made with says, `AddKeysToAgent no` (no key of the host's lands in an agent the session forwards), `ProxyJump none` and `ProxyCommand none` (no hop through something else), `UpdateHostKeys no` (the VM can't add host keys; devvm reads them itself) and `HashKnownHosts no`. A `RemoteForward` can't be turned off without refusing `ssh -R` on the command line too, so it isn't (Not covered). VS Code's Remote-SSH uses local and dynamic forwards (`-L`, `-D`) and is unaffected. Then sshd's own settings, a defence for an honest VM (`assets/layers/base.sh`, `/etc/ssh/sshd_config.d/00-devvm.conf`, first so it wins; Lima's own forwards are local; it applies only where the image's `sshd_config` includes `sshd_config.d`, as Ubuntu's and Debian's do, so for some `--from` images not at all, which only an honest VM's defence loses):
|
||||
|
||||
- **Local forwarding** (`-L`, `-D`, `-W`) is allowed: the VM itself connects, from its own network, which network policy confines like any other connection of the VM's (checked). VS Code's Remote-SSH reaches its server this way.
|
||||
- **Remote forwards bind only `127.77.0.0/16`,** the range devvm keeps for links between VMs, and remote socket forwards are refused. A remote forward makes the host connect on the VM's behalf, so one the host's ssh asked for by mistake could reach anything the host reaches, its loopback services and sockets (`docker.sock`, agents) included, around network policy. `GatewayPorts clientspecified` binds the address a request names, and `PermitListen 127.77.*:*` matches that address as text, so a request for `localhost` (ssh's default), `127.0.0.1`, `0.0.0.0` or `::1` is refused. Only devvm on the host asks for a forward in that range, always by number. X11 and tunnels are refused too.
|
||||
- **Agent forwarding** is allowed: the entry decides it from the SSH agent choice the VM's current start was made with (`ForwardAgent`, devvm's own agent too), as on Lima; refusing it would break `devvm ssh-agent on` in editors.
|
||||
- **Agent forwarding** is allowed: the entry decides it from the SSH agent choice the VM's current start was made with (`ForwardAgent`, devvm's own agent too); refusing it would break `devvm ssh-agent on` in editors.
|
||||
|
||||
These settings guard against the host's ssh asking for a forward that devvm's entry doesn't pin (a `RemoteForward` under `Host *`, `ssh -R`), and only while root in the VM leaves sshd as it is. They're a safeguard for an honest VM, and the boundary is the host's ssh, which accepts a channel only for a forward it asked for.
|
||||
|
||||
**What it relies on:** smolvm binding forwards on the host's loopback alone and carrying them under mediated egress, which decides only the VM's own connections; `machine exec` reaching the VM itself; OpenSSH's client refusing unrequested channels; devvm's `Include` line first in `~/.ssh/config`, so its entries' options win.
|
||||
**What it relies on:** OpenSSH's client refusing unrequested channels, and devvm's `Include` line first in `~/.ssh/config`, so its entries' options win.
|
||||
|
||||
**What could break it:** a smolvm release that binds forwards beyond the loopback (the network could reach sshd: still key-only); host ssh settings that come before devvm's entries (as on Lima); a program on the host that takes the port while the VM is stopped (there's no entry for a stopped VM, a start whose port is taken fails, and the pinned host key refuses any other server).
|
||||
**What could break it:** host ssh settings that come before devvm's entries.
|
||||
|
||||
**Not covered:**
|
||||
|
||||
- A remote forward you ask for (`ssh -R`, a `RemoteForward` of yours) into a VM whose root allowed it, or on an address in `127.77.0.0/16`, which sshd allows for anyone it lets in: sshd's settings are the VM's to change, and the entry can't refuse it. Don't forward into a VM you don't trust.
|
||||
- **DNS detection:** a machine with any port forward of smolvm's (its ssh's) runs on smolvm's virtio-net network, as one with an allow list always does; without one, on TSI, where the VM asks this machine's resolver itself (checked: `nameserver 10.0.0.1` vs `100.96.0.1`, and a TSI machine can't have a forward). On virtio-net, smolvm's resolver asks through the system's resolver, which nettop can't tie to the VM, so smolvm's decision log, with `devvm.invalid` as its control, is network policy's only DNS detector there, with or without a forward. nettop's DNS control (the queries seen to leave) is a TSI machine's, and every devvm VM has a forward now, so e2e runs it on a machine of its own from base's pack, without one. (The no-leak check ran both with and without a forward before ssh was reviewed, and held both ways; smolvm writes its decision log only with a decider, so a machine of e2e's own can't repeat the one without.) A host-side detector for virtio-net would take root (a packet capture) or a canary zone ([manual checks](../contributing/testing.md#manual-checks)).
|
||||
- Sessions see the proxy's password, as devvm's own shells do; what VS Code relays ([VS Code](../using/ssh.md#vs-code)) is as on Lima.
|
||||
- Other users on the host reach the port (the host's loopback): they get the host key, and no login.
|
||||
- Linux hosts are untested.
|
||||
|
||||
**End-to-end checks** (`tests/e2e.sh --backend smolvm`):
|
||||
|
||||
- an entry by the folder's name, its port on the host's loopback alone; the machine's process listens on its ssh forward's alone, with ports listed or not; the net backend pinned: virtio-net (`nameserver 100.96.0.1`) with a forward, with network policy or without, TSI (this machine's resolver) on a machine without one;
|
||||
- an image without sshd (root moved it away): the next start warns `vm_no_sshd` and runs, without an entry, `devvm host` says so; sshd back, a start has ssh again;
|
||||
- the pinned host key is the VM's own, ed25519, its only one; a changed one is refused; a restart makes a new one, pinned again; another VM from the same image has its own, and its own port;
|
||||
- `ssh` by name reaches the VM's user with `BASH_ENV`; the agent isn't forwarded whatever `Host *` says; passwords and keyboard-interactive are refused, publickey alone offered; another key, `root` and another user are refused, devvm's key is the control;
|
||||
- a remote forward binds on `127.77.0.250` (the control) and nowhere else: ssh's default (`localhost`), `127.0.0.1`, `0.0.0.0`, `::1`, `localhost` and another range are refused, and so is a remote forward of the host's agent socket, while a local forward works; `sshd -T` shows the settings above, and the config is root's alone, mode 600;
|
||||
- after the setup, ports below 1024 are open to the VM's user (`ip_unprivileged_port_start` is `0`), and a remote forward binds `127.77.0.250:80`;
|
||||
- a hostile sshd (root rewrites its config to allow remote forwarding, X11, tunnels, and restarts it), reached through a `Host *` that asks for X11 and to add keys to the agent: no display in the session and no key in the agent; the same asked for on the command line (`-X`, `-o AddKeysToAgent=yes`) gets both (the controls), and `ssh -R` then works (what isn't covered); `ssh -A` forwards the agent (the agent-off check's control);
|
||||
- a recorded port squatted while the VM is stopped: its next start forwards another, and ssh reaches it; another VM's key doesn't log in to it;
|
||||
- `devvm host`, `devvm code` (a stub `code`), `devvm stop` (no entry, nothing on the port), `rm` (entry and keys gone);
|
||||
- `--clone`: the clone pushed in over ssh, every branch, nothing of the folder mounted; fetching the VM's commit and pushing a branch through devvm's ssh config; `rm -f` keeping the fetched work;
|
||||
- with network policy: ssh on the VM's `ssh_port`, sessions (a login's or not) with the proxy's settings, an allowed host through the proxy; a local forward to `1.1.1.1:80` or a service on the host's loopback gets nothing back, a remote forward on the VM's loopback is refused, a direct connection from a session fails; after `devvm network off`, the same local forward gets an answer (the control); network policy's DNS no-leak check runs with the forward (DNS detection above).
|
||||
|
||||
### Ports on smolvm
|
||||
|
||||
**The guarantee:** when a VM forwards every port, each TCP port from 1024 up that a server in it listens on, on its loopback or on all its addresses, is forwarded to the same port on the host's loopback, and only to its loopback. When a VM lists its ports, only those are forwarded, however many it lists, by the same rules. The forwarder never takes a port that a program on the host has on any address when the forward is made, or a port devvm records for a VM. Forwarding gives the VM no way out that it doesn't already have, because every connection starts on the host, so with network policy the VM still reaches nothing past its proxy. The emulation is reviewed, with the threat check's findings fixed or listed below, which is why the host key read is capped, reports are paced and the log is limited, and the end-to-end checks prove the rest. Listed ports use the same forwarder with `-only`, as on [Lima](#ports-on-lima), so the threat check's findings for every port hold for them, and the leads that are their own are in the threat check for listed ports below.
|
||||
|
||||
**What it's built from:**
|
||||
|
||||
- **None of smolvm's forwards.** devvm makes a VM with no `-p` but its ssh's, whatever ports it forwards, and `SetPorts` changes only devvm's record of them, then starts a running VM's forwarder again with them. smolvm's own forwards would need each port at create or update while the machine is stopped, allow at most 64 of them, reach only servers on all addresses, and share a port that a host program has on every address (`SO_REUSEADDR`), taking that program's loopback connections.
|
||||
- **Only when allowed.** The caller requires `ports` or `ports-all` with `Review.Require` when the VM is made or its ports are set, and warns when it lets them through. It checks again at each start with `Review.Allowed`, and refuses the start otherwise, so a VM made while the emulation was let through doesn't start once it isn't. Because the emulation is reviewed, it's always let through. The backend then runs a forwarder at each start of a VM whose record says every port (`ports_all`) or lists ports (`listed_ports`).
|
||||
- **A forwarder per VM, on the host.** The forwarder is `vmssh.Forwarder`, which [Lima's ports](#ports-on-lima) also use, and on smolvm it runs as `devvm _smolvm-ports`. `Start` starts it detached once `services.sh` has run the VM's sshd ([ssh](#ssh-for-editors-on-smolvm)), and `SetPorts` starts it again on a running VM, each after stopping any forwarder the VM had, which ends the connections open through it. devvm finds that one by its pid file, which it checks against the process's arguments, as it does for the proxy. It sends that forwarder SIGTERM and kills it if it hasn't ended within 2 s, so its ports are free before devvm asks which listed ports a host program has. devvm holds a lock of the VM's own (`ports.lock`, beside its pid file `ports.pid` in the VM's backend folder) from stopping the old forwarder until the new one has started, so two devvm runs at once, such as a start and `devvm ports`, leave one forwarder, the one its pid file names. A machine started outside devvm since devvm's last start has no sshd of devvm's, so `SetPorts` starts no forwarder for it and devvm warns with `ports_no_ssh`. `Start` waits up to 10 s for the forwarder to say it forwards while it runs. The forwarder says so in a status file of its own beside its pid file (`ports.status`), which holds its pid and which devvm removes before each start. If it doesn't, devvm warns with `ports_forward_failed`, naming its log, and leaves it to keep trying while the VM runs on. A VM without ssh forwards nothing, and devvm warns with `ports_no_ssh`. The forwarder ends when the machine's process does. It follows the same lifeline as the proxy, `agent.pid`, and exits once that process is gone or a new start has changed the file's contents. `stop` and `Delete` stop it first.
|
||||
- **Reaching the VM.** The forwarder makes one ssh connection, a master (`ssh -F none -M -S <socket>`), to the port on the host's loopback that the VM's sshd is forwarded from. It logs in as the VM's user with the VM's own key alone (`IdentitiesOnly`, `IdentityAgent=none`). It reads the VM's host key through smolvm each time it starts, after a start of the VM or a change of its ports, as root, with `machine exec … cat /etc/ssh/ssh_host_ed25519_key.pub`. Because the VM decides what that prints, devvm reads at most 64 KiB of it, for at most 30 s. The key goes into a known_hosts file of the forwarder's own and is pinned with `HostKeyAlias` and `StrictHostKeyChecking yes`. The master reads none of the user's configuration and forwards nothing either way, with `ClearAllForwardings`, `PermitRemoteOpen none`, `ProxyCommand none`, and no agent, X11 or tunnel. Its control socket is in `~/.local/share/devvm/run` (mode 700) and is named by a hash of the VM's name, because a socket's path is at most 104 characters. When the connection is lost, the forwarder closes its forwards and makes the connection again every 2 s while the lifeline holds.
|
||||
- **What listens.** The master's session runs `ports.sh` as the VM's user (`sh -s`). It prints the local addresses of the VM's listening TCP sockets, which are the state `0A` lines of `/proc/net/tcp` and `tcp6`, whenever they change and every 10 s regardless, so it ends soon after the connection does. The forwarder treats the report as untrusted. A line over 128 bytes or a report over 4096 lines ends the connection, and anything that isn't a hex address and port is skipped. Reports are applied at least 500 ms apart, and one that comes sooner waits, holding up the VM's ssh channel with it, so the VM can't make the forwarder bind, dial and read devvm's state at its own pace. The VM can make the forwarder write to its log, with ports coming and going and with the session's stderr, so the log takes 200 writes at once and then one every 10 s. Each write is at most 512 bytes, without control characters but newlines and tabs, C1 included, and a start empties the log once it's over 1 MiB. A forwarded port's connections go to `127.0.0.1` for a server on all IPv4 addresses or on that address, and to `::1` for a server on all IPv6 addresses or on that address. A server on another `127.x` address alone gets its connections there. Servers on other addresses alone aren't forwarded.
|
||||
- **Which ports.** With every port, the forwarder takes ports from 1024 up, because the ports below are the host's system services. With listed ports, it takes those alone (`-only`), a listed port below 1024 included, because the user asked for it, and a bind the host refuses is logged. The listed ports are the record's less those `Confinement.Free` leaves out, which are the ports a program on the host has when the forwarder starts, as on every backend, with a `ports_taken` warning. `Free` is asked once the VM's old forwarder has stopped, so the VM's own forwards don't read as taken, and when no port is left, no forwarder runs. Either way the forwarder takes at most 256 ports at once, and it never takes a reserved port. The reserved ports are the VM's own ssh, proxy and decider ports, and every VM's ssh, proxy and decider ports and other VMs' listed ports as their state records them (`netpolicy.UsedPorts`). The forwarder reads them again each time it would take a port, and while it can't read them, it takes no new port. A smolvm VM without network policy keeps its ssh port only in its smolvm record. smolvm holds that port while the VM runs, but while the VM is stopped another VM's forwarder can take it, and the VM's next start then forwards ssh from another port. The pinned host key refuses any other server on the old one. A port the forwarder couldn't take is tried again only once the VM's server on it goes and comes back.
|
||||
- **Listening.** The forwarder listens on `127.0.0.1` and `::1`, or on IPv4 alone on a host without IPv6. It binds without `SO_REUSEADDR` (`platform.ListenExclusive`). With that option, which Go and smolvm set, macOS lets a socket take `127.0.0.1:PORT` while a program has `*:PORT`, and that program's loopback connections go with it. Without the option, the bind is refused when another program has the port on any address. This was checked on macOS for a program on `0.0.0.0`, on `::` (IPv4 and IPv6 at once, as Node's and Go's servers listen), on IPv6 alone and on `127.0.0.1`, each with and without `SO_REUSEADDR` of its own. A port held only by ended connections (`TIME_WAIT`, with nothing answering on it) is taken as usual, so a server that restarts gets its forward back. When a bind is refused, the forwarder dials the port and takes it only if the dial is refused. A full backlog times out, which counts as taken. A port the forwarder took on `127.0.0.1` but finds in use on `::1` is given up, so `localhost` never reaches two programs. On Linux, `SO_REUSEADDR` stays on. Linux refuses that bind with the option too while another socket listens on the port, and without it, the forwarder's own ended connections (`TIME_WAIT`) would keep anyone from listening on the port for a minute, its next forwarder included.
|
||||
- **Each connection.** Each forwarded connection is a channel of the master's (`ssh -S <socket> -W HOST:PORT`), with one process per connection and at most 256 at once. The VM's sshd opens it to the VM's own loopback from inside the VM, so sshd connects over IPv4 or IPv6 (`AddressFamily any`) while still listening on IPv4 alone. The channel's ssh has the master's options. If the master is gone, ssh connects on its own, and it then reaches the VM's sshd the same way, never the host's.
|
||||
|
||||
**What keeps a forward from carrying the VM out.** Every connection starts on the host. A program connects to the forwarder's port, and the forwarder asks the VM's sshd to connect to the VM's loopback. The VM opens nothing to the host through the forwarder, because the master asks for no remote forward, agent, X11 or tunnel, and OpenSSH's client refuses a channel that the server opens unasked, whatever sshd root in the VM runs. The only remote forwards devvm asks a VM for are a client's links, on a link session that is a connection of its own, never the forwarder's master ([links](#links-between-vms)). What the VM sends back goes to the program that connected, as with any forward. The VM's own connections, including sshd's to its loopback, belong to the VM's own network, which network policy confines as usual. The forwarder never takes the VM's proxy or decider port, so while the proxy is gone, a server in the VM can't take the place of the decider smolvm asks, or of another VM's decider while that one is down.
|
||||
|
||||
**What it relies on:** the VM's sshd and its pinned host key, which come from the [ssh](#ssh-for-editors-on-smolvm) emulation. It also relies on OpenSSH's client refusing unrequested channels and honoring `-F none`, on smolvm binding the ssh forward on the host's loopback alone, on the kernel refusing a bind without `SO_REUSEADDR` where another socket has the port (checked on macOS), and on devvm's state listing every VM's ports.
|
||||
|
||||
**What could break it:** a smolvm release that binds the ssh forward beyond the loopback, which still lets in only the VM's key. Another is devvm's state being lost or unreadable for a VM whose proxy port is then free, which the forwarder handles by forwarding no new port while it can't read the state.
|
||||
|
||||
**Threat check for listed ports** (the security-audit skill, its local IPC companion). The forwarder and its transport are the ones checked for every port, so these leads are what listed ports add, each confirmed or ruled out:
|
||||
|
||||
- **A port the VM chooses:** ruled out. `-only` comes from devvm's record for the VM, less what `Confinement.Free` leaves out, both on the host, and the VM's reports can't add to it. A listed port is forwarded only while a server in the VM listens on it, as with every port.
|
||||
- **smolvm's own forwards:** ruled out. devvm makes and updates a machine with no `-p` but its ssh's, so a listed port is never one of smolvm's, which would share a host program's port (`SO_REUSEADDR`). The end-to-end checks look at the machine's process, which listens on its ssh forward alone, with listed ports and with network policy.
|
||||
- **A listed port that is the VM's ssh forward:** ruled out. The ssh forward's host port is never one of the VM's listed ports. A port the VM had is given up when it's listed, the VM's `ssh_port` is picked again when it's listed, and the backend refuses one that's listed anyway (`smolvm_ssh_port_forwarded`). The forwarder also reserves the ssh port, which smolvm holds while the VM runs.
|
||||
- **Port 22 listed:** ruled out as a collision. Port 22 in the VM is its sshd, and the ssh forward comes from another host port, so a listed 22 forwards the VM's sshd to the host's port 22 as it would forward any server. The VM's sshd still takes only the VM's own key, as the VM's user. A host whose own sshd has port 22 keeps it, with a `ports_taken` warning. The end-to-end checks list 22 with network policy, and ssh by name still reaches the VM from its own port.
|
||||
- **A listed proxy or decider port:** ruled out. The forwarder reserves the VM's own proxy and decider ports whether or not they're listed, and every other VM's as well.
|
||||
- **A listed port below 1024:** taken because the user asked for it. A host service that has the port keeps it, and a bind the host refuses is logged. One that isn't running yet is under **Not covered**.
|
||||
- **More ports than smolvm forwards:** ruled out. smolvm's limit of 64 forwards doesn't apply because smolvm forwards none of them, and the forwarder takes at most 256 at once.
|
||||
- **A forwarder left behind:** ruled out. `stop` and `Delete` stop it, `Delete` removes its files, and a start or change whose listed ports are all taken runs none. Two devvm runs that start a VM's forwarder at once take turns on the VM's lock, so the second stops the first one's forwarder, and neither leaves one that its pid file doesn't name, which nothing would stop.
|
||||
- **Network policy:** ruled out. Listed ports take fewer ports than every port, never more, and every connection still starts on the host. The end-to-end checks prove that direct connections fail with listed ports too.
|
||||
|
||||
**Not covered:**
|
||||
|
||||
- A VM can take a free port from 1024 up, or a listed one, on the host's loopback that a program there expects to be its own, such as one that isn't running yet or is restarting. What the VM serves there reaches whatever connects, so a page it serves to the user's browser can reach the internet from the host, past network policy.
|
||||
- A host program that starts on a port while the VM has it forwarded still binds it when it listens on all addresses with `SO_REUSEADDR`, as most servers do (checked on macOS). Its loopback connections then reach the VM, because the forward's address is the narrower one. A program that binds without `SO_REUSEADDR` is refused.
|
||||
- The VM can make the forwarder dial a host loopback port that's in use and then close the connection at once without sending anything, because that's how the forwarder checks for a port held only by ended connections. This happens at most once per port every second, as the VM's listener on the port goes and comes back.
|
||||
- Servers only on the VM's other addresses, such as its network address or a container's, aren't forwarded.
|
||||
- Other users on the host reach the forwards, because they're on the host's loopback.
|
||||
- UDP isn't forwarded on any backend. [Ports](../using/ports-size.md#ports) shows how to tunnel it over TCP.
|
||||
- A server that keeps a port while its forward couldn't be made, because the host had the port, isn't forwarded until it stops and starts again.
|
||||
- Linux hosts are untested.
|
||||
|
||||
**End-to-end checks** (`tests/e2e.sh --backend smolvm`):
|
||||
|
||||
- The machine's process listens on its ssh forward alone. The forwarder's ssh master reads no config, offers the VM's key alone with its host key pinned, and asks for no forwarding.
|
||||
- Servers on the VM's `127.0.0.1`, on `::1`, on all IPv4 addresses and on all addresses each answer at the host's `127.0.0.1` and `::1`, and the forwarder listens on the host's loopback alone.
|
||||
- A port that a host program has on every address stays the host program's, and the VM's server on it isn't forwarded. A port below 1024 isn't forwarded. The host program also keeps its port when it's on the host's `127.0.0.1` alone, on its `::1` alone (so `localhost` never reaches two programs), or on `::`, which is IPv4 and IPv6 at once. A server on the VM's own network address alone isn't forwarded, and neither is a port another VM's state lists while it's free, while a loopback server is forwarded as the control. A server that stops loses its forward, and the others stay.
|
||||
- `devvm stop` stops the forwarder and closes its ports. A new start has a new forwarder, which forwards a server started then, and `rm` deletes the forwarder and its files.
|
||||
- With listed ports, the machine's process still listens on its ssh forward alone, and the forwarder runs with the listed ports alone (`-only`). A listed port's server on all addresses, and one on the VM's loopback alone, each answer at the host's loopback, while an unlisted port's server on the VM's loopback doesn't. A listed port that a host program has on every address is left out with a `ports_taken` warning, its localhost connections stay the host program's while a listed port's server is forwarded as the control, and once the program is gone the next start forwards the port again.
|
||||
- On a running VM, a port that `devvm ports add` lists has its server reach the host at once, and once `devvm ports rm` takes it out, it doesn't. The machine's process is the same throughout, so the VM never restarted.
|
||||
- With network policy, the self-check passes and a server's port is forwarded, while direct connections still fail, even as root. With the proxy and decider gone and the VM listening on their ports, neither port is forwarded, while a port of the VM's own is forwarded as the control, and the next devvm starts the proxy on those ports again. With network policy and listed ports, 22 among them, the self-check passes, the machine's process listens on its ssh forward alone, which isn't port 22, and ssh by name reaches the VM. The forwarder runs with the listed ports alone, a listed port's server answers while an unlisted one's doesn't, and direct connections still fail.
|
||||
|
||||
### SSH agent toggling on smolvm
|
||||
|
||||
**The guarantee:** as on Lima, `devvm ssh-agent on`, `devvm` or `off` changes an existing VM's agent from its next start, and every start devvm makes (a launch, `restart`, an export's, `rm`'s check of a `--clone` VM) gives the VM only the agent its choice names: with `devvm`, devvm's own and never yours; with `off`, no agent at all, so the VM, root included, lists no keys, adds none and signs nothing, and reaches no agent of anyone's through smolvm's. A VM started some other way, which may have an agent devvm didn't choose, is stopped when devvm next finds it running. Reviewed: the threat check's one finding, a VM you start yourself, is fixed that way (the lifeline check below); the rest is listed below, and the end-to-end checks prove it.
|
||||
**What it's built from:**
|
||||
|
||||
- **Forwarding from the start:** smolvm sets forwarding only at `machine create --ssh-agent` (`machine update` has no option for it). A VM made while `agent-toggle` is let through (`VMSpec.AgentToggle`, from `Review.Require`, warned when unreviewed) is made with it whatever its choice, and its state records that it relies on the emulation (`agent_toggle=on`). The backend's record keeps both: made forwarding (`forwarding`), and the choice being none (`agent_off`), which `SetAgentForwarding` sets on a stopped VM; `Inspect` reports forwarding only when made so and not off.
|
||||
- **The agent, at each start:** smolvm's process reads `SSH_AUTH_SOCK` when the machine starts and connects to that path again for each of the VM's connections to `/tmp/ssh-agent.sock` (checked: a socket made at the path after the start is reached, a missing one gives the VM `communication with agent failed`, and a start without `SSH_AUTH_SOCK` fails). `Start` sets it alone: none for one made without forwarding; `/dev/null/devvm-no-agent` when the record or the start's `Confinement.NoAgent` says none (either is enough, so a start that skips the launch's `SetAgentForwarding`, as an export's does, still gives none); else `Confinement.AgentSocket` (devvm's own); else devvm's own `SSH_AUTH_SOCK` (yours); with none, `smolvm_no_agent` before anything changes. Your agent or devvm's is chosen from the VM's state alone (the record keeps only `agent_off`), and a record and state that disagree, as a choice changed while the VM ran leaves them, give none. Every other smolvm command devvm runs gets no `SSH_AUTH_SOCK`, and `machine exec` doesn't read it anyway (checked: an exec with your agent gives the VM none).
|
||||
- **None is a path, not an agent:** `/dev/null` is a device, not a folder, so nothing, root included, can make a socket below it, and no process listens for it. An empty agent of devvm's would hold nothing too, but every VM set to none would share it: a VM could add a key there for another to use, lock it, or have devvm's process sign for keys it put in. With a path, there's nothing to add to, sign with, or share.
|
||||
- **The lifeline check:** after each start, `Start` records the machine's lifeline (`agent.pid`: its process and start time) in the record (`started`; with network policy, `confined` too). `AgentUnchosen` (`backend.AgentStarter`, which Lima doesn't implement: its agent is the VM's config) says a running VM made forwarding may have an agent devvm didn't choose when the lifeline differs or its process is gone. A launch (devvm, `host`, `code`, after network policy's self-check, which says more for a VM with it) and an export's or `rm`'s start of a VM it finds running stop it then (`agent_unchosen_stop`, stopped even when interrupted), unless its choice is `on`: your agent is what it'd get anyway. The next devvm starts it as chosen.
|
||||
- **The entry and devvm's connections follow the start,** as on every backend: a choice changed while the VM runs reaches neither until its next start, as with smolvm's own agent. Here a start is told apart by its lifeline.
|
||||
- **Only when allowed:** a VM made ready for it (`agent_toggle=on`) doesn't start once the toggle isn't let through (`Review.Allowed`, else the refusal), as with every port (it always is: it's reviewed). One made without forwarding (while the toggle wasn't let through) is refused when turned on (`agent_fixed`), before its state changes.
|
||||
|
||||
**What it relies on:** smolvm reading `SSH_AUTH_SOCK` only at `machine start` and keeping the path for that run, its host side connecting to that path and nothing else, whatever the VM sends; `machine exec` not starting a stopped machine (checked: it fails); the kernel refusing a path below a device; smolvm writing a new `agent.pid` at each start, which the VM can't write; devvm's state and records being on the host, out of the VM's reach (`~/.local/share/devvm`, never mounted).
|
||||
|
||||
**What could break it:** a smolvm release that reads the agent from somewhere else (its own config, the environment of a later command) or falls back to a default socket when the path fails (the off checks fail: they need the VM's agent to be unreachable, not empty); one that refuses a start whose path doesn't exist fails closed (the start fails). A devvm agent that ends while the VM runs leaves a VM set to `devvm` with no agent, never yours (smolvm connects to its path alone).
|
||||
|
||||
**Not covered:**
|
||||
|
||||
- **Starting the VM yourself, until devvm next looks:** `smolvm machine start --name devvm-…` from your shell (or any smolvm command of yours that starts it) gives a VM made with forwarding the agent your shell names, whatever its choice (checked), and it keeps it until devvm, `host`, `code`, an export or `rm` finds it running and stops it; `devvm ls`, a shell or editor you opened before, or nothing at all don't. Only you (or a program of yours on the host) can do it, not the VM.
|
||||
- The VM has smolvm's agent socket while it runs, and an agent it's given is reachable for that whole time, not only while you're connected (smolvm's native forwarding, with `on` or `devvm`). With `devvm`, the VM can add keys of its own to devvm's agent, remove or lock its keys, as with any forwarded agent; every VM set to `devvm` shares it.
|
||||
- Linux hosts are untested.
|
||||
|
||||
**End-to-end checks** (`tests/e2e.sh --backend smolvm`; your agent is a throwaway one of e2e's, devvm's has a throwaway key; every look into the VM is a `machine exec` run with your agent):
|
||||
|
||||
- every new VM is made forwarding, recorded, and given none (the mounts VM too, made from a shell without an agent);
|
||||
- off, devvm run with your agent: root in the VM reaches no agent (`ssh-add -l` can't talk to one, rather than finding it empty) and can't add a key, your agent and devvm's unchanged; devvm's shell lists none;
|
||||
- `devvm ssh-agent devvm` while it runs changes nothing until a restart, `ssh` by name after a launch included, then the VM and `ssh` by name list devvm's key alone; with devvm's agent ended, none, never yours; `on`, then yours alone, and root can add a key to it (the add check's control); `off` while it runs, stopped, then started by `devvm history export` (no launch, its record still forwarding): none; `off` again after a restart, none; a VM made with `--ssh-agent`, turned off, none;
|
||||
- stopped, then `smolvm machine start` from a shell with your agent gives it yours; `devvm history export` then stops it in one line, writing nothing; started so again, devvm stops it too, and the next devvm starts it with none; `devvm host` on that start of devvm's keeps it running;
|
||||
- with network policy, a VM started outside devvm with a decider of someone else's is still reported by the self-check (`net_unenforced_stop`) first.
|
||||
- Sessions see the proxy's password, as devvm's own shells do, and VS Code relays what [VS Code](../using/ssh.md#vs-code) describes.
|
||||
|
||||
### Ports on Lima
|
||||
|
||||
**The guarantee:** the same as on [smolvm](#ports-on-smolvm). When a VM forwards every port, each TCP port from 1024 up that a server in it listens on, on its loopback or on all its addresses, is forwarded to the same port on the host's loopback, and only to its loopback. When a VM lists its ports, only those are forwarded. The forwarder never takes a port that a program on the host has on any address when the forward is made, or a port devvm records for another VM. Forwarding gives the VM no way out that it doesn't already have, because every connection starts on the host. Lima's own forwards listen with `SO_REUSEADDR`, so on macOS, whenever a server in the VM starts, Lima takes `127.0.0.1:PORT` while a program on the host has `*:PORT`, and that program's loopback connections go with it. That's why Lima forwards nothing and devvm's forwarder forwards by the same rules on every backend. On macOS, a VM with network policy doesn't depend on Lima for that, because its hostagent's sandbox refuses it every port but its ssh port, so Lima can't forward a port of the VM's even if it ignored its rules. The emulation is reviewed: the forwarder is the one reviewed for smolvm, and the parts that are Lima's own are below, with their threat check.
|
||||
**The guarantee:** when a VM forwards every port, each TCP port from 1024 up that a server in it listens on, on its loopback or on all its addresses, is forwarded to the same port on the host's loopback, and only to its loopback. When a VM lists its ports, only those are forwarded, however many it lists, by the same rules. The forwarder never takes a port that a program on the host has on any address when the forward is made, or a port devvm records for another VM. Forwarding gives the VM no way out that it doesn't already have, because every connection starts on the host. Lima's own forwards listen with `SO_REUSEADDR`, so on macOS, whenever a server in the VM starts, Lima takes `127.0.0.1:PORT` while a program on the host has `*:PORT`, and that program's loopback connections go with it. That's why Lima forwards nothing and devvm's forwarder forwards by the same rules on every backend. On macOS, a VM with network policy doesn't depend on Lima for that, because its hostagent's sandbox refuses it every port but its ssh port, so Lima can't forward a port of the VM's even if it ignored its rules. The emulation is reviewed, with the threat check's findings fixed or listed below, which is why the host key read is capped, reports are paced and the log is limited, and the end-to-end checks prove the rest.
|
||||
|
||||
**What it's built from:**
|
||||
|
||||
- **Lima's forwards off.** Each VM's `portForwards` holds three ignore rules, each for every guest port and protocol (`any`, which is TCP and UDP). They're on `127.0.0.1`, which Lima also matches for `::1`, on `0.0.0.0` and on `::`, which together match servers on all addresses. They come ahead of Lima's own last rule, which forwards everything. `CreateVM` sets them with `limactl clone --set`. `Start` sets them only where `limactl list` shows other rules, because an edit gives the VM new host keys at its next boot. Lima's ssh is its VM driver's forward (`ssh.localPort`), not a rule, so the ignore rules leave it alone, and they cover the guest's own ssh port like any other.
|
||||
- **The sandbox's binds (macOS, network policy).** The hostagent of a VM with network policy runs under a Seatbelt profile ([confinement](lima.md#confinement)) that denies every network bind but two kinds. It may bind the VM's ssh port over TCP, which devvm chooses and records in the VM's state (`ssh_port`), and unix sockets in the VM's Lima folder, which hold the hostagent's own socket (`ha.sock`), the VM's network (`default_ep.sock`, `default_fd.sock`) and ssh's control socket. Seatbelt matches a bind by its port alone, on any address, even when the rule names `localhost`, and it can't allow an ephemeral bind (port 0) without allowing every port. It matches a unix socket by its path with links resolved, so a link in the Lima folder doesn't let the hostagent bind a socket elsewhere. Lima's host resolver binds two ephemeral ports for its DNS server, so a VM with network policy starts with the resolver off and `127.0.0.1` as its DNS server, as on Linux, where nothing listens and lookups fail at once. The hostagent reaches the guest agent over vsock, which needs no bind. This list comes from starting a VM under a profile that reported every bind, then under one that denied the rest: Lima logs a forward it's refused (`failed to listen`) and carries on, while a refused resolver ends the start.
|
||||
- **Which ports.** The backend keeps a record of which ports each VM forwards, `ports` in the VM's backend folder (`vms/<hash>/backend/`), holding `all`, `none` or a list. `CreateVM` writes it, and `SetPorts` writes it without editing Lima's config, then starts a running VM's forwarder again with the new ports. A VM without a record forwards nothing, and devvm warns with `ports_forward_failed`. When the VM lists ports, the forwarder forwards the record's less those `Confinement.Free` leaves out, which are the ports a program on the host has, with a `ports_taken` warning. When none is left, no forwarder runs.
|
||||
- **The forwarder.** Lima's VMs use the forwarder that smolvm uses (`vmssh.Forwarder`, `vmssh.Forwards`), and [smolvm's note](#ports-on-smolvm) says what it reads, how it listens and what its limits are. On Lima it runs as `devvm _lima-ports`. `Start` starts it detached once the VM runs, for project VMs alone, whose starts set `Confinement.HostKey` where builds' starts don't. The forwarder reaches the VM's sshd on Lima's ssh port on the host's loopback. It logs in as Lima's user with Lima's key, `_config/user` in devvm's Lima home, which every VM there authorizes. It never uses the user's agent, and it forwards nothing either way. The VM's sshd allows local forwarding, and remote forwards only to `127.77.0.0/16` for [links](#links-between-vms) (`base.sh`), and `-W` is local forwarding.
|
||||
- **Reserved ports.** The forwarder never takes the VM's own Lima ssh port or its proxy port, which `Start` passes as `-reserve`. It also never takes the ssh, proxy and decider ports devvm chooses and records in any VM's state, or other VMs' listed ports (`netpolicy.UsedPorts`). Every Lima VM's ssh port is one of those, with or without network policy: devvm chooses it when it makes the VM, sets it with `limactl clone --set .ssh.localPort`, and records it as the VM's `ssh_port` before the clone (`Proxy.SSHPort`). devvm chooses a port while it holds a lock (`run/ports.lock`), so two devvm commands making or starting VMs at once never choose the same one. A stopped VM gets a new one only when a program on the host has its port on any address, even one that accepts no connections, or when the VM lists it to forward, and its start then sets it with an edit. Lima binds the port only once the VM boots, a few seconds after its start, so a port Lima picked itself would be free for another VM's forwarder in that window, and Lima's own ssh, which checks no host key, would then reach the other VM (the threat check below).
|
||||
- **A forwarder per VM, on the host.** The forwarder is `vmssh.Forwarder`, run detached by `vmssh.Forwards` as `devvm _lima-ports`, one per VM. `Start` starts it once the VM runs, for project VMs alone, whose starts set `Confinement.HostKey` where builds' starts don't, and `SetPorts` starts it again on a running VM, each after stopping any forwarder the VM had, which ends the connections open through it. devvm finds that one by its pid file, which it checks against the process's arguments, as it does for the proxy. It sends that forwarder SIGTERM and kills it if it hasn't ended within 2 s, so its ports are free before devvm asks which listed ports a host program has. devvm holds a lock of the VM's own (`ports.lock`, beside its pid file `ports.pid` in the VM's backend folder) from stopping the old forwarder until the new one has started, so two devvm runs at once, such as a start and `devvm ports`, leave one forwarder, the one its pid file names. `Start` waits up to 10 s for the forwarder to say it forwards while it runs. The forwarder says so in a status file of its own beside its pid file (`ports.status`), which holds its pid and which devvm removes before each start. If it doesn't, devvm warns with `ports_forward_failed`, naming its log, and leaves it to keep trying while the VM runs on.
|
||||
- **Reaching the VM.** The forwarder makes one ssh connection, a master (`ssh -F none -M -S <socket>`), to the VM's sshd on Lima's ssh port on the host's loopback. It logs in as Lima's user with Lima's key alone (`IdentitiesOnly`, `IdentityAgent=none`), `_config/user` in devvm's Lima home, which every VM there authorizes, and never with the user's agent. The master reads none of the user's configuration and forwards nothing either way, with `ClearAllForwardings`, `PermitRemoteOpen none`, `ProxyCommand none`, and no agent, X11 or tunnel. The VM's sshd allows local forwarding, and remote forwards only to `127.77.0.0/16` for [links](#links-between-vms) (`base.sh`), and `-W` is local forwarding. Its control socket is in `~/.local/share/devvm/run` (mode 700) and is named by a hash of the VM's name, because a socket's path is at most 104 characters. When the connection is lost, the forwarder closes its forwards and makes the connection again every 2 s while the lifeline holds.
|
||||
- **What listens.** The master's session runs `ports.sh` (`assets/guest/ports.sh`) as the VM's user (`sh -s`). It prints the local addresses of the VM's listening TCP sockets, which are the state `0A` lines of `/proc/net/tcp` and `tcp6`, whenever they change and every 10 s regardless, so it ends soon after the connection does. The forwarder treats the report as untrusted. A line over 128 bytes or a report over 4096 lines ends the connection, and anything that isn't a hex address and port is skipped. Reports are applied at least 500 ms apart, and one that comes sooner waits, holding up the VM's ssh channel with it, so the VM can't make the forwarder bind, dial and read devvm's state at its own pace. The VM can make the forwarder write to its log, with ports coming and going and with the session's stderr, so the log takes 200 writes at once and then one every 10 s. Each write is at most 512 bytes, without control characters but newlines and tabs, C1 included, and a start empties the log once it's over 1 MiB. A forwarded port's connections go to `127.0.0.1` for a server on all IPv4 addresses or on that address, and to `::1` for a server on all IPv6 addresses or on that address. A server on another `127.x` address alone gets its connections there. Servers on other addresses alone aren't forwarded.
|
||||
- **How many.** With every port, the forwarder takes ports from 1024 up, because the ports below are the host's system services. With listed ports, it takes those alone (`-only`), a listed port below 1024 included, because the user asked for it, and a bind the host refuses is logged. Either way the forwarder takes at most 256 ports at once. It reads the reserved ports (below) again each time it would take a port, and while it can't read them, it takes no new port. A port the forwarder couldn't take is tried again only once the VM's server on it goes and comes back.
|
||||
- **Listening.** The forwarder listens on `127.0.0.1` and `::1`, or on IPv4 alone on a host without IPv6. It binds without `SO_REUSEADDR` (`platform.ListenExclusive`). With that option, which Go and Lima set, macOS lets a socket take `127.0.0.1:PORT` while a program has `*:PORT`, and that program's loopback connections go with it. Without the option, the bind is refused when another program has the port on any address. This was checked on macOS for a program on `0.0.0.0`, on `::` (IPv4 and IPv6 at once, as Node's and Go's servers listen), on IPv6 alone and on `127.0.0.1`, each with and without `SO_REUSEADDR` of its own. A port held only by ended connections (`TIME_WAIT`, with nothing answering on it) is taken as usual, so a server that restarts gets its forward back. When a bind is refused, the forwarder dials the port and takes it only if the dial is refused. A full backlog times out, which counts as taken. A port the forwarder took on `127.0.0.1` but finds in use on `::1` is given up, so `localhost` never reaches two programs. On Linux, `SO_REUSEADDR` stays on. Linux refuses that bind with the option too while another socket listens on the port, and without it, the forwarder's own ended connections (`TIME_WAIT`) would keep anyone from listening on the port for a minute, its next forwarder included.
|
||||
- **Each connection.** Each forwarded connection is a channel of the master's (`ssh -S <socket> -W HOST:PORT`), with one process per connection and at most 256 at once. The VM's sshd opens it to the VM's own loopback from inside the VM. The channel's ssh has the master's options. If the master is gone, ssh connects on its own, and it then reaches the VM's sshd the same way, never the host's.
|
||||
- **Reserved ports.** The forwarder never takes the VM's own Lima ssh port or its proxy port, which `Start` passes as `-reserve`. It also never takes the ssh, proxy and desktop ports devvm chooses and records in any VM's state, or other VMs' listed ports (`netpolicy.UsedPorts`). Every Lima VM's ssh port is one of those, with or without network policy: devvm chooses it when it makes the VM, sets it with `limactl clone --set .ssh.localPort`, and records it as the VM's `ssh_port` before the clone (`Proxy.SSHPort`). devvm chooses a port while it holds a lock (`run/ports.lock`), so two devvm commands making or starting VMs at once never choose the same one. A stopped VM gets a new one only when a program on the host has its port on any address, even one that accepts no connections, or when the VM lists it to forward, and its start then sets it with an edit. Lima binds the port only once the VM boots, a few seconds after its start, so a port Lima picked itself would be free for another VM's forwarder in that window, and Lima's own ssh, which checks no host key, would then reach the other VM (the threat check below).
|
||||
- **The host key.** devvm forgets a VM's pinned host keys before each start and reads them again after it, through `limactl shell`, at most 64 KiB for at most 30 s, into its `known_hosts` (`sshconfig.HostKey`). The forwarder gets the VM's ed25519 key from there, copied into its own known_hosts file and pinned with `HostKeyAlias` and `StrictHostKeyChecking yes`. The pin keeps the forwarder from talking to a program on the host that takes the ssh port. It doesn't guard against the VM itself, which is already the other end of the connection.
|
||||
- **Its lifeline.** The forwarder follows the hostagent's pid file (`ha.pid`), as the proxy does, and exits once the file is gone, holds anything else, or its process is gone. `Stop` and `Delete` stop it, and `Delete` also removes its files and the record.
|
||||
|
||||
**What keeps a forward from carrying the VM out:** the same as on smolvm. The master asks for no remote forward, agent, X11 or tunnel, and OpenSSH's client refuses a channel that the server opens unasked. Every connection starts on the host, and the VM's sshd opens it to the VM's own loopback. With network policy, the VM's own connections stay confined by Seatbelt or QEMU's `restrict=on`, while the forwarder runs on the host as devvm, outside the hostagent's sandbox.
|
||||
**What keeps a forward from carrying the VM out:** every connection starts on the host. A program connects to the forwarder's port, and the forwarder asks the VM's sshd to connect to the VM's loopback. The VM opens nothing to the host through the forwarder, because the master asks for no remote forward, agent, X11 or tunnel, and OpenSSH's client refuses a channel that the server opens unasked, whatever sshd root in the VM runs. The only remote forwards devvm asks a VM for are a client's links, on a link session that is a connection of its own, never the forwarder's master ([links](#links-between-vms)). What the VM sends back goes to the program that connected, as with any forward. With network policy, the VM's own connections stay confined by Seatbelt or QEMU's `restrict=on`, while the forwarder runs on the host as devvm, outside the hostagent's sandbox.
|
||||
|
||||
**What it relies on:** what the shared forwarder relies on, which is OpenSSH honoring `-F none` and the kernel refusing a bind without `SO_REUSEADDR` where another socket has the port. It also relies on Lima binding its ssh forward on the host's loopback alone, on the host key that devvm pins at the start, and on Lima honoring the ignore rules ahead of its own rule. On macOS, a VM with network policy relies on Seatbelt refusing the hostagent's binds instead of on the rules, and on the Virtualization framework's own process, which runs outside the profile, binding nothing: the VM's network goes through the hostagent's unix sockets.
|
||||
**What it relies on:** OpenSSH's client refusing unrequested channels and honoring `-F none`, the kernel refusing a bind without `SO_REUSEADDR` where another socket has the port (checked on macOS), and devvm's state listing every VM's ports. It also relies on Lima binding its ssh forward on the host's loopback alone, on the host key that devvm pins at the start, and on Lima honoring the ignore rules ahead of its own rule. On macOS, a VM with network policy relies on Seatbelt refusing the hostagent's binds instead of on the rules, and on the Virtualization framework's own process, which runs outside the profile, binding nothing: the VM's network goes through the hostagent's unix sockets.
|
||||
|
||||
**What could break it:** a Lima release that forwards despite the ignore rules, or that forwards from somewhere other than `portForwards`. On macOS, a VM with network policy keeps the guarantee even then, because its sandbox refuses the binds. A VM without network policy, and every VM on Linux, where QEMU's `restrict=on` doesn't cover the hostagent's own binds, still relies on Lima honoring the rules. A Lima release that needs a new bind for a VM with network policy, such as a resolver that can't be turned off, fails its start closed, and Lima's log names the refused bind. The end-to-end checks look at the rules, and use `lsof` or `ss` to check that the hostagent has no TCP or UDP port of the VM's and that a host program keeps its port. A program on the host could take Lima's ssh port while the VM is stopped, and the pinned host key refuses it. Lima's key logs in to every VM in devvm's Lima home, as it does for Lima's own ssh, but public key authentication never sends the key to the VM.
|
||||
|
||||
@@ -206,9 +69,24 @@ These settings guard against the host's ssh asking for a forward that devvm's en
|
||||
- **A compromised hostagent:** listed. The bind rules stop a Lima that misbehaves, not code an attacker runs in it, which the profile still lets read and write your files.
|
||||
- **Starts without the sandbox:** listed. Only network-policy starts on macOS run under it. A build keeps Lima's host resolver, so its binds aren't denied, and a VM without network policy starts unconfined. Such a VM could run under a profile that denies binds alone, as its ssh port is fixed, but it would need Lima's resolver off too, which changes how it resolves names (the user-mode network's own DNS instead of the host's resolver), so that's proposed rather than done.
|
||||
|
||||
**Threat check for listed ports** (the security-audit skill, its local IPC companion). Listed ports use the same forwarder with `-only`, so these leads are what listed ports add, each confirmed or ruled out:
|
||||
|
||||
- **A port the VM chooses:** ruled out. `-only` comes from devvm's record for the VM, less what `Confinement.Free` leaves out, both on the host, and the VM's reports can't add to it. A listed port is forwarded only while a server in the VM listens on it, as with every port.
|
||||
- **Port 22 listed:** ruled out as a collision. Port 22 in the VM is its sshd, and Lima's ssh forward comes from another host port, so a listed 22 forwards the VM's sshd to the host's port 22 as it would forward any server. The VM's sshd still takes only keys. A host whose own sshd has port 22 keeps it, with a `ports_taken` warning.
|
||||
- **A listed proxy port:** ruled out. The forwarder reserves the VM's own proxy port whether or not it's listed, and every other VM's as well.
|
||||
- **A listed port below 1024:** taken because the user asked for it. A host service that has the port keeps it, and a bind the host refuses is logged. One that isn't running yet is under **Not covered**.
|
||||
- **A forwarder left behind:** ruled out. `Stop` and `Delete` stop it, `Delete` removes its files, and a start or change whose listed ports are all taken runs none. Two devvm runs that start a VM's forwarder at once take turns on the VM's lock, so the second stops the first one's forwarder, and neither leaves one that its pid file doesn't name, which nothing would stop.
|
||||
- **Network policy:** ruled out. Listed ports take fewer ports than every port, never more, and every connection still starts on the host.
|
||||
|
||||
**Not covered:**
|
||||
|
||||
- Everything on [smolvm's list](#ports-on-smolvm) applies. A VM can take a free port on the host's loopback that a program expects, host programs that bind all addresses later get their loopback connections sent to the VM, servers only on the VM's other addresses aren't forwarded, other users on the host reach the forwards, and UDP isn't forwarded.
|
||||
- A VM can take a free port from 1024 up, or a listed one, on the host's loopback that a program there expects to be its own, such as one that isn't running yet or is restarting. What the VM serves there reaches whatever connects, so a page it serves to the user's browser can reach the internet from the host, past network policy.
|
||||
- A host program that starts on a port while the VM has it forwarded still binds it when it listens on all addresses with `SO_REUSEADDR`, as most servers do (checked on macOS). Its loopback connections then reach the VM, because the forward's address is the narrower one. A program that binds without `SO_REUSEADDR` is refused.
|
||||
- The VM can make the forwarder dial a host loopback port that's in use and then close the connection at once without sending anything, because that's how the forwarder checks for a port held only by ended connections. This happens at most once per port every second, as the VM's listener on the port goes and comes back.
|
||||
- Servers only on the VM's other addresses, such as its network address or a container's, aren't forwarded.
|
||||
- Other users on the host reach the forwards, because they're on the host's loopback.
|
||||
- UDP isn't forwarded. [Ports](../using/ports-size.md#ports) shows how to tunnel it over TCP.
|
||||
- A server that keeps a port while its forward couldn't be made, because the host had the port, isn't forwarded until it stops and starts again.
|
||||
- Another user on the host can take a VM's ssh port while the VM is stopped or booting. Lima's own ssh would then reach that user's program, as it checks no host key, while devvm's forwarder and ssh config pin the VM's.
|
||||
- A VM started outside devvm, such as with `devvm limactl start`, or one whose forwarder ended, runs without forwarded ports until its next start through devvm, or until `devvm ports` changes its ports, which starts a forwarder with the host key devvm pinned at its last start.
|
||||
|
||||
@@ -223,30 +101,6 @@ These settings guard against the host's ssh asking for a forward that devvm's en
|
||||
- On macOS, a VM with network policy has a profile that denies every bind but its ssh port's over TCP and unix sockets in its Lima folder, and the same binds that work outside the profile, a TCP port and a UDP socket on the ssh port, fail under it. Its hostagent listens on its ssh port alone, with Lima's resolver off. Started again with Lima's own forwarding rule put back inside the sandbox, the hostagent tries a VM server's TCP and UDP ports and is refused, and has neither. The VM still works: ssh by name, devvm's forwarder (on the host's loopback alone), the proxy and the self-check. Its next start puts the ignore rules back.
|
||||
- With network policy, DNS fails at once, and Lima's network's DNS address and the host's address on it give no answer for a name.
|
||||
|
||||
## smolvm
|
||||
|
||||
Tried with smolvm 1.32.2 on an arm64 Mac before devvm had the backend ([its column](backends.md#features), [its page](../backends/smolvm.md)). The backend has its native features, network policy, emulated ([above](#network-policy-on-smolvm)), ssh for editors, emulated ([above](#ssh-for-editors-on-smolvm)), ports forwarded, every one or the listed ones, emulated ([above](#ports-on-smolvm)), and agent toggling, emulated ([above](#ssh-agent-toggling-on-smolvm)), all reviewed.
|
||||
|
||||
**Network policy.** smolvm's allow lists work per address, not per port, and DNS has its own path:
|
||||
|
||||
- With `--allow-cidr` of the host's gateway (`100.96.0.1`), the VM reaches every port on the host's loopback (ssh, local databases), not just the proxy's, and nothing else.
|
||||
- Under any allow list, the gateway answers DNS for any name, even queries sent to `8.8.8.8`: a way out for data. `--allow-host-pattern` of a name that doesn't exist makes it answer NXDOMAIN, and then smolvm's process sends no query anywhere (checked with nettop: on its own network it queries the host's resolver itself). `--dns 127.0.0.1` makes it time out, but only `machine create` sets it.
|
||||
- `--mediated-egress` with `--egress-interceptor` hands each connection the allow list admits to a host process, with its address, port and first bytes: it allows, denies, or takes the connection over. A test decider that took over only the proxy's port reached the proxy, and nothing else got through. It fails closed: with the decider gone, or a wrong token, connections are reset, and once started so, the VM won't start without one.
|
||||
- A connection the decider will refuse still opens in the VM (smolvm collects its first bytes first), then resets: only data, not a connect, shows it's refused.
|
||||
|
||||
**How the backend fits the interface:**
|
||||
|
||||
- **Tool images:** uncompressed EROFS, since smolvm's kernel can't mount compressed ones. The tools build machine runs `assets/shared-tools/build.sh` as on Lima, then makes each image again without compression (`plain.sh`), so `build.sh` and Lima's tool keys stay as they are. A backend names its format (`ToolFormat`, `plain-<plain.sh's hash>`), which a tool image's key hashes when it isn't build.sh's own; one share holds both kinds.
|
||||
- **No init system:** the image runs as a container in a microVM. While a build's scripts run, `systemctl` and `rc-update` are stand-ins that do nothing; after each start devvm makes the loop devices, mounts the tools and starts Docker where the docker layer installed it (`services.sh`). Docker's storage is `-v /var/lib/docker`, on the machine's own disk, on every VM. A project VM's setup tells a running systemd by `/run/systemd/system`, not by `systemctl` being there (Docker's packages install it).
|
||||
- **Ubuntu's container image, not its cloud image:** before the scripts, base gets `ca-certificates`, `sudo`, `bash` and the VM's user (`prepare.sh`). The user has the host's name and uid, as on Lima: virtiofs shows the project folder as the host's uid, so `ubuntu` (uid 1000) couldn't write it; a user with that uid is removed first. `Built.Origin` is the image by its digest. The backend's own scripts that go into base are in its key (`KeyFiles`).
|
||||
- **Network at create:** packs carry the build machine's network, CPUs and memory, and `--block-private` can't be removed from them, so builds use smolvm's default network and `CreateVM` sets everything. The network changes on a stopped VM (`machine update`), so `Start` sets it where it differs. For network policy, the decider's address and token come with `Confinement` (a backend with a decider implements `backend.Decider`), and the proxy is at the gateway.
|
||||
- **ssh-agent forwarding is chosen at create:** `machine update` can't change it, so turning it on or off later is a feature of its own (`agent-toggle`), emulated by the agent each start names ([above](#ssh-agent-toggling-on-smolvm)). The agent socket is read at each start.
|
||||
- **Every port** isn't something smolvm forwards, and listed ports aren't forwarded by smolvm either. Its forwards are at most 64, one of them ssh's, reach only servers on all addresses, and are set only while a machine is stopped. So `ports` and `ports-all` are emulated by a forwarder of devvm's ([above](#ports-on-smolvm)), and the VM's ssh is smolvm's only forward.
|
||||
- **smolvm's forwards share a port.** A forward of smolvm's takes `127.0.0.1:PORT` and `[::1]:PORT` while a program on the host has `*:PORT`, and that program's connections to them go with it (checked on macOS), as they do for any Go listener, because both set `SO_REUSEADDR`. That's one more reason a VM's ports aren't smolvm's forwards. Each start, and each change of a running VM's ports, on every backend, first checks the listed ports with `platform.PortInUse`, which listens on each without that option, and leaves out the ports in use with a warning (`Confinement.Free`). devvm's forwarder binds without `SO_REUSEADDR`, and devvm checks the ssh ports it chooses, smolvm's and Lima's confined ones, the same way.
|
||||
- **Lifeline:** smolvm's `agent.pid` has a second line, the start time, so the proxy reads only the first.
|
||||
- **Ports** are set on a stopped VM, so `Confinement.SSHPort` is a forward set before the start, and `Confinement.SSH` says whether to run ssh at all: an emulation runs only once it's let through.
|
||||
- **State:** `--state-dir` is Linux only, so on macOS devvm's machines share the user's smolvm, told apart by a label naming devvm's data folder; devvm acts only on machines with it. smolvm keeps a local usage journal; devvm turns it off (`SMOLVM_USAGE=0`).
|
||||
|
||||
## devcontainer.json
|
||||
|
||||
A new VM gets what the project's `devcontainer.json` says, as far as devvm does it ([its page](../using/devcontainer.md)), on every backend.
|
||||
@@ -263,7 +117,7 @@ A new VM gets what the project's `devcontainer.json` says, as far as devvm does
|
||||
- **The image:** `--from`'s path, but only an image its registry gives anyone: asked anonymously (`from.Lookup.Public`, never Docker's store), pinned to that digest, which every backend pulls by. A registry named `localhost` or by an address that isn't the internet's is refused by name, and the lookup's client (`from.NewPublicRegistry`) connects only to the internet's addresses, whatever a name resolves to, its token service's included; offline, only a registry digest recorded for that reference stands in.
|
||||
- **The docker layer:** the backend's own rules for it, as when it's named; the file never takes network policy away.
|
||||
- **The environment:** each variable's value is built as a shell word (single-quoted text, `"${X}"` for the VM's own), stored as JSON in the VM's state, and written as `export NAME=word` into the VM's environment file before devvm's own (which win); a name is checked again when it's written.
|
||||
- **Commands:** stored as argv in the VM's state; run by the backend's `Exec` (Lima: one `sh -c` string, each word in single quotes; smolvm: arguments as they are), as the VM's user, in the folder, after the self-check, `.git`'s locks and a `--clone` VM's clone: confined like anything in the VM. Their output goes to the run log, shown only through `printable`.
|
||||
- **Commands:** stored as argv in the VM's state; run by the backend's `Exec` (on Lima, one `sh -c` string, each word in single quotes), as the VM's user, in the folder, after the self-check, `.git`'s locks and a `--clone` VM's clone: confined like anything in the VM. Their output goes to the run log, shown only through `printable`.
|
||||
- **Ports:** only numbers and `localhost:N`/`127.0.0.1:N`, and never beyond the user's ports (`devvm ports -g`, or `--ports`, which wins): with every port forwarded, the default, they're among them; ports the user's list leaves out are said (`devvm ports add` forwards them), not added (`devcontainer_ports_not_forwarded`). Forwarded on this machine's loopback as any listed port, never a host port of another program's (`ports_taken`).
|
||||
|
||||
**What it relies on:** `os.Root` and `O_NONBLOCK`; `encoding/json`; each backend's `Exec` passing arguments unchanged; the registry's digest naming what's pulled (a pull checks it); the backend's own confinement of the VM and its builds.
|
||||
@@ -284,7 +138,7 @@ A new VM gets what the project's `devcontainer.json` says, as far as devvm does
|
||||
- **Reading** (a link out, `..`, a FIFO, a device, a huge file, a swap between the check and the read): ruled out: `os.Root`, a non-blocking open, the descriptor's own `Stat`, 1 MiB; one read per new VM; unit-tested (links, a FIFO).
|
||||
- **Variables** (`${localEnv:…}`, `${env:…}`, nested or unterminated): ruled out: refused, or left as text for the VM's shell; nothing is read from this machine.
|
||||
- **The environment file and state** (newlines, quotes, `$()`, a name like `A;rm`): ruled out: values are shell words, JSON-escaped in state (one line), names checked twice; the file is the VM's own.
|
||||
- **Command quoting** (`'`, newlines, an argument starting with `-`): ruled out: every backend runs `bash -lc 'exec "$@"'` with the argv after it; Lima quotes each word; smolvm passes `--`.
|
||||
- **Command quoting** (`'`, newlines, an argument starting with `-`): ruled out: every backend runs `bash -lc 'exec "$@"'` with the argv after it, and Lima quotes each word.
|
||||
- **Messages** (the file's values in this machine's terminal): ruled out: every message value goes through `msg.OneLine` as it renders, the image through `from.Valid`, errors' causes aren't printed, the log tail goes through `msg.Printable`.
|
||||
- **Commands before confinement:** ruled out: they run after the self-check (which stops a VM whose policy fails), `.git`'s locks, and a clone's seeding.
|
||||
- **A digest the registry made up** (`Docker-Content-Digest`): ruled out: `sha256:` and 64 hex digits, and every pull checks content against it.
|
||||
@@ -312,7 +166,6 @@ Behind a company proxy, nothing reaches the internet without going through it, s
|
||||
|
||||
- **Lima:** the build VM (an image's, the tools build's or `--from`'s conversion VM) reaches the proxy at `192.168.5.2`, the host's address on Lima's user-mode network, with vz and with QEMU, and on macOS its Seatbelt profile allows that one port of the host's loopback alongside its ssh port. The proxy runs on the host, so a company proxy on this machine's loopback, such as one a VPN client runs, works for builds on macOS too. Lima's `propagateProxyEnv` would write the host's proxy settings into the guest's `/etc/environment` between `#LIMA-START` and `#LIMA-END` at each boot (Lima's `07-etc-environment.sh`), and a stopped build VM's disk would keep that block, so build VMs start with `propagateProxyEnv: false`, and only VMs on Lima's own network (`NetDirect`) start with it on. Lima also logs the proxy settings it reads, password and all, into devvm's run log, so devvm runs `limactl` without them, and only a `NetDirect` VM's start gets them back. Each build script gets the build proxy's variables exported at its start, on its input with the script (`internal/backend/lima/buildproxy.go`), and `/etc/sudoers.d/devvm-build-proxy` keeps them for `sudo` until the scripts end. The build proxy's files and logs are in the build VM's folder, in `run/builds/<name>/run/build-proxy/` in devvm's data folder.
|
||||
- **`--from`'s conversion:** `oci/build.sh` runs as root with the build proxy's variables for crane. The container image's own code runs only in a chroot under `env -i`: the `/etc/os-release` check gets `PATH` alone, and `chroot_run` (`bootify.sh`, the CAs' `ca.sh`) gets `PATH`, `HOME`, `LC_ALL` and the build proxy's variables, for `bootify.sh`'s package downloads.
|
||||
- **smolvm** passes the host's proxy settings into a machine only with `--use-host-proxy`, which devvm doesn't use, so its builds get no proxy settings.
|
||||
|
||||
The build's policy is `**` alone, so on its own the build's proxy would refuse every name this machine can't resolve, and where only the company proxy resolves outside names, a build would reach nothing by name. Lima's build proxies start with `-upstream-unresolved`, which sends such names on to the company proxy unjudged. The refusal would protect little there, because without a company proxy those builds are on Lima's user-mode network and reach internal addresses directly.
|
||||
|
||||
@@ -334,14 +187,13 @@ The build's policy is `**` alone, so on its own the build's proxy would refuse e
|
||||
|
||||
**The password:** VNC's own authentication (RFB security type 2: DES of a 16-byte challenge, `desktop.Response`) is what macOS's Screen Sharing speaks to a server that isn't a Mac, and it takes 8 characters. devvm's are random, from 31 characters (about 40 bits), checked one at a time with a second's wait after a wrong one, so an online guess takes thousands of years. The relay checks it before it starts any ssh, so a wrong viewer costs the VM nothing. It's kept in the VM's state (`desktop_password`, mode 600), shown only with the address (`desktop_ready`, a message, not the run log), and never sent to the VM, so a VM can't use it to reach its own desktop's port. Screen Sharing gets the address alone (`open vnc://127.0.0.1:PORT`), not the password, which would be in `open`'s arguments where any process on this machine reads them.
|
||||
|
||||
**What keeps the VNC connection from carrying the VM out.** Every connection starts on this machine: a viewer connects to the relay, and the relay asks devvm's ssh for a local channel (`-W`) that the VM's sshd connects to the VM's own socket. The ssh asks for no session, agent, X11, tunnel or remote forward, and OpenSSH's client refuses a channel the server opens unasked, as for [the forwarder](#ports-on-smolvm). What the VM sends back goes only to the viewer that connected. The VM's server reaches nothing on this machine, so network policy holds as it is: the VM's own connections still reach only its proxy, and devvm allows no new host for the desktop.
|
||||
**What keeps the VNC connection from carrying the VM out.** Every connection starts on this machine: a viewer connects to the relay, and the relay asks devvm's ssh for a local channel (`-W`) that the VM's sshd connects to the VM's own socket. The ssh asks for no session, agent, X11, tunnel or remote forward, and OpenSSH's client refuses a channel the server opens unasked, as for [the forwarder](#ports-on-lima). What the VM sends back goes only to the viewer that connected. The VM's server reaches nothing on this machine, so network policy holds as it is: the VM's own connections still reach only its proxy, and devvm allows no new host for the desktop.
|
||||
|
||||
**The clipboard:** off unless `--clipboard`. Without it, `Xvnc` starts with `AcceptCutText`, `SendCutText`, `SetPrimary` and `SendPrimary` off, and the relay drops every `ClientCutText` from the viewer, extended clipboard ones too (`internal/desktop/filter.go`). It reads the viewer's messages by their lengths (RFC 6143's and the extensions TigerVNC offers: fences, continuous updates, desktop size, xvp, GII, QEMU's key and audio events) and ends the connection on a type it doesn't know, so nothing it can't read reaches the VM. The other way, from the VM to the viewer, isn't read: following the server's `ServerCutText` would mean decoding every screen update's encoding. A VM whose server was changed can send its clipboard to the viewer, so Screen Sharing's Use Shared Clipboard setting is what keeps it off this machine then.
|
||||
|
||||
**End-to-end checks** (`tests/e2e.sh`):
|
||||
|
||||
- `desktop` (Lima, a base VM with network policy): the relay on `127.0.0.1` alone, its port and password in the VM's state; a wrong password refused, the password let in, with the VM's ServerInit and a screen update (`TestE2EDesktop`); `Xvnc` on its user's socket (700, 600) and no TCP port, the clipboard off; the password in no file of the VM's, no run log and no host process's arguments while `devvm desktop` started; the self-check passed and no direct connection out, nor to the desktop's port on this machine; root's own server in place of `Xvnc` (no password, its socket anyone's, recording what reaches it): a wrong viewer never reaches it, and the viewer's clipboard never does while its key event does; Ctrl+C closing the port; `--clipboard` on the same port, the clipboard on;
|
||||
- `--backend smolvm`: the relay on `127.0.0.1` alone, a wrong password refused and the password let in, `Xvnc` on its user's socket and no TCP port, the clipboard off, the password in no file of the VM's or run log, Ctrl+C closing the port.
|
||||
- `desktop` (Lima, a base VM with network policy): the relay on `127.0.0.1` alone, its port and password in the VM's state; a wrong password refused, the password let in, with the VM's ServerInit and a screen update (`TestE2EDesktop`); `Xvnc` on its user's socket (700, 600) and no TCP port, the clipboard off; the password in no file of the VM's, no run log and no host process's arguments while `devvm desktop` started; the self-check passed and no direct connection out, nor to the desktop's port on this machine; root's own server in place of `Xvnc` (no password, its socket anyone's, recording what reaches it): a wrong viewer never reaches it, and the viewer's clipboard never does while its key event does; Ctrl+C closing the port; `--clipboard` on the same port, the clipboard on.
|
||||
|
||||
**Not covered:** the VM's clipboard sent to a viewer that takes it, by a server root changed; Screen Sharing itself, which no check drives, so its messages are the relay's reading of the protocol; a program on this machine with the password, which reaches the desktop as you do; a program on this machine, or a VM that reaches this machine's loopback, that keeps the relay's 8 connections busy or keeps failing its check, which keeps viewers out for as long as it does, and gets no further.
|
||||
|
||||
@@ -401,7 +253,7 @@ VMs with network policy and the nix layer share their downloads from cache.nixos
|
||||
|
||||
## Links between VMs
|
||||
|
||||
A link lets a program in one VM, the client, reach a TCP service in another VM, the target, by name, as in `postgres://db:5432/app`. Links work on Lima and smolvm, and with or without network policy on either VM. You run `devvm link publish 5432` in the target's folder to offer the port to any of your VMs, and `devvm link add db 5432` in the client's folder to reach it as `db:5432` and `db.devvm.internal:5432`. A link carries its connections over ssh through the host, so it uses neither VM's network, and the design keeps every guarantee that network policy and port forwarding give. The review of the code checks it against the threat check below.
|
||||
A link lets a program in one VM, the client, reach a TCP service in another VM, the target, by name, as in `postgres://db:5432/app`. Links work with or without network policy on either VM. You run `devvm link publish 5432` in the target's folder to offer the port to any of your VMs, and `devvm link add db 5432` in the client's folder to reach it as `db:5432` and `db.devvm.internal:5432`. A link carries its connections over ssh through the host, so it uses neither VM's network, and the design keeps every guarantee that network policy and port forwarding give. The review of the code checks it against the threat check below.
|
||||
|
||||
**The rules:**
|
||||
|
||||
@@ -420,11 +272,11 @@ A link lets a program in one VM, the client, reach a TCP service in another VM,
|
||||
- **The published ports** are in the target's state, a list of ports and ranges as `devvm ports` takes them, without `all`. `devvm link unpublish` takes ports out of the list, and a link to a port that isn't published is refused on its next connection.
|
||||
- **An address per target.** Each target a client links to gets an address of its own in `127.77.0.0/16`, chosen when the first link to it is made and kept for every port of that target in that client, so two targets can share a port. The client listens on the target's own port, so `devvm link add db 80` listens on port 80. The addresses are internal and appear only on these pages.
|
||||
- **Names in the client.** The setup that devvm sends at each launch writes a block marked `# devvm links begin` and `# devvm links end` into the client's `/etc/hosts`, with a line `127.77.x.y NAME NAME.devvm.internal` for each target, and replaces the block whole, writing the file in place rather than renaming over it. devvm sends the same block over ssh as root when links change on a running client, and it applies at once. No link name goes into `NO_PROXY` or `no_proxy`, which name the VM alone, because a running VM can't take a new environment: HTTP clients with the VM's proxy settings reach a link through the proxy (below). So a change of links changes no VM's environment, restarts no daemon, and on Lima runs no `limactl edit`, which would give the VM new ssh host keys.
|
||||
- **The client's sshd.** Every VM's sshd allows remote forwards to `127.77.0.0/16` alone, with one rule written when the image is built, so no link rewrites or reloads it. On Lima that's `00-devvm.conf` from `assets/layers/base.sh`, and on smolvm it's `services.sh`'s config. Both set `AllowTcpForwarding all`, `GatewayPorts clientspecified` and `PermitListen 127.77.*:*`, and keep `AllowStreamLocalForwarding local`, `PermitTunnel no` and `X11Forwarding no`. Without `clientspecified`, sshd would bind every remote forward on the VM's loopback, `127.0.0.1`. sshd matches the address a request names against the rule as text, so `0.0.0.0`, `127.0.0.1`, `::1`, `localhost` and `*` are refused, and only devvm on the host asks for these forwards, always with a numeric address. The rule is a safeguard for an honest VM, because root in the VM can change sshd, and the boundary is the host's ssh client (below).
|
||||
- **Low ports.** At each start, the setup sets `net.ipv4.ip_unprivileged_port_start` to `0` where it's `1024`, which is on Lima's Alpine VMs and on smolvm, so sshd can listen on a link's port below 1024 for the VM's user. Lima's Ubuntu and Debian VMs already have `0`, so devvm leaves it there.
|
||||
- **The client's sshd.** Every VM's sshd allows remote forwards to `127.77.0.0/16` alone, with one rule written when the image is built, so no link rewrites or reloads it. That's `00-devvm.conf` from `assets/layers/base.sh`, which sets `AllowTcpForwarding all`, `GatewayPorts clientspecified` and `PermitListen 127.77.*:*`, and keep `AllowStreamLocalForwarding local`, `PermitTunnel no` and `X11Forwarding no`. Without `clientspecified`, sshd would bind every remote forward on the VM's loopback, `127.0.0.1`. sshd matches the address a request names against the rule as text, so `0.0.0.0`, `127.0.0.1`, `::1`, `localhost` and `*` are refused, and only devvm on the host asks for these forwards, always with a numeric address. The rule is a safeguard for an honest VM, because root in the VM can change sshd, and the boundary is the host's ssh client (below).
|
||||
- **Low ports.** At each start, the setup sets `net.ipv4.ip_unprivileged_port_start` to `0` where it's `1024`, which is on Lima's Alpine VMs, so sshd can listen on a link's port below 1024 for the VM's user. Lima's Ubuntu and Debian VMs already have `0`, so devvm leaves it there.
|
||||
- **The link session.** For each running client with links, a hidden command, `devvm _links`, runs on the host as one detached process. It keeps an ssh connection of its own to the client, never the forwarder's master, with the options of `internal/backend/vmssh`: `-F none`, `BatchMode`, the VM's key alone (`IdentitiesOnly`, `IdentityAgent=none`), its pinned host key, `ForwardAgent=no`, `ForwardX11=no`, `Tunnel=no`, `PermitRemoteOpen=none`, `PermitLocalCommand=no` and `ProxyJump=none`. It starts that connection as a master with `ClearAllForwardings=yes`, so the master asks for nothing at first, and adds each link with `ssh -O forward -R 127.77.x.y:PORT:<socket>` and removes it with `ssh -O cancel`, at its start and while the client runs. A cancel keeps the connections that are open, and the master ending drops them. Each link is its own `-O forward`, never `ExitOnForwardFailure` for all of them, so a link whose address a program in the client already holds fails alone, with an error naming the link (`link_port_taken`).
|
||||
- **The sockets.** Each link's forward ends at a unix socket on the host, mode 600 in devvm's run folder `~/.local/share/devvm/run` (mode 700), named by a hash of the client, the address and the port, because a socket's path is at most 104 characters. The masters' control sockets are in the same folder, named by a hash of the client, and for a master to a target, of the target and its start too. A stale socket at the path is replaced, anything else there is refused, and the socket goes when its link or the process ends.
|
||||
- **Each connection.** When a program in the client connects to a link's address, the client's sshd opens a channel to the host for the forward, and the host's ssh connects it to that link's socket. `devvm _links` then reads the links state again and checks that the link still exists, that the target's ID matches, that the port is published, that the policy rule holds, that the target runs as its backend says, and, for a client with network policy, that the target's is enforced as it runs. The connections to one target share what its backend says of its run, which is whether it runs, its start and its ssh: one lookup is in flight for each target, and its answer is reused for one second (`linkRunFor`), so a burst of 256 connections asks smolvm once rather than running `smolvm machine ls` for each, which under that load answered wrongly for some. A connection that closes while its lookup runs finds the target stopped, but that lookup isn't kept: the connections waiting on it look again, so they get the target's real answer. A target that stops is noticed within that second, and the connection's other checks, the policy's as the target runs included, are made for each connection. It then carries the connection with `ssh -S <master> -o ProxyCommand=/usr/bin/false -W 127.0.0.1:PORT` through a master to the target that it keeps, one per target, with the target's key and pinned host key. The target's sshd connects to the target's own loopback. When the master is gone, `-S` alone would make a connection of its own, and `ProxyCommand=/usr/bin/false` makes that connection fail, so a channel goes through the master or nowhere. A target's master ends when the target stops, and the next one reads the target's known hosts again, because smolvm VMs get new host keys at each start. devvm never starts the target. At most 256 connections are carried at once, and the next one is refused and logged. A link's socket holds 128 connections waiting to be accepted on macOS, and the process accepts nothing while it starts an ssh, so its accept loop only accepts, and hands a burst on whole once 5 ms pass with nothing more waiting, the first has waited 50 ms, or 257 wait. Another goroutine then carries or refuses each connection in it, logging each refusal before it closes the connection, while the loop goes on accepting the next burst, and the loop waits for that goroutine only once 257 of the next burst wait. So every connection in a burst is carried or refused with `link_limit`, and none is refused by the socket unlogged.
|
||||
- **Each connection.** When a program in the client connects to a link's address, the client's sshd opens a channel to the host for the forward, and the host's ssh connects it to that link's socket. `devvm _links` then reads the links state again and checks that the link still exists, that the target's ID matches, that the port is published, that the policy rule holds, that the target runs as its backend says, and, for a client with network policy, that the target's is enforced as it runs. The connections to one target share what its backend says of its run, which is whether it runs, its start and its ssh: one lookup is in flight for each target, and its answer is reused for one second (`linkRunFor`), so a burst of 256 connections asks the backend once rather than once for each. A connection that closes while its lookup runs finds the target stopped, but that lookup isn't kept: the connections waiting on it look again, so they get the target's real answer. A target that stops is noticed within that second, and the connection's other checks, the policy's as the target runs included, are made for each connection. It then carries the connection with `ssh -S <master> -o ProxyCommand=/usr/bin/false -W 127.0.0.1:PORT` through a master to the target that it keeps, one per target, with the target's key and pinned host key. The target's sshd connects to the target's own loopback. When the master is gone, `-S` alone would make a connection of its own, and `ProxyCommand=/usr/bin/false` makes that connection fail, so a channel goes through the master or nowhere. A target's master ends when the target stops, and the next one reads the target's known hosts again, because a VM whose Lima config changed gets new host keys when it boots. devvm never starts the target. At most 256 connections are carried at once, and the next one is refused and logged. A link's socket holds 128 connections waiting to be accepted on macOS, and the process accepts nothing while it starts an ssh, so its accept loop only accepts, and hands a burst on whole once 5 ms pass with nothing more waiting, the first has waited 50 ms, or 257 wait. Another goroutine then carries or refuses each connection in it, logging each refusal before it closes the connection, while the loop goes on accepting the next burst, and the loop waits for that goroutine only once 257 of the next burst wait. So every connection in a burst is carried or refused with `link_limit`, and none is refused by the socket unlogged.
|
||||
- **The proxy's entrance.** In a client with network policy, an HTTP client that honors `HTTP_PROXY` sends `db:5432` to the VM's proxy, and the proxy is a second entrance to the same socket, so a link added while the client runs works at once without a restart. `devvm _links` writes every link the client has, carried or not, to `links.json` in the client's run folder, `vms/<hash>/run/` (mode 600, written whole) whenever they change or the file is gone, with each link's names, address, port, target and socket. A link it doesn't carry has no socket, and a session that ended leaves its list, so the proxy refuses those links (`502`, `link_refused`) instead of asking its rules, which could send `db` to a host the host's resolver or a company proxy finds by that name. devvm removes the list with the VM. devvm passes the path to `devvm _proxy -links`, and its run folder, where the sockets are, to `-link-sockets`, so `internal/proxy` stays standard library only, and the proxy reads the list for every request, after the VM's password and before any rule, as it does for `devvm.proxy`. It matches `CONNECT NAME:PORT` and absolute-form `GET http://NAME:PORT/` exactly, after one normalization: lower case, one trailing dot dropped, and `NAME.devvm.internal` as the list names it. It takes an entry only when the entry's socket is the one that `proxy.LinkSocket` names from devvm's run folder, this VM, the entry's address and its port, which is also the name `vmssh.Links.Socket` gives the socket. It then connects to the socket and passes the bytes as they are: no SNI check, no interception, no secret put in, even when a secret's hosts would match, and no rule asked. An absolute-form request goes over a new connection to the socket for each request, without the proxy's headers, and HTTPS in absolute form gets `400`. `devvm _links`'s checks of each connection apply to both entrances unchanged, and it logs the connection once, as `link`. A stale entry fails there, or finds no socket, which the proxy answers with `502` and logs as `link_refused` (`not carried`). The proxy also refuses any other name under `devvm.internal`, logged as a refused block, so a long name never reaches the rules. An absolute-form request to a link ends when the client gives it up, so a target that never answers can't hold the client's 256 connections. Anything else not on the list meets the floor and the rules as before, so a short name the client has no link for, before its first session lists it, is the rules' to decide.
|
||||
- **Events.** `devvm _links` writes `link`, `link_refused` (with why), `link_target_stopped` and `link_limit` events to the client's event log, in the proxy's JSON-lines format, with the link's name as the host and the target VM as `target`, so `devvm network log` shows them. A client without network policy gets an event log for them. `devvm _links` writes it with the proxy's own writer, which rotates it past 10 MiB by the proxy's rule and follows the file to its new name when the other writer rotated it, so the two writers never lose each other's lines.
|
||||
- **The forwarder skips links.** The port forwarder (`vmssh.Forwarder`) forwards a server on any loopback address of the VM's, so it would put a link's listener on the host's `127.0.0.1` and `::1`. It never forwards a listener whose address is in `127.77.0.0/16`, on any VM, so a server of the client's own on `127.0.0.1` with the same port is forwarded as usual. Lima's own forwards don't take it either, because devvm's rules ignore every port first, and Lima's fallback rule matches `127.0.0.1` and the bind addresses `0.0.0.0`, `::` and `::1` alone.
|
||||
@@ -433,29 +285,29 @@ A link lets a program in one VM, the client, reach a TCP service in another VM,
|
||||
**What keeps a link from carrying a VM out.** Every connection starts on the host, and neither VM's network carries it:
|
||||
|
||||
- **A VM with network policy reaches only its proxy and the links you made.** The link's bytes travel inside ssh connections that the host opens, so no backend's confinement changes, and the client's own connections, including sshd's, stay confined as before. Through its proxy, a VM reaches only the sockets of its own links: a request names a host and a port, never a socket, the proxy's list is in the VM's run folder, which no VM can write, and the proxy takes an entry only when its socket is the one devvm names for that VM's link at that address and port.
|
||||
- **The VM can't choose where its connections go on the host.** OpenSSH's client accepts a forwarded channel only for a listener it asked for, and connects it only where it chose, which is the link's socket. A channel the client's sshd opens for any other address or port, or of any other kind, is refused, whatever sshd root in the client runs. The forwarder's master asks for no remote forward, and the link session is a connection of its own, so links don't change what [the ports notes](#ports-on-smolvm) say.
|
||||
- **The VM can't choose where its connections go on the host.** OpenSSH's client accepts a forwarded channel only for a listener it asked for, and connects it only where it chose, which is the link's socket. A channel the client's sshd opens for any other address or port, or of any other kind, is refused, whatever sshd root in the client runs. The forwarder's master asks for no remote forward, and the link session is a connection of its own, so links don't change what [the ports note](#ports-on-lima) says.
|
||||
- **Other users and VMs can't use a link.** Its end on the host is a unix socket of yours, mode 600 in a folder of mode 700, so no other user on the host reaches it, and neither does a VM that reaches the host's loopback. Programs of yours on the host can connect to it, as they can already ssh into the target by the name devvm host shows.
|
||||
- **A target's service isn't put on the host's localhost.** `-W` reaches the target's loopback through its sshd, and the forwarder never forwards `127.77.0.0/16`, so a link listens nowhere on the host.
|
||||
- **Each VM's own ssh rules hold.** Host keys are pinned, each VM has its own key, and no agent is forwarded (`ForwardAgent=no`, `IdentityAgent=none`), as for the forwarder.
|
||||
|
||||
**Why not a shared network, the proxy, or a host port:**
|
||||
|
||||
- **A network shared between VMs** would bypass the proxy and every backend's confinement. On Lima it needs a root helper, and QEMU and smolvm can't make one.
|
||||
- **A network shared between VMs** would bypass the proxy and every backend's confinement. On Lima it needs a root helper, and QEMU can't make one.
|
||||
- **`CONNECT` through the proxy as the only way in** would work only for VMs with network policy, and a raw TCP client in every VM would need a tool of devvm's to make the connection. The proxy is a second entrance instead, for HTTP clients, beside the ssh forward that carries every link on every VM.
|
||||
- **The target's port forwarded to the host's localhost** is refused by the proxy's floor, is reached by any VM without network policy and any program on the host, and is a port that a host program can take first.
|
||||
|
||||
**What the prototype showed.** devvm's prototype ran in the e2e sandbox on every backend, and nothing needed the link feature off:
|
||||
|
||||
- macOS's ssh 10.3p1 and Linux hosts' ssh 9.6p1 and 10.2p1 accept `-R 127.77.x.y:PORT:<unix socket>`, and `-O forward` and `-O cancel` work on a master started with `ClearAllForwardings=yes`. A cancel keeps open connections, ending the master drops them, and a session keeps the `PermitListen` it connected with.
|
||||
- sshd 9.2p1 (Debian 12, `--from`), 10.2p1 (Ubuntu 26.04 and smolvm) and 10.3p1 (Alpine), with `GatewayPorts clientspecified` and `PermitListen` naming one address, bind that address alone and refuse `0.0.0.0`, `127.0.0.1`, `::1`, `localhost`, `*`, other ports and port 0. The glob `127.77.*:*` works the same way and matches the requested address as text.
|
||||
- All of them honor `ip_unprivileged_port_start`, which is `0` by default on Lima's Ubuntu and Debian VMs, and `1024` on Lima's Alpine VMs and on smolvm.
|
||||
- `SIGHUP` keeps sessions and open connections under systemd, OpenRC and `services.sh`. Lima's Ubuntu VMs (an sshd per connection over vsock) read the config at every connection. sshd's rule is written once, so links don't depend on either.
|
||||
- `ssh -W` through a kept master works over Lima's ssh and smolvm's forward, and a new master after the target restarts reads its rewritten known hosts. smolvm refuses the old key, and Lima keeps its key. Without a master, `-S` connects on its own unless `ProxyCommand=/usr/bin/false`.
|
||||
- sshd 9.2p1 (Debian 12, `--from`), 10.2p1 (Ubuntu 26.04) and 10.3p1 (Alpine), with `GatewayPorts clientspecified` and `PermitListen` naming one address, bind that address alone and refuse `0.0.0.0`, `127.0.0.1`, `::1`, `localhost`, `*`, other ports and port 0. The glob `127.77.*:*` works the same way and matches the requested address as text.
|
||||
- All of them honor `ip_unprivileged_port_start`, which is `0` by default on Lima's Ubuntu and Debian VMs, and `1024` on Lima's Alpine VMs.
|
||||
- `SIGHUP` keeps sessions and open connections under systemd and OpenRC. Lima's Ubuntu VMs (an sshd per connection over vsock) read the config at every connection. sshd's rule is written once, so links don't depend on either.
|
||||
- `ssh -W` through a kept master works over Lima's ssh, and a new master after the target restarts reads its rewritten known hosts, while Lima keeps its key. Without a master, `-S` connects on its own unless `ProxyCommand=/usr/bin/false`.
|
||||
- glibc 2.36 and 2.43 and musl 1.2.6 resolve `/etc/hosts` names in `127.77.0.0/16`, and Go, Node 18, 22 and 24, curl, Python and libpq 15 and 18 reach `db` and `db.devvm.internal`. HTTP clients honor `NO_PROXY` with `db,.devvm.internal`, Node 22 needs the leading dot, and Node 18's `fetch` ignores proxies.
|
||||
- devvm's port forwarder put a link's listener on the host's `127.0.0.1` and `::1` on Lima and smolvm, which is why it skips `127.77.0.0/16`.
|
||||
- devvm's port forwarder put a link's listener on the host's `127.0.0.1` and `::1`, which is why it skips `127.77.0.0/16`.
|
||||
- The prototype didn't run VMs with network policy, so the end-to-end checks do.
|
||||
|
||||
**What it relies on:** OpenSSH's client accepting forwarded channels only for listeners it asked for, and connecting each one only where it chose. It also relies on `-O forward` and `-O cancel` changing one master's forwards, on `ProxyCommand=/usr/bin/false` keeping `-S` from connecting without its master, and on the host's unix socket permissions. The pinned host keys and each VM's own key are the ones the [forwarder](#ports-on-smolvm) and [ssh](#ssh-for-editors-on-smolvm) rely on. Lima's rules must ignore every port ahead of its fallback rule, and devvm's state on the host must hold each link's target, ID and port. The proxy's entrance relies on devvm's run folder and the VM's being yours alone, and on the proxy checking each entry's socket against the one it names itself from the VM, the address and the port.
|
||||
**What it relies on:** OpenSSH's client accepting forwarded channels only for listeners it asked for, and connecting each one only where it chose. It also relies on `-O forward` and `-O cancel` changing one master's forwards, on `ProxyCommand=/usr/bin/false` keeping `-S` from connecting without its master, and on the host's unix socket permissions. The pinned host keys are the ones the [forwarder](#ports-on-lima) and [ssh](#ssh-into-vms) rely on. Lima's rules must ignore every port ahead of its fallback rule, and devvm's state on the host must hold each link's target, ID and port. The proxy's entrance relies on devvm's run folder and the VM's being yours alone, and on the proxy checking each entry's socket against the one it names itself from the VM, the address and the port.
|
||||
|
||||
**What could break it:** an OpenSSH release whose client accepts a channel for a listener it didn't ask for, which the end-to-end checks would see as a host connection devvm didn't make. A Lima release that forwards a listener on a `127.77` address despite the rules would put a link on the host's loopback, which the forwarder's own skip doesn't cover, and the end-to-end checks look for it on the host. A backend that started a target for a connection would break the rule that a connection never starts a VM, but devvm never asks a backend to start one then.
|
||||
|
||||
@@ -498,7 +350,7 @@ A link lets a program in one VM, the client, reach a TCP service in another VM,
|
||||
| Links changing on a running client | `-O forward` and `-O cancel`, the setup over ssh, and the proxy's list | devvm link add and devvm link rm on a running client apply within seconds, and with network policy, through the proxy too, without a restart |
|
||||
| Two targets on one port | An address per target | Two targets publishing the same port are each reached by their own name |
|
||||
| A link left behind | `devvm stop` and `devvm rm` end the process and its sockets, and `gc --orphans` finds leftovers | Removing either VM leaves no `devvm _links` process, socket or link state |
|
||||
| Links on every backend and both network policy choices | The same mechanism everywhere | The section runs on Lima and smolvm, with both VMs with network policy and both without, a port below 1024 such as 80 on Lima's Alpine VMs and smolvm, and `devvm network log` shows link events with and without network policy |
|
||||
| Links on every backend and both network policy choices | The same mechanism everywhere | The section runs with both VMs with network policy and both without, a port below 1024 such as 80 on Lima's Alpine VMs, and `devvm network log` shows link events with and without network policy |
|
||||
|
||||
### Groups
|
||||
|
||||
@@ -541,7 +393,7 @@ Lima on QEMU keeps one qcow2 disk per VM, and a clone copies it (2.0 GB for `bas
|
||||
|
||||
## One binary
|
||||
|
||||
devvm's own files (`assets/` in the repo: `base.yaml`, `layers/`, `features/`, `shared-tools/`, `guest/`, `oci/`, `container/`, `smolvm/`) are embedded in the binary (`assets.FS`), so devvm installs, moves and upgrades as one file and can't find a mismatched copy beside it. Code reads them from that file system; scripts reach VMs on their standard input, never by path or file mode. The binary is the only copy: no shared folder on disk holds devvm's files, because a copy there could be edited and still be used. A VM's proxy is devvm itself, so it reads its built-in policies from the binary (`-builtin-policy`, by name), once, and `-policy` carries only your files. `limactl create` reads `base.yaml` on its standard input (`-`). Only `--from`'s build on Lima needs a path, because its build VM mounts `oci/` read-only (root there reads it), with `guest/ca.sh` beside it when you have [company CAs](network.md#a-companys-ca). It writes them into its own temporary folder, `devvm-oci.<random>`, beside `vm/` and never inside it, files 600 and folders 700, and the build's cleanup deletes the folder however the build ends. Image keys hash the embedded files, so what goes into an image is always what its key describes.
|
||||
devvm's own files (`assets/` in the repo: `base.yaml`, `layers/`, `features/`, `shared-tools/`, `guest/`, `oci/`) are embedded in the binary (`assets.FS`), so devvm installs, moves and upgrades as one file and can't find a mismatched copy beside it. Code reads them from that file system; scripts reach VMs on their standard input, never by path or file mode. The binary is the only copy: no shared folder on disk holds devvm's files, because a copy there could be edited and still be used. A VM's proxy is devvm itself, so it reads its built-in policies from the binary (`-builtin-policy`, by name), once, and `-policy` carries only your files. `limactl create` reads `base.yaml` on its standard input (`-`). Only `--from`'s build on Lima needs a path, because its build VM mounts `oci/` read-only (root there reads it), with `guest/ca.sh` beside it when you have [company CAs](network.md#a-companys-ca). It writes them into its own temporary folder, `devvm-oci.<random>`, beside `vm/` and never inside it, files 600 and folders 700, and the build's cleanup deletes the folder however the build ends. Image keys hash the embedded files, so what goes into an image is always what its key describes.
|
||||
|
||||
## devvm's own Lima home
|
||||
|
||||
@@ -560,13 +412,13 @@ Lima merges `_config/default.yaml` and `override.yaml` of its home into every VM
|
||||
|
||||
## Things learned
|
||||
|
||||
- **Lima `vz` never returns freed guest memory to the Mac.** sbx returns it with a VM monitor of its own; libkrun has `MADV_FREE`, with a stronger fix still an open PR; smolvm's libkrun fork includes it.
|
||||
- **Lima `vz` never returns freed guest memory to the Mac.** sbx returns it with a VM monitor of its own; libkrun has `MADV_FREE`, with a stronger fix still an open PR.
|
||||
- **APFS clones** cost nothing until written, and `du` overcounts them: real use was 5.5 GB where `du` said 12.7 GB.
|
||||
- **Lima locks each additional disk to one running VM,** so images shared across VMs go through a shared folder (virtiofs on macOS, 9p on Linux) and are loop-mounted from it.
|
||||
- **Read-only mounts are enforced by the host:** even root in the VM can't write to them, but root can unmount a nested one and reach what's underneath.
|
||||
- **Codex and opencode refreshing their OAuth logins in a VM can rotate the token and sign the host out.** With network policy the VM holds only placeholders and the proxy refreshes on the host (`internal/proxy/logins.go`). Codex decodes `id_token`'s claims and the access token's `exp` without checking signatures, so placeholders are unsigned JWTs with the real account claims and a far-off `exp`.
|
||||
- **No existing tool** gives Lima Dockerfile-style layers with sharing at run time; smolvm, nerdbox and Kata do it on VM runtimes of their own.
|
||||
- **Where devvm fits,** next to sbx, smolvm and Colima: sbx puts agents first; devvm gives a full Linux VM per project, with agents optional.
|
||||
- **No existing tool** gives Lima Dockerfile-style layers with sharing at run time; nerdbox and Kata do it on VM runtimes of their own.
|
||||
- **Where devvm fits,** next to sbx and Colima: sbx puts agents first; devvm gives a full Linux VM per project, with agents optional.
|
||||
|
||||
## Open work and risks
|
||||
|
||||
@@ -574,7 +426,7 @@ User-facing limits are in [Known limits](../using/limits.md) and [what the secur
|
||||
|
||||
- **`--from`:** a moved tag is noticed only at the next build, not when listing images; devvm doesn't log in to registries, so private images work only through Docker; registries over plain HTTP (`localhost:5000`) aren't supported.
|
||||
- **Alpine:** `rc-status` as a normal user shows `acpid` and `syslog` as crashed, as their pid files are root's (`sudo rc-status` is clean).
|
||||
- **Free-space floors:** the free space devvm wants before each build and new VM ([free space](../using/ports-size.md#free-space)) is set by Lima's and smolvm's own packages, and for shared tool images in `internal/backend/disk.go`, where the comments give what each number was measured from. The measurements are free space, read with statfs before, during and after each step, in e2e runs on macOS with Lima `vz` and smolvm, and for shared tool images also with devvm's data folder on a tmpfs of its own on Linux. On Linux hosts, Lima's numbers add a copy of base's disk to an image's and a tools build's, but they haven't been measured there yet. A `--from` base converts its image in the host's temporary folder, which devvm doesn't check, because on Linux that's often a small tmpfs.
|
||||
- **Free-space floors:** the free space devvm wants before each build and new VM ([free space](../using/ports-size.md#free-space)) is set by Lima's own package, and for shared tool images in `internal/backend/disk.go`, where the comments give what each number was measured from. The measurements are free space, read with statfs before, during and after each step, in e2e runs on macOS with Lima `vz`, and for shared tool images also with devvm's data folder on a tmpfs of its own on Linux. On Linux hosts, Lima's numbers add a copy of base's disk to an image's and a tools build's, but they haven't been measured there yet. A `--from` base converts its image in the host's temporary folder, which devvm doesn't check, because on Linux that's often a small tmpfs.
|
||||
- **x86_64 hosts** are untested on real hardware; on Intel Macs, `--from`'s kernel is untested with `vz`.
|
||||
- **Linux hosts:** the QEMU wrapper depends on the shape of Lima's `-netdev user,id=net0,…` argument. If Lima changes it, the wrapper refuses to start QEMU rather than run it unrestricted.
|
||||
- **Network policy, not built:**
|
||||
|
||||
@@ -9,11 +9,11 @@ This page explains how `devvm desktop` serves a VM's desktop on this machine, ho
|
||||
|
||||
The `desktop` feature installs Xfce, TigerVNC's `Xvnc` and a command of devvm's, `devvm-desktop`, into `base`. Its packages come from base's package snapshot, as base's own do, and it downloads nothing else. When you run `devvm desktop`, devvm first checks that the VM has `devvm-desktop`, and refuses a VM without it (`desktop_no_feature`). Then it runs `devvm-desktop start off`, or `start on` with `--clipboard`, as the VM's user.
|
||||
|
||||
`devvm-desktop` starts `Xvnc` on display `:1` unless it's running. `Xvnc` listens on the socket `/run/devvm-desktop/vnc.sock` alone, in a folder of the VM's user's own (mode 700), the socket itself mode 600. It listens on no TCP port (`-rfbport -1`), and takes no X11 connections over TCP (`-nolisten tcp`), so devvm's port forwarder never sees it, even on a VM that forwards every port. It asks for no password of its own (`-SecurityTypes None`), because devvm checks the viewer's password on this machine first. The clipboard settings (`AcceptCutText`, `SendCutText`, `SetPrimary`, `SendPrimary`) are on or off as asked, and on a desktop that runs already, `devvm-desktop` changes them in place with `vncconfig`. Then it starts an Xfce session on the display, in a D-Bus session of its own, because smolvm's VMs run no init system that would start one. Nothing starts the desktop at boot, so a VM whose desktop you never open runs none. Its log is `~/.cache/devvm-desktop.log` in the VM.
|
||||
`devvm-desktop` starts `Xvnc` on display `:1` unless it's running. `Xvnc` listens on the socket `/run/devvm-desktop/vnc.sock` alone, in a folder of the VM's user's own (mode 700), the socket itself mode 600. It listens on no TCP port (`-rfbport -1`), and takes no X11 connections over TCP (`-nolisten tcp`), so devvm's port forwarder never sees it, even on a VM that forwards every port. It asks for no password of its own (`-SecurityTypes None`), because devvm checks the viewer's password on this machine first. The clipboard settings (`AcceptCutText`, `SendCutText`, `SetPrimary`, `SendPrimary`) are on or off as asked, and on a desktop that runs already, `devvm-desktop` changes them in place with `vncconfig`. Then it starts an Xfce session on the display, in a D-Bus session of its own. Nothing starts the desktop at boot, so a VM whose desktop you never open runs none. Its log is `~/.cache/devvm-desktop.log` in the VM.
|
||||
|
||||
## On this machine
|
||||
|
||||
`devvm desktop` listens on `127.0.0.1` alone, on the VM's port. That's the port its state records as `desktop_port` while no program on this machine has it, and otherwise a new one from 20000 to 59999 that no program and no VM has, which devvm records in its place. The port is among those devvm records for VMs, with their ssh, proxy and decider ports, so no VM's [port forwarder](ports.md#what-it-never-takes) takes it and no new VM gets it for its ssh or its proxy. devvm listens without address reuse, so a program that has the port on any address keeps it. The listener stays open until you press Ctrl+C, or until the VM no longer runs, which devvm checks every 5 seconds (`desktop_vm_stopped`). Nothing else listens for the desktop on this machine, at any other time.
|
||||
`devvm desktop` listens on `127.0.0.1` alone, on the VM's port. That's the port its state records as `desktop_port` while no program on this machine has it, and otherwise a new one from 20000 to 59999 that no program and no VM has, which devvm records in its place. The port is among those devvm records for VMs, with their ssh and proxy ports, so no VM's [port forwarder](ports.md#what-it-never-takes) takes it and no new VM gets it for its ssh or its proxy. devvm listens without address reuse, so a program that has the port on any address keeps it. The listener stays open until you press Ctrl+C, or until the VM no longer runs, which devvm checks every 5 seconds (`desktop_vm_stopped`). Nothing else listens for the desktop on this machine, at any other time.
|
||||
|
||||
Each connection to the port goes through devvm's relay, which runs in `devvm desktop`:
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ This page explains how devvm builds images and shared tools, how it keys and cac
|
||||
devvm builds each image in a VM of its own, and that VM then is the image:
|
||||
|
||||
1. For base, devvm makes a new VM from [Ubuntu's cloud image](#ubuntus-cloud-image) with `base.yaml`'s settings, or, with `--from`, from a container image [converted into a disk](#how-its-converted). A layer's VM is a copy of its parent image.
|
||||
2. The VM starts confined, so it reaches the internet but not the host's own services on loopback, and it forwards no ports. How that's enforced depends on the backend, as [Lima](lima.md#confinement) and [smolvm](smolvm.md#building-images) describe.
|
||||
2. The VM starts confined, so it reaches the internet but not the host's own services on loopback, and it forwards no ports. How that's enforced depends on the backend, as [Lima](lima.md#confinement) describes.
|
||||
3. The script runs. For base, that's `assets/layers/base.sh` and then the [features](../using/customizing.md) you chose, and for a layer, it's the layer's script.
|
||||
4. The VM stops. devvm writes the image's record last, `~/.local/share/devvm/images/<key>/record.json`, with its name, its chain, what base started from and its digest, its C library and when the build finished. The record is JSON that only devvm writes, and devvm ignores fields it doesn't know, so a newer devvm's record still reads.
|
||||
|
||||
@@ -24,7 +24,7 @@ devvm builds images in layers and caches them, as Docker does. `base` comes firs
|
||||
|
||||
| Image | Its key hashes |
|
||||
| --- | --- |
|
||||
| `base` | the backend, `assets/base.yaml`, `assets/layers/base.sh`, the chosen features in order (each name and its script), its rebuild counter, and with `--from`, the image, its digest and the scripts that convert it; on Lima, Ubuntu's pinned cloud image for the host (its release and SHA-256); on smolvm, its scripts for containers and Ubuntu's container image, pinned by digest |
|
||||
| `base` | the backend, `assets/base.yaml`, `assets/layers/base.sh`, the chosen features in order (each name and its script), its rebuild counter, and with `--from`, the image, its digest and the scripts that convert it; on Lima, Ubuntu's pinned cloud image for the host (its release and SHA-256) |
|
||||
| a built-in layer | its parent's key, its name, its script (`assets/layers/<name>.sh`) and its rebuild counter |
|
||||
| a custom layer | its parent's key, its name, its script (`~/.config/devvm/layers/<name>.sh`) and its rebuild counter |
|
||||
|
||||
@@ -62,7 +62,7 @@ A VM keeps the image it was made from, and its state keeps that image's chain. W
|
||||
|
||||
## Ubuntu's cloud image
|
||||
|
||||
On Lima, base starts from a pinned, dated release of Ubuntu 26.04's cloud image (`release-YYYYMMDD` on cloud-images.ubuntu.com), and devvm pins the image's SHA-256 for arm64 and amd64 with it. The pin moves with base's package snapshot to the newest release dated before the snapshot, as smolvm's container image does ([maintaining](../contributing/maintaining.md#updating-pinned-versions)). A release with newer packages than the snapshot's would leave apt unable to install the packages that depend on their exact versions.
|
||||
On Lima, base starts from a pinned, dated release of Ubuntu 26.04's cloud image (`release-YYYYMMDD` on cloud-images.ubuntu.com), and devvm pins the image's SHA-256 for arm64 and amd64 with it. The pin moves with base's package snapshot to the newest release dated before the snapshot ([maintaining](../contributing/maintaining.md#updating-pinned-versions)). A release with newer packages than the snapshot's would leave apt unable to install the packages that depend on their exact versions.
|
||||
|
||||
devvm checks the image before it uses it:
|
||||
|
||||
@@ -85,7 +85,6 @@ Each download in `assets/layers/base.sh` is pinned to a version and a SHA-256 at
|
||||
devvm fits base's CPUs and memory to the host with one rule that every backend uses. Base gets `base.yaml`'s 4 CPUs, or the host's count when the host has fewer, because a Lima `vz` VM given more CPUs than the Mac has can start so slowly that its ssh never comes up, as [Lima's issue](https://github.com/lima-vm/lima/issues/1621) reports. Base gets `base.yaml`'s 8 GiB of memory, or half the host's whole GiB when 8 GiB would leave the host less than 2 GiB, because a VM asking for all of the host's memory doesn't start.
|
||||
|
||||
- **Lima** passes the fitted size to `limactl create` as `--cpus` and `--memory`, for base and for the VM that converts a `--from` image. The images built on base are clones of it, so they and their VMs keep that size.
|
||||
- **smolvm** sets the fitted size on base's build machine and on every VM you give no size, because a pack would otherwise give a VM its build machine's CPUs and memory.
|
||||
|
||||
A size you set with `--cpus`, `--memory` or `devvm size -g` replaces the fitted one. devvm checks that size against the same rule, so it refuses more memory than the host's whole GiB less 2, or half of them on a host of 4 GiB or less, and the fitted memory always passes ([size](../using/ports-size.md#size-and-ports)). The fitted size isn't in image keys, because the host's size doesn't change what an image holds.
|
||||
|
||||
@@ -97,7 +96,7 @@ The built-in [`docker` layer](../using/images.md#built-in-layers)'s script is `a
|
||||
|
||||
The built-in [`nix` layer](../using/images.md#nix)'s script is `assets/layers/nix.sh`, and its allowlist is `assets/layers/nix.policy`. The script pins Nix's release tarball, the direnv binary and nix-direnv's `direnvrc` at the top, each with its version and SHA-256, which are per architecture for Nix and direnv, and fetches them with `devvm-fetch`. `scripts/bump.sh nix direnv nix-direnv` moves them. Nix's version is the one nixos.org's installer fetches, at least 2.35.3, which fixes the scripted installer's store ownership (GHSA-hf6w-2rg9-v84g) and the daemon's store corruption through `repair` (CVE-2026-110450). Nix's newer releases come with another installer, from artifacts.nixos.org, so the layer's pins change shape when it moves to one of them.
|
||||
|
||||
The script runs the tarball's own installer as `install --daemon --yes --no-channel-add`, which copies the tarball's store into `/nix`, downloading nothing, makes the `nixbld` build users and, under systemd, starts `nix-daemon`. On OpenRC, which a base `--from alpine` runs, the script adds a service of devvm's, `/etc/init.d/nix-daemon`, to the default runlevel and starts it, and before the install it adds Alpine's `xz`, unpinned, which GNU tar needs for the tarball. Nix's own binaries are static or linked against the C library in its store, so they run on musl. A VM with no init system, which is how smolvm runs an image, gets its daemon from the script and then from devvm after each start ([smolvm](smolvm.md#no-init-system)). Its extra settings turn on flakes and the `nix` command and keep `trusted-users = root`, so only root can choose caches and signing keys. They also set `sandbox = true` and `sandbox-fallback = false`, so a build fails where the kernel can't sandbox it, rather than run outside the sandbox without a word. The installer writes any proxy variables it finds into a systemd drop-in for the daemon, which would put a build's proxy into the image, so the script runs it without them. It points Nix at the system's CAs, which hold devvm's and yours. After the install, the script checks that every path in the store is root's, and it fails otherwise.
|
||||
The script runs the tarball's own installer as `install --daemon --yes --no-channel-add`, which copies the tarball's store into `/nix`, downloading nothing, makes the `nixbld` build users and, under systemd, starts `nix-daemon`. On OpenRC, which a base `--from alpine` runs, the script adds a service of devvm's, `/etc/init.d/nix-daemon`, to the default runlevel and starts it, and before the install it adds Alpine's `xz`, unpinned, which GNU tar needs for the tarball. Nix's own binaries are static or linked against the C library in its store, so they run on musl. Its extra settings turn on flakes and the `nix` command and keep `trusted-users = root`, so only root can choose caches and signing keys. They also set `sandbox = true` and `sandbox-fallback = false`, so a build fails where the kernel can't sandbox it, rather than run outside the sandbox without a word. The installer writes any proxy variables it finds into a systemd drop-in for the daemon, which would put a build's proxy into the image, so the script runs it without them. It points Nix at the system's CAs, which hold devvm's and yours. After the install, the script checks that every path in the store is root's, and it fails otherwise.
|
||||
|
||||
It also adds Nix's default profile to the end of sudo's `secure_path`, through `/etc/sudoers.d/devvm-nix`, so `sudo nix` works, and appends Nix's profiles to the `PATH` that `BASH_ENV` gives shells that read no profile. direnv goes into `/usr/local/bin` and nix-direnv into `/usr/local/share/nix-direnv`. A file in `~/.config/direnv/lib` loads nix-direnv and puts each project's direnv layout under `~/.cache/direnv/layouts`, named by a hash of the project's path, so its cached dev shell and garbage collector roots stay in the VM's home and out of the project folder. direnv's shell hook is in `~/.bashrc.d/direnv.sh`, which bash loads before `mise.sh`, and since each hook puts itself first in `PROMPT_COMMAND`, direnv's runs after mise's, and a dev shell's `PATH` comes before the shared tools'.
|
||||
|
||||
@@ -147,7 +146,7 @@ A new VM gets the lock's versions, and devvm checks the lock again first when th
|
||||
|
||||
devvm builds the tool images that a VM's shared tools need when it makes the VM, after its image, and when `devvm tools add` or `devvm tools update` gives a VM new ones, unless the share already has them (`Launch.buildTools`). `devvm build` builds images alone, never tool images. They build in a throwaway VM that devvm makes from base and confines like an image build. That VM never sees the share. It writes into a folder of its own, `~/.local/share/devvm/tools-build.<random>`, which devvm deletes once it's done. devvm then checks that each image is a plain file and not a link (`tool_bad_output`), moves it into the share and writes its record beside it, never through a name the VM could have planted. Go builds in a VM of its own, never together with other tools. Only one build at a time writes to the share, because each holds the share's lock, `~/.local/share/devvm/tools.lock`, outside the share that VMs mount. Another devvm waits for it, saying so (`share_waiting`) after 3 seconds, until the build ends or you press Ctrl+C. The lock is an OS lock on an open file, so the system releases it when its devvm ends, however it ends, and a devvm that crashed or that you killed never leaves another one waiting.
|
||||
|
||||
Each tool image is named `<tool>-<version>-<key>.erofs`. Its key hashes the tool's entry in the tools lock (its version, its downloads and their checksums), `assets/shared-tools/build.sh`, the `[settings]` table of `assets/shared-tools/mise.toml`, the C library the image is built for and the backend's format. The settings are in the key because they change what mise installs, such as `python.compile`, and the key reads what they say, so a comment or another way of writing the same settings leaves it as it is. Lima's format is `build.sh`'s own, compressed EROFS, which adds nothing to the key. smolvm's is `plain-<hash>`, the same image rewritten uncompressed by `assets/smolvm/plain.sh`, and the hash is of that script. A new version, a new download, an edited build script or a changed setting builds the image again, and a base with a different C library, such as Alpine's musl, or a VM on another backend gets an image of its own. The share can therefore hold up to four builds of one version. When the lock has no download of a tool for the VM's platform, devvm doesn't build it and says to try again later (`tool_unbuilt`).
|
||||
Each tool image is named `<tool>-<version>-<key>.erofs`. Its key hashes the tool's entry in the tools lock (its version, its downloads and their checksums), `assets/shared-tools/build.sh`, the `[settings]` table of `assets/shared-tools/mise.toml`, the C library the image is built for and the backend's format. The settings are in the key because they change what mise installs, such as `python.compile`, and the key reads what they say, so a comment or another way of writing the same settings leaves it as it is. Lima's format is `build.sh`'s own, compressed EROFS, which adds nothing to the key. A new version, a new download, an edited build script or a changed setting builds the image again, and a base with a different C library, such as Alpine's musl, gets an image of its own, and so would a VM on another backend. When the lock has no download of a tool for the VM's platform, devvm doesn't build it and says to try again later (`tool_unbuilt`).
|
||||
|
||||
An image is base and its layers alone, and a VM's shared tools are a list in its state (`tool_names`) beside its image. `build.CheckLayers` refuses a shared tool's name in an image name (`tool_not_layer`), so `devvm build`, `devvm rebuild` and `devvm images rm` refuse one, because shared tools aren't images and their versions come from the lock.
|
||||
|
||||
@@ -159,20 +158,19 @@ A build's `ImageSpec.Trust` holds two scripts made from `ca.sh`, which run as ro
|
||||
|
||||
- **Lima:** `Add` runs right after the start, through `sudo sh`, then base's or the layer's scripts, then `Remove`, before the final `sync` and the stop.
|
||||
- **Lima with `--from`:** the conversion's build VM, which is deleted afterwards, also runs `Add`. `oci/build.sh` gets `ca.sh`, from devvm's `guest/` folder mounted read-only, and runs it in the image's chroot with the CAs before `bootify.sh` and without them after it, so that Alpine's `apk` reaches its HTTPS mirrors. The converted base then builds as Lima's does.
|
||||
- **smolvm:** `Add` runs right after the start, before `prepare.sh`, whose downloads come first in a container image (`apk` over HTTPS on Alpine), and `Remove` runs after `sshd.sh`, before the stand-ins go and the machine is packed.
|
||||
- **Shared tools:** `ToolsSpec.Trust.Add` runs before `build.sh` on every backend. devvm deletes the build VM and keeps only its output folder, so it needs no `Remove`.
|
||||
|
||||
An image is therefore the same with or without CAs, which is why its key holds none of them, and a tool image's key stays its lock entry, `build.sh`, mise's settings and the C library. When there are CAs, the build's numbered steps include the two scripts. A layer script that copies the system's bundle elsewhere keeps that copy.
|
||||
|
||||
**End-to-end checks** (`tests/e2e.sh`, `images`): a layer built with a test CA in the folder trusts it while its script runs, keeps its key once the folder is emptied, and a copy of its image booted without devvm has none of devvm's CA files. The smolvm section checks the same build.
|
||||
**End-to-end checks** (`tests/e2e.sh`, `images`): a layer built with a test CA in the folder trusts it while its script runs, keeps its key once the folder is emptied, and a copy of its image booted without devvm has none of devvm's CA files.
|
||||
|
||||
## The share
|
||||
|
||||
devvm builds each tool version once for each backend and C library into a read-only image (EROFS) in `~/.local/share/devvm/tools`, with its record next to it in `<image>.json`. The record is JSON that only devvm writes, with the image's SHA-256 (`sha256`), its C library (`libc`), its backend's format (`format`), the backend that built it (`backend`), when it was moved in (`built`) and, once retention finds that no VM has it, since when (`idle_since`). The share holds only the images and their records. Lima's images are compressed, and smolvm's are uncompressed, because smolvm's kernel mounts no other format. That folder is mounted read-only in every VM at `/mnt/devvm-tools`, and each VM mounts the images its tools need at `/opt/devvm/tools/<tool>/<version>`, at boot and on every launch. A VM can't change the shared images, even as root.
|
||||
devvm builds each tool version once for each backend and C library into a read-only image (EROFS) in `~/.local/share/devvm/tools`, with its record next to it in `<image>.json`. The record is JSON that only devvm writes, with the image's SHA-256 (`sha256`), its C library (`libc`), its backend's format (`format`), the backend that built it (`backend`), when it was moved in (`built`) and, once retention finds that no VM has it, since when (`idle_since`). The share holds only the images and their records, and Lima's images are compressed. That folder is mounted read-only in every VM at `/mnt/devvm-tools`, and each VM mounts the images its tools need at `/opt/devvm/tools/<tool>/<version>`, at boot and on every launch. A VM can't change the shared images, even as root.
|
||||
|
||||
A tool that doesn't mount fails the launch (`tools_unmounted`). mise's `auto_install` stays on for a project's own version files, so without this check a tool that isn't mounted would download into the VM on first use without a word. The VM's mount script, `devvm-tools`, tries every image in the VM's list. It leaves out the empty mount point of one that fails, lists each failed image in `/run/devvm/tools-unmounted` and exits non-zero, which fails the launch's setup. The setup removes that list before anything else it runs, so a list left from the VM's boot isn't read after a failure that has nothing to do with the tools. devvm then reads the first 16 KiB of that list from the VM, and it gives up after 10 seconds, because root in the VM could make the read hang. It counts only a whole line that is one of the VM's own tool images from its state, so the error shows devvm's own names, never the VM's text. devvm reads the list with a command of its own because the setup's output goes straight to the run log, and a pipe for reading it would keep devvm waiting on any process that the setup left running.
|
||||
|
||||
At boot the same failure fails only the `devvm-tools` service, and the boot goes on. smolvm's machines run no init system, so devvm mounts their tools at each start, and a failure there also lets the start go on. In every case, the launch's setup runs the mount script again and stops on the failure.
|
||||
At boot the same failure fails only the `devvm-tools` service, and the boot goes on. Either way, the launch's setup runs the mount script again and stops on the failure.
|
||||
|
||||
## Listing and cleaning up
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ A VM's state records its choice as `net=on` or `net=off`. When devvm starts a VM
|
||||
1. It makes its CA, unless it has one with over a week left, and on macOS it keeps the CA out of Time Machine.
|
||||
2. It writes the VM's [secrets](#secrets) as the VM's proxy sees them.
|
||||
3. It starts the VM's [proxy](#the-proxy) on a free port on the host's loopback, and waits for the proxy to say it's listening.
|
||||
4. It starts the VM [confined](lima.md#confinement), with the VM's proxy settings pointing at the proxy. On smolvm the confinement is emulated ([smolvm](smolvm.md#network-policy)).
|
||||
4. It starts the VM [confined](lima.md#confinement), with the VM's proxy settings pointing at the proxy.
|
||||
5. It runs [the self-check](#the-self-check) before the VM's setup and before its shell.
|
||||
6. It sets the VM up, as [the VM's setup](#the-vms-setup) describes. The setup puts devvm's CA in the VM, points the tools that don't read the environment at the proxy, and writes the VM's placeholders and its [agents' logins and settings](#agents-logins-and-settings) with your keys taken out.
|
||||
|
||||
@@ -24,7 +24,7 @@ devvm makes a VM without network policy, and warns you, when the VM's backend ca
|
||||
|
||||
One proxy runs for each VM. It runs on the host as `devvm _proxy`, a hidden command, and listens on a loopback port. The VM reaches nothing else over its network, so every connection the VM makes goes through its proxy. The one other way out of the VM is the [links](ports.md#links-between-vms) you add to it, which this machine carries over ssh to the ports your other VMs publish, so they don't use the VM's network. The proxy is a second entrance to those links, for the VM's HTTP clients ([links through the proxy](#links-through-the-proxy)).
|
||||
|
||||
Other programs on the host can also reach that port, so the port alone doesn't identify the VM. Every request must carry the VM's password in `Proxy-Authorization`, with the user `devvm`, or it gets `407`. Each VM has its own random password in its proxy settings. The proxy reads the password from a file only you can read, never from its arguments, which other users can see, and it refuses to start without one. The VM's settings also get the password through files ([Lima](lima.md#a-lima-home-of-its-own), [smolvm](smolvm.md#what-devvm-sets-on-a-vm)).
|
||||
Other programs on the host can also reach that port, so the port alone doesn't identify the VM. Every request must carry the VM's password in `Proxy-Authorization`, with the user `devvm`, or it gets `407`. Each VM has its own random password in its proxy settings. The proxy reads the password from a file only you can read, never from its arguments, which other users can see, and it refuses to start without one. The VM's settings also get the password through files ([Lima](lima.md#a-lima-home-of-its-own)).
|
||||
|
||||
For each connection, the proxy does the following:
|
||||
|
||||
@@ -56,8 +56,6 @@ flowchart TD
|
||||
|
||||
A tunnel that the proxy doesn't intercept carries the bytes both ways as they are. When the VM finishes sending, the proxy closes its side of the connection to the far end, so the far end sees the end of what the VM sent and can still answer. The tunnel ends when the far end's bytes end, or when the proxy can't pass them on because the VM's connection has gone, and then the proxy closes both connections. In a tunnel to a host the policy allows, the proxy reads the VM's first five bytes to see whether they start a TLS ClientHello before it passes anything on, so with a protocol whose server speaks first, such as SMTP, the VM gets no answer until it has sent five bytes.
|
||||
|
||||
On smolvm the proxy also decides each connection the VM opens, before smolvm makes it. It takes over the connections to itself and refuses the rest ([details](smolvm.md#network-policy)).
|
||||
|
||||
### Links through the proxy
|
||||
|
||||
A VM's `NO_PROXY` names only the VM itself, so an HTTP client that uses the VM's proxy settings sends a request for a link, such as `http://db:5432/`, to the proxy. A running VM can't take a new environment, so the proxy carries those requests itself, and a link added while the VM runs works for every HTTP client at once.
|
||||
@@ -89,7 +87,7 @@ The event log's `upstream` field names the company proxy, by host and port, for
|
||||
|
||||
### How long a proxy runs
|
||||
|
||||
The proxy exits when the VM's Lima hostagent does, which it learns from the hostagent's pid file, the VM's lifeline (`-lifeline`). On smolvm it watches the machine's process instead. The proxy starts before the VM, so it waits for the lifeline to name a process that runs. What the file held when the proxy started is an earlier start's, and the proxy waits past it, but when a new start writes the file and its process is already gone, the proxy exits. Once it follows a start, it runs while the file holds what it held then and that process runs, so a VM started again gets a new proxy. If the hostagent never appears, the proxy exits 15 minutes after it started, and `devvm stop` stops it at once.
|
||||
The proxy exits when the VM's Lima hostagent does, which it learns from the hostagent's pid file, the VM's lifeline (`-lifeline`). The proxy starts before the VM, so it waits for the lifeline to name a process that runs. What the file held when the proxy started is an earlier start's, and the proxy waits past it, but when a new start writes the file and its process is already gone, the proxy exits. Once it follows a start, it runs while the file holds what it held then and that process runs, so a VM started again gets a new proxy. If the hostagent never appears, the proxy exits 15 minutes after it started, and `devvm stop` stops it at once.
|
||||
|
||||
A VM that starts again gets a new proxy on the same port. A running VM also gets a new proxy when its list of policies changed, when its CA was replaced, when its proxy is from another devvm binary, when the [CAs in your CA folder](#a-companys-ca) changed, or when the [company proxy](#through-a-company-proxy) settings in devvm's environment differ from the ones the proxy started with. To start a new proxy, devvm stops the old one with `SIGTERM`, and with `SIGKILL` when it's still running two seconds later. The old proxy counts as stopped only once its process is gone, not once its arguments can no longer be read, because an ending process loses its memory before its files, and for that moment its port still looks taken by another program, which would fail the launch with `proxy_port_taken`. `SIGKILL` goes only to a process whose arguments devvm can still read as the proxy's, so a proxy still ending gets none, and neither does another process given its pid since, even one whose arguments devvm can't read. If it still runs two seconds after that, devvm stops with `proxy_stop_failed` and starts nothing, because the old proxy would go on with its old settings.
|
||||
|
||||
@@ -243,10 +241,7 @@ flowchart TD
|
||||
|
||||
`devvm ls` and `devvm network` show such a VM's network policy as `unenforced`. That's a VM whose last self-check failed, or a running VM that isn't on the process devvm started confined, which devvm checks on the host each time.
|
||||
|
||||
What "the process devvm started" is depends on the backend:
|
||||
|
||||
- **Lima:** the VM's Lima process, which devvm starts [confined](lima.md#confinement).
|
||||
- **smolvm:** the machine's process, through the proxy's decider. `smolvm machine start` refuses the VM without a decider, and a VM started with someone else's decider isn't confined.
|
||||
On Lima, "the process devvm started" is the VM's Lima process, which devvm starts [confined](lima.md#confinement).
|
||||
|
||||
## Log files
|
||||
|
||||
@@ -279,9 +274,6 @@ devvm runs the proxy as itself, `devvm _proxy`. Its flags take one dash or two,
|
||||
| `-upstream` | a file of `HTTPS_PROXY=`, `HTTP_PROXY=` and `NO_PROXY=` lines (mode 600): reach allowed hosts through that company proxy |
|
||||
| `-secrets` | the VM's secret bindings, read again when they change |
|
||||
| `-secret-cmd` | the program run as `PROGRAM secret get NAME` for a value |
|
||||
| `-decider` | also decide each connection the VM opens, on this loopback address (smolvm's mediated egress) |
|
||||
| `-decider-to` | with `-decider`: the proxy's address in the VM, the only destination taken over |
|
||||
| `-decider-token-file` | with `-decider`: a file holding the shared key smolvm proves itself with (64 hex digits); required |
|
||||
| `-nix-cache` | serve the [shared Nix cache](#the-shared-nix-cache) at `http://devvm.proxy/nix/` from this folder, which it makes, only yours (mode 700) |
|
||||
| `-nix-cache-max` | with `-nix-cache`: the cache's cap, in bytes (default 10 GiB) |
|
||||
| `-links` | the VM's links' list, which `devvm _links` writes: reach each link through its socket, before any rule ([links through the proxy](#links-through-the-proxy)); a missing list has no links |
|
||||
|
||||
@@ -122,12 +122,11 @@ devvm writes nothing into the project folder. It keeps what you edit in `~/.conf
|
||||
| `exports/` | the agents' history that `devvm history export` and `devvm rm` save |
|
||||
| `agent.sock` | the socket of [devvm's own SSH agent](../using/ssh.md#devvms-own-agent) |
|
||||
| `lima/` | devvm's own [Lima home](lima.md#a-lima-home-of-its-own), unless `DEVVM_LIMA_HOME` moves it |
|
||||
| `smolvm/` | the smolvm backend's own files that aren't one VM's, such as its images |
|
||||
|
||||
[What devvm keeps on this machine](../using/space.md) says how each of these is cleaned up, and lists what the backends keep outside this folder.
|
||||
|
||||
A VM's state file records the VM's name and its ssh alias, the image the VM came from, its project folder, its backend and its settings, one `key=value` per line. devvm finds a folder's VM by the hash of the folder's path, so an existing VM has the name and the backend its state records, whichever backend you ask for: `devvm --backend smolvm` and then `devvm` in the same folder open the one VM. Only a new VM gets a name, which fits its backend's limit. The VM's folder lasts as long as the VM, because `devvm rm` also deletes it, so the next devvm in that folder starts fresh.
|
||||
A VM's state file records the VM's name and its ssh alias, the image the VM came from, its project folder, its backend and its settings, one `key=value` per line. devvm finds a folder's VM by the hash of the folder's path, so an existing VM has the name and the backend its state records, whichever backend you ask for. Only a new VM gets a name, which fits its backend's limit. The VM's folder lasts as long as the VM, because `devvm rm` also deletes it, so the next devvm in that folder starts fresh.
|
||||
|
||||
No VM's folder holds a socket, because a unix socket's path is at most 104 characters and ssh adds 17 to a control socket's while it makes it. The sockets that VMs need are in `run/`, named by hashes: each port forwarder's control socket, `run/<backend>-<hash>.ctl`, and each link session's `run/link-<hash>.sock` and `run/link-<hash>.ctl`. With the default data folder, every socket fits for a home folder of up to 35 characters, and the ssh control sockets are the longest.
|
||||
No VM's folder holds a socket, because a unix socket's path is at most 104 characters and ssh adds 17 to a control socket's while it makes it. The sockets that VMs need are in `run/`, named by hashes: each port forwarder's control socket, `run/<backend>-<hash>.ctl`, and each link session's `run/link-<hash>.sock` and `run/link-<hash>.ctl`. With the default data folder, every socket fits for a home folder of up to 37 characters, and the ssh control sockets are the longest.
|
||||
|
||||
Each write replaces a file whole, so a file is never left half written. devvm makes its files readable only by you (mode 600), and the programs it keeps to run, such as its mise and QEMU wrapper, are mode 700, as are its folders. Before every command, devvm makes the data folder and `~/.config/devvm` when they're missing and sets both to mode 700, whatever mode they had. A wider mode on anything beneath them then opens nothing to others, and when devvm can't set a folder's mode, it warns and goes on. The folders that hold history, logs, keys or secrets (`exports/`, `logs/`, `logs/runs/`, `run/`, `ca/`, `secrets/`, and the `run/`, `logs/` and `backend/` folders in each VM's folder) are set to mode 700 again whenever devvm writes an export, a log, a key or a secret into them, whatever mode they had before. devvm refuses to use one of those folders when it's a symbolic link or not a folder at all, so it never sets the mode of whatever a link points to. The data folder and `~/.config/devvm` may be symbolic links, such as into a dotfiles repo, and devvm follows them. When a file can't be read, devvm names the file and the line, and you fix the line or delete the file.
|
||||
@@ -5,7 +5,7 @@ weight: 4
|
||||
|
||||
This page explains how devvm's forwarder forwards a VM's ports to this machine, which ports it never takes, and how it runs on each backend. [Ports and size](../using/ports-size.md#ports) covers choosing a VM's ports with `--ports` and `devvm ports`.
|
||||
|
||||
devvm's forwarder forwards ports by the same rules on every backend, and devvm uses no backend's own forwards for a VM's ports. [Lima](lima.md#ports) and [smolvm](smolvm.md#ports) each explain why, and what devvm sets on the backend instead.
|
||||
devvm's forwarder forwards ports by the same rules on every backend, and devvm uses no backend's own forwards for a VM's ports. [Lima](lima.md#ports) explains why, and what devvm sets on Lima instead.
|
||||
|
||||
## What it forwards
|
||||
|
||||
@@ -17,7 +17,7 @@ The forwarder never forwards a server on an address in `127.77.0.0/16`, on any V
|
||||
|
||||
The forwarder never takes a port that a program on this machine has on any address. That program keeps the port and its `localhost` connections, and the forward waits until the VM's server stops and starts again.
|
||||
|
||||
The forwarder also never takes a port that devvm records for a VM, even while that port is free. Those are the ssh, proxy and decider ports that devvm chooses for VMs, the VM's own ssh port, and the ports other VMs list. A Lima VM without network policy has an ssh port that Lima picks and devvm doesn't record, but Lima holds that port, so the forwarder can't take it.
|
||||
The forwarder also never takes a port that devvm records for a VM, even while that port is free. Those are the ssh, proxy and desktop ports that devvm chooses for VMs, the VM's own ssh port, and the ports other VMs list. A Lima VM without network policy has an ssh port that Lima picks and devvm doesn't record, but Lima holds that port, so the forwarder can't take it.
|
||||
|
||||
When a start, or a change of a running VM's ports, finds that a program on this machine has a listed port, devvm doesn't forward that port and warns you (`ports_taken`). The VM starts or runs on all the same, and the next start or change that finds the port free forwards it again. [Ports](../using/ports-size.md#ports) says what happens to a program that binds a port on all addresses after the forwarder has forwarded it.
|
||||
|
||||
@@ -34,25 +34,23 @@ flowchart TD
|
||||
sshd -- "127.0.0.1:5173,<br>its own loopback" --> server["your server, in the VM"]
|
||||
```
|
||||
|
||||
How the forwarder logs in, and when it ends, differs by backend, as the Ports sections of [Lima](lima.md#ports) and [smolvm](smolvm.md#ports) describe.
|
||||
How the forwarder logs in, and when it ends, depends on the backend, as Lima's [Ports](lima.md#ports) section describes.
|
||||
|
||||
## Its process and files
|
||||
|
||||
The forwarder runs as a hidden devvm command, one process for each VM. devvm starts it after each start of the VM and again with the new ports when you change a running VM's ports, and `devvm stop` stops it. devvm keeps which ports a VM forwards in its own record for the VM, so `devvm ports` changes that record and never the backend's config. That record is in the VM's `backend/` folder, `~/.local/share/devvm/vms/<hash>/backend/`, and the forwarder's files are beside it: its log `ports.log`, and `ports.pid`, `ports.status`, `ports.known_hosts` and `ports.lock`. Its control socket is `~/.local/share/devvm/run/<backend>-<hash>.ctl`, outside the VM's folder, because a unix socket's path is at most 104 characters.
|
||||
|
||||
devvm reads every list of ports the same way, whether it comes from `--ports`, the VM's state or the backend's record. Each entry is a port from 1 to 65535 or a range of them, such as `8000-8010`. When the VM's state holds a list that devvm can't read this way, such as a file edited by hand, the VM doesn't start and devvm names the value it couldn't read with `port_invalid`, so a bad entry never becomes a port the VM didn't ask for.
|
||||
devvm reads every list of ports the same way, whether it comes from `--ports`, the VM's state or devvm's record. Each entry is a port from 1 to 65535 or a range of them, such as `8000-8010`. When the VM's state holds a list that devvm can't read this way, such as a file edited by hand, the VM doesn't start and devvm names the value it couldn't read with `port_invalid`, so a bad entry never becomes a port the VM didn't ask for.
|
||||
|
||||
| Backend | Process | Ports record | Log |
|
||||
| --- | --- | --- | --- |
|
||||
| Lima | `devvm _lima-ports` | `vms/<hash>/backend/ports`, which holds `all`, `none` or a list | `vms/<hash>/backend/ports.log` |
|
||||
| smolvm | `devvm _smolvm-ports` | `vms/<hash>/backend/record.json` | `vms/<hash>/backend/ports.log` |
|
||||
|
||||
The paths in the table are in devvm's data folder, `~/.local/share/devvm`.
|
||||
|
||||
## When it can't forward
|
||||
|
||||
- A VM without ssh forwards no ports, and devvm warns you (`ports_no_ssh`). On smolvm, for example, that's a VM whose image has no sshd.
|
||||
- When a forwarder doesn't start, devvm warns you and names its log (`ports_forward_failed`), and the VM runs on without forwarded ports.
|
||||
When a forwarder doesn't start, devvm warns you and names its log (`ports_forward_failed`), and the VM runs on without forwarded ports.
|
||||
|
||||
## Links between VMs
|
||||
|
||||
@@ -62,7 +60,7 @@ A [link between VMs](../using/links.md) carries a client VM's connections to a p
|
||||
|
||||
Each target that a client links to gets an address of its own in `127.77.0.0/16` in that client, starting at `127.77.0.1`. devvm chooses it when the client's first link to that target is made and keeps it for every port of that target, so two targets can share a port. The client's `/etc/hosts` holds a block between `# devvm links begin` and `# devvm links end`, with a line `127.77.x.y NAME NAME.devvm.internal` for each target. The VM's setup replaces the block whole at each launch, and again when links change on a running client. The setup writes the file in place, never renaming over it, and only when the block changed.
|
||||
|
||||
A link listens at its target's address on the target's own port, never on the client's `127.0.0.1` or `::1`. At each start, the setup sets `net.ipv4.ip_unprivileged_port_start` to `0` where it's `1024`, which is on Lima's Alpine VMs and on smolvm, so a link to a port below 1024 listens on that port too. Lima's Ubuntu and Debian VMs already have `0`.
|
||||
A link listens at its target's address on the target's own port, never on the client's `127.0.0.1` or `::1`. At each start, the setup sets `net.ipv4.ip_unprivileged_port_start` to `0` where it's `1024`, which is on Lima's Alpine VMs, so a link to a port below 1024 listens on that port too. Lima's Ubuntu and Debian VMs already have `0`.
|
||||
|
||||
The addresses are internal to devvm. `devvm link` and its JSON never show them, and the forwarder never forwards them ([above](#what-it-forwards)).
|
||||
|
||||
@@ -88,7 +86,7 @@ flowchart TD
|
||||
|
||||
1. The client's sshd carries the connection over the link session to this machine, where ssh connects it to the link's unix socket. The socket is mode 600, in `~/.local/share/devvm/run` (mode 700), and named by a hash of the client, the address and the port, because a socket's path is at most 104 characters.
|
||||
2. `devvm _links` checks the link again. The link must still exist, the target must be the VM it was made for, by its ID, the port must be published, the [network policy rule](../using/links.md#links-and-network-policy) must hold, and the target must be running, as its backend says. For a client with network policy, the target's network policy must also be enforced as the target runs, as `devvm ls` shows it, because a target that got network policy while it ran stays outside its proxy until its next start, and one whose self-check failed may reach the internet directly. devvm never starts the target for a connection. The link session asks the target's backend whether the target is running and how its ssh reaches it, and the connections to that target share that answer for one second, so a burst of connections asks the backend once and devvm notices a target that stops within a second. An answer that a connection closing cut short isn't shared, so the other connections ask again. devvm makes every other check again for each connection, including the check of the target's network policy as it runs.
|
||||
3. It carries the connection over one ssh connection that it keeps to each target, with the target's key and pinned host key, and the target's sshd connects to `127.0.0.1:PORT` in the target. That connection to a target ends when the target stops, and the next one reads the target's host keys again, because smolvm VMs get new ones at each start.
|
||||
3. It carries the connection over one ssh connection that it keeps to each target, with the target's key and pinned host key, and the target's sshd connects to `127.0.0.1:PORT` in the target. That connection to a target ends when the target stops, and the next one reads the target's host keys again, because a VM whose Lima config changed gets new ones when it boots.
|
||||
|
||||
With network policy, an HTTP client that uses the VM's proxy settings sends `db:5432` to the VM's proxy instead, and the proxy connects to the same link socket on this machine ([links through the proxy](network.md#links-through-the-proxy)). Steps 2 and 3 are the same for it, so the link's checks, its cap and its events hold for both ways in.
|
||||
|
||||
|
||||
@@ -46,22 +46,19 @@ The VM can't change the parts of `.git` that run code on the host, because devvm
|
||||
|
||||
A VM with network policy reaches nothing but its own proxy on the host and the [links](ports.md#links-between-vms) you added to it. On macOS its Lima process runs under a macOS sandbox, and on Linux QEMU's network is restricted ([details](lima.md#confinement)). Even root in the VM can't get around that. A link's connections don't use the VM's network, because this machine carries them over ssh, and only to a port that another VM with network policy publishes.
|
||||
|
||||
On [smolvm](smolvm.md#network-policy), which is experimental, network policy is emulated and reviewed. smolvm's allow list holds only the host, and its DNS answers only one name, `devvm.invalid`. smolvm still asks your resolver about that name, which is a narrow way out ([details](smolvm.md#network-policy)). smolvm asks the proxy about every connection before it makes the connection.
|
||||
The proxy applies the allowlist, and it refuses the host's own addresses and internal addresses unless a rule names them ([the proxy](network.md#the-proxy)). The one thing that VMs with network policy share is the [shared Nix cache](network.md#the-shared-nix-cache), for those with the nix layer. Only the host writes it, with packages from cache.nixos.org whose signature it checked, and nothing a VM sends is stored, so a VM can make the host fetch but can't change what another VM gets. After each start, devvm checks that the VM still runs confined and can't connect out directly, and it stops a VM that fails the check instead of opening it ([the self-check](network.md#the-self-check)).
|
||||
|
||||
### ssh into VMs
|
||||
|
||||
ssh and editors reach a running VM by name through the entries that devvm writes ([ssh access by name](../using/ssh.md#ssh-access-by-name)). Each entry is built so that ssh connects only to that VM and the connection gives the VM nothing else of this machine's:
|
||||
|
||||
- **Each entry checks the VM's own host keys,** which devvm keeps in `~/.local/share/devvm/known_hosts`. devvm reads them from the VM through its backend, instead of over the network, once the VM runs and again after each start. A VM whose Lima config changed gets new host keys when it boots, and a [smolvm](smolvm.md#ssh-for-editors) VM gets new ones at every start. A VM whose keys devvm can't read gets no entry, and ssh refuses a host key that doesn't match.
|
||||
- **Each connection is its own.** The entries set `ControlMaster no`, so a session never rides on a connection that another program opened. Of Lima's own ssh settings for the VM, devvm copies only the address, port, user and login key, because Lima's settings turn host key checks off. On smolvm the login key is devvm's own, one for each VM.
|
||||
- **Each entry checks the VM's own host keys,** which devvm keeps in `~/.local/share/devvm/known_hosts`. devvm reads them from the VM through its backend, instead of over the network, once the VM runs and again after each start. A VM whose Lima config changed gets new host keys when it boots. A VM whose keys devvm can't read gets no entry, and ssh refuses a host key that doesn't match.
|
||||
- **Each connection is its own.** The entries set `ControlMaster no`, so a session never rides on a connection that another program opened. Of Lima's own ssh settings for the VM, devvm copies only the address, port, user and login key, because Lima's settings turn host key checks off.
|
||||
- **The entries turn off everything else your ssh could share with the VM.** They set `ForwardX11 no`, `ForwardX11Trusted no`, `Tunnel no`, `PermitRemoteOpen none`, `AddKeysToAgent no`, `ProxyJump none`, `ProxyCommand none`, `UpdateHostKeys no` and `HashKnownHosts no`, whatever your own `Host *` says. That turns off X11, tunnels, remote SOCKS forwards and adding keys to an agent. `PermitRemoteOpen` needs OpenSSH 8.7 or newer (`ssh -V`), and an older ssh refuses the entries.
|
||||
- **Your agent is forwarded only as the VM's [SSH agent](../using/ssh.md#agent-forwarding) choice says.** On smolvm, changing that choice once a VM is made is emulated and reviewed ([smolvm](smolvm.md#ssh-agent-forwarding)).
|
||||
- **Your agent is forwarded only as the VM's [SSH agent](../using/ssh.md#agent-forwarding) choice says.**
|
||||
|
||||
A session carries the VM's connections through your machine only where your ssh asks for it. The entries can't turn off a `RemoteForward` of yours without also refusing an `ssh -R` you type, so a `RemoteForward` still applies, and you should keep remote forwards out of `Host *`. The VM's sshd allows local forwarding (`-L` and `-D`, which VS Code uses), and it allows remote forwards only on addresses in `127.77.0.0/16`, which devvm keeps for links between VMs, so a remote forward on the VM's `localhost`, as `ssh -R` asks by default, is refused. It allows no tunnels or X11. Root in the VM can change all of that, so it's your ssh that decides.
|
||||
|
||||
On [smolvm](smolvm.md#ssh-for-editors), ssh is emulated and reviewed. devvm runs the VM's sshd itself, with new host keys at each start, and a key of the VM's own is the only login.
|
||||
|
||||
### Secrets stay on the host
|
||||
|
||||
devvm saves secrets in the macOS Keychain, or elsewhere in files only you can read, and it never puts a secret in a process's arguments ([where secrets are saved](network.md#where-secrets-are-saved)). A VM uses only the Claude Code token, when its image has `claude`, and the secrets you bind to it. With network policy, a VM's secrets and its agents' logins stay on your machine, and its proxy puts them only into requests for their own hosts.
|
||||
@@ -76,7 +73,7 @@ The proxy's CA (`~/.local/share/devvm/ca`) is how the proxy reads traffic to the
|
||||
- **Files the VM writes into the project folder.** Review changes before you run project code on the host, such as `npm install`, `make`, editor tasks or hooks in the working tree. `--clone` keeps the VM's changes out until you fetch and merge them, and you should review those commits the same way.
|
||||
- **VMs without network policy,** because you answered no, passed `--no-network-policy`, or devvm warned that the VM can't have it. They reach anything this machine can, including its services on `localhost` (other VMs' ports, dev servers, databases) and your local network. They get the secrets they use themselves, and those secrets still work wherever the VM kept them after `devvm secret unuse`, `devvm secret rm` or `devvm network on`, so rotate them if that matters.
|
||||
- **Codex and opencode logins, and Claude Code's MCP secrets, without network policy.** The VM gets `auth.json` as it is, and it gets `~/.claude.json`'s MCP servers with their env values and headers. devvm names the servers that have them ([details](../using/coding-agents.md#copies)).
|
||||
- **A VM started outside devvm** with `limactl start`, or one running since before `devvm network on`, runs unconfined and reaches anything this machine can ([the self-check](network.md#the-self-check)). On smolvm, `smolvm machine start` refuses a VM that devvm started with network policy, unless it's given a decider of its own. It also gives any VM your shell's SSH agent, whatever the VM's choice, until devvm next finds the VM running and stops it ([details](smolvm.md#ssh-agent-forwarding)).
|
||||
- **A VM started outside devvm** with `limactl start`, or one running since before `devvm network on`, runs unconfined and reaches anything this machine can ([the self-check](network.md#the-self-check)).
|
||||
- **What allowed hosts and secrets permit.** The VM can push with a GitHub token it may use, spend Claude quota, or upload to any host on its allowlist. Use fine-grained GitHub tokens and keep allowlists short.
|
||||
- **What a VM made with a secret.** The proxy puts the secret into any request to that service, so a VM can use it to make credentials of its own. The proxy refuses GitHub REST calls that add a key to your account, a deploy key, a self-hosted runner or a webhook (`403`), but it can't refuse everything, such as GitHub's GraphQL API, an OAuth app grant or other services. If a VM may have done that, rotate the secret and check the service's keys, credentials and runners.
|
||||
- **What one VM learns of another through the shared Nix cache.** A VM can tell by how fast the cache answers whether some VM fetched a public package, and a VM that fetches many packages fills the cache up to its cap and pushes other VMs' packages out, so they download them again ([the shared Nix cache](network.md#the-shared-nix-cache)).
|
||||
@@ -85,7 +82,7 @@ The proxy's CA (`~/.local/share/devvm/ca`) is how the proxy reads traffic to the
|
||||
- **What a VM does through a link.** A [link between VMs](../using/links.md) joins the two VMs' trust: code in the client can often run code in the target through the service it reaches, such as Postgres's `COPY … TO PROGRAM`, and it then has the target's network, the secrets it may use and its project folder. devvm limits a link to the ports the target publishes, on the target's loopback, and a client with network policy to targets with network policy, but it doesn't limit what the service does ([links between VMs](../safety/network.md#links-between-vms)).
|
||||
- **Remote forwards you ask for** into a VM, with `RemoteForward` in your ssh config or `ssh -R`. The VM can connect through them to whatever they name on your machine. The VM's sshd refuses them only while root in the VM leaves that setting alone, and it never refuses one on an address in `127.77.0.0/16` ([ssh into VMs](#ssh-into-vms)).
|
||||
- **What VS Code relays** over Remote-SSH (`devvm code`), which is the ports that programs in the VM listen on and your GitHub sign-in for git's prompts. devvm turns both off in the VM's VS Code settings each time it sets the VM up, but the VM can turn them back on, so turn them off in your own VS Code settings as well ([VS Code](../using/ssh.md#vs-code)).
|
||||
- **Set-id bits on Linux hosts.** Root in a VM can set the set-user-id and set-group-id bits on files in the project folder. On macOS these bits don't reach the host, because virtiofs drops them, but on Linux they do. A file that a Lima or smolvm VM writes is yours, so a set-user-id file runs as you for anyone else on the machine who runs it. A set-user-id file that your machine's root owns runs as root for anyone who runs it, you included. devvm names such files at each launch and stop. It lists root's files apart with `setid_root_files`, and you shouldn't run them but delete them with `sudo rm`. It lists the rest with `setid_files`, and `chmod u-s,g-s FILE` clears their bits. Don't run programs from the project folder outside the VM.
|
||||
- **Escapes from the VM itself**, through bugs in Lima, Apple's Virtualization framework or QEMU, or on smolvm through bugs in smolvm and libkrun, which also enforce its network policy.
|
||||
- **Set-id bits on Linux hosts.** Root in a VM can set the set-user-id and set-group-id bits on files in the project folder. On macOS these bits don't reach the host, because virtiofs drops them, but on Linux they do. A file that a Lima VM writes is yours, so a set-user-id file runs as you for anyone else on the machine who runs it. A set-user-id file that your machine's root owns runs as root for anyone who runs it, you included. devvm names such files at each launch and stop. It lists root's files apart with `setid_root_files`, and you shouldn't run them but delete them with `sudo rm`. It lists the rest with `setid_files`, and `chmod u-s,g-s FILE` clears their bits. Don't run programs from the project folder outside the VM.
|
||||
- **Escapes from the VM itself**, through bugs in Lima, Apple's Virtualization framework or QEMU.
|
||||
|
||||
Found a way out of a VM? See [SECURITY.md](https://github.com/w3cj/devvm/blob/main/SECURITY.md).
|
||||
@@ -1,112 +0,0 @@
|
||||
---
|
||||
title: smolvm
|
||||
weight: 10
|
||||
---
|
||||
|
||||
This page explains how devvm builds and runs VMs on smolvm, and how it emulates what smolvm lacks. [smolvm (experimental)](../backends/smolvm.md) covers what you need to run it and what's different for you.
|
||||
|
||||
devvm emulates four [features](backends.md#features) that smolvm lacks, and each emulation has been reviewed. They are [network policy](#network-policy), [ssh for editors](#ssh-for-editors) (`devvm host`, `devvm code` and `--clone`), [forwarding ports](#ports), every one or only the ones you list, and [turning SSH agent forwarding on or off](#ssh-agent-forwarding) after a VM is made.
|
||||
|
||||
## Its machines
|
||||
|
||||
On macOS, smolvm keeps every machine in your own smolvm state, because devvm can't give it a folder of its own (`--state-dir` is Linux only). So devvm keeps its machines apart from yours by a label. Every machine devvm makes carries the label `devvm.data=<devvm's data folder>`, and devvm lists, starts, stops, changes and deletes only the machines with its label. If one of your machines has a name devvm wants, devvm refuses with `smolvm_machine_foreign` and never touches it. devvm also runs smolvm with its usage journal off (`SMOLVM_USAGE=0`), and it never lets `SMOLVM_MACHINE_NAME` choose a machine.
|
||||
|
||||
On Linux, smolvm's state belongs to devvm alone, in `~/.local/share/devvm/smolvm/state`.
|
||||
|
||||
Images aren't machines. Each image is a pack (`smolvm pack create --from-vm`) in `~/.local/share/devvm/smolvm/images/<key>`. A project VM is a machine made from its image's pack, and the machine reads the pack when its disk grows, so devvm doesn't delete an image that a VM was made from (`image_in_use`). [Cleaning smolvm's caches](../backends/smolvm.md#cleaning-smolvms-caches) covers the packs' size and smolvm's own caches.
|
||||
|
||||
## Building images
|
||||
|
||||
`base` starts from Ubuntu's container image (`ubuntu:26.04`), by the digest devvm pins with base's package snapshot (`ContainerDigest` in `internal/ubuntu/ubuntu.go`). That digest is in base's key and its record. With `--from`, the build starts from that image by its recorded digest, and devvm refuses an image that only Docker has (`smolvm_from_registry_only`).
|
||||
|
||||
Before `assets/layers/base.sh` runs, devvm adds what Ubuntu's cloud image has and a container lacks: `sudo`, CA certificates, `bash` and the VM's user, and on Alpine also OpenRC and ssh's client. After base's scripts, it adds `sshd` without host keys, because each VM makes its own.
|
||||
|
||||
The VM's user has your user name and uid, as on Lima, with its home at `/home/<you>.guest`. The project folder shows as your uid's, and only that user can write it. The user has no password that works (`*`).
|
||||
|
||||
The scripts run as that user, with stand-ins for `systemctl` and `rc-update` while they run. Base's services are enabled the Lima way, and devvm starts them itself ([below](#no-init-system)). The stand-ins are gone before the image is packed.
|
||||
|
||||
Builds use smolvm's default network, which reaches the internet but not the host's loopback. A pack keeps its build machine's network, CPUs and memory, so devvm sets all three on every VM it makes. Base's CPUs, memory and disk come from `base.yaml`, which sets 4 CPUs, 8 GiB of memory and a 100 GiB disk. On a host with fewer than 4 CPUs, base and the VMs you give no size get as many CPUs as the host has, and when 8 GiB would leave the host less than 2 GiB, they get half of its memory ([base's size](images.md#bases-size)).
|
||||
|
||||
devvm's own scripts for these steps are in `base`'s key, together with the backend, so smolvm's images are never Lima's. They are `prepare.sh`, `shims.sh` and `sshd.sh`. `sshd.sh` installs sshd after base's scripts, from the Ubuntu snapshot they pin, and keeps the snapshot's package lists for layers.
|
||||
|
||||
When a build fails, devvm keeps its machine, stopped (`smolvm_script_failed`), so you can [look inside](../backends/smolvm.md#looking-inside).
|
||||
|
||||
## What devvm sets on a VM
|
||||
|
||||
- **Mounts:** devvm mounts the project folder (read-write) and agents' folders (read-only) at their host paths, and the shared tools at `/mnt/devvm-tools` (read-only). It also mounts `/var/lib/docker` on the machine's own disk, because the [docker layer](../using/images.md#built-in-layers)'s storage needs it. Every VM gets that mount. devvm refuses a path with a colon, because smolvm splits mounts on colons. Files a VM makes in the project folder are yours on the host, with mode 0600.
|
||||
- **Network:** without network policy, a VM has smolvm's own network, which reaches the internet but not the host's loopback. With network policy, devvm confines it as [below](#network-policy).
|
||||
- **Size:** a VM gets the size you ask for, or base's. Its disk only grows.
|
||||
- **Ports:** devvm's forwarder forwards them, and smolvm forwards none of them ([below](#ports)). The only port smolvm forwards is the VM's [ssh](#ssh-for-editors).
|
||||
- **SSH agent forwarding:** you choose it when the VM is made (`--ssh-agent`), and each start gives the VM an agent ([below](#ssh-agent-forwarding)).
|
||||
- **Environment:** with network policy, the VM gets the proxy's settings, as on Lima. The proxy variables come from the VM's proxy file, `proxy` in the VM's backend folder, `~/.local/share/devvm/vms/<hash>/backend/` (mode 600), which devvm writes at each start with network policy and removes at a start without it. Each of devvm's commands in the VM names the file (`smolvm machine exec --secret-file`) and smolvm reads it, so the proxy's password is in no process's arguments. A `smolvm machine exec` of your own gets the variables only in a login shell. `machine create --secret-file` would last, but smolvm ignores it for a VM made from a pack.
|
||||
|
||||
## Network policy
|
||||
|
||||
Network policy is emulated, and reviewed. A VM with [network policy](../safety/network.md) reaches only its proxy, as on Lima. devvm builds this from three parts, which it sets while the VM is stopped ([design](design.md#network-policy-on-smolvm)):
|
||||
|
||||
- **An allow list of the host alone** (`100.96.0.1/32`, the gateway). smolvm refuses connections anywhere else, and all UDP but DNS.
|
||||
- **DNS closed.** smolvm answers every query with `NXDOMAIN` itself, without asking anyone, and names resolve in the proxy instead. smolvm still asks your resolver about one name, `devvm.invalid`, because it needs that name to filter on. That's a narrow way out, as the VM chooses when and how to ask ([details](design.md#network-policy-on-smolvm)).
|
||||
- **devvm's proxy deciding each connection** (smolvm's mediated egress). Before smolvm connects anywhere, it asks the proxy. The proxy takes over connections to itself and refuses the rest, such as connections to the host's other ports, which `devvm network log` shows as a `BLOCKED` direct connection. The proxy's address in the VM is `http://100.96.0.1:<port>`.
|
||||
|
||||
The policy fails closed. With the proxy gone, nothing gets out, and once a VM has started this way, `smolvm machine start` refuses to start it without a decider. A VM that someone started with a decider of their own, or whose allow list someone widened while it runs, isn't confined, so devvm shows it as `unenforced` and stops it ([the self-check](network.md#the-self-check)). A UDP allow that someone adds (`smolvm machine update --allow-udp`) lets UDP past the decider, and smolvm doesn't show it, so don't add one to devvm's machines. `devvm network off` removes all three parts at the VM's next start.
|
||||
|
||||
## ssh for editors
|
||||
|
||||
ssh for editors is emulated, and reviewed. `devvm host`, `devvm code`, `--clone` and the [ssh config entries](../using/ssh.md#ssh-access-by-name) work as they do on Lima ([design](design.md#ssh-for-editors-on-smolvm)).
|
||||
|
||||
devvm starts an sshd of its own after each start of the VM ([below](#no-init-system)), with a config of devvm's own, `/etc/devvm/ssh/sshd_config`, which only root can change. The image's own sshd config doesn't apply.
|
||||
|
||||
The VM gets a new ed25519 host key at each start, so no two VMs made from one image share one. devvm reads the key through smolvm (`smolvm machine exec`), not over the network, and pins it in `~/.local/share/devvm/known_hosts`, as on Lima. ssh refuses a key that doesn't match.
|
||||
|
||||
Only the VM's own key logs in, and only as the VM's user. The key is `key` in the VM's backend folder, `~/.local/share/devvm/vms/<hash>/backend/` (mode 600), which devvm makes at the VM's first start with ssh. Its public half is that VM's only authorized key, so the key logs in to no other VM. Passwords, root and other users can't log in. The ssh config entries offer only that key (`IdentitiesOnly yes`), and never your agent's keys.
|
||||
|
||||
Port 22 in the VM is forwarded from a port on the host's `127.0.0.1` and `::1` alone. devvm chooses that port at the start and keeps it while it stays free on every address, so it's never one a program on the host has on any address, and never one of the VM's listed ports. If the port is one of them anyway, devvm refuses the start (`smolvm_ssh_port_forwarded`). With network policy, it's the port devvm records for the VM. The ssh config names the port, so connect by name. devvm answers for the port only once that start's sshd runs.
|
||||
|
||||
An ssh session gives the VM no way out as long as your ssh doesn't ask for one. A session can carry the VM's connections out only through what your machine's ssh asks for, such as remote forwards, X11, a tunnel or your agent. devvm's entry turns off X11, tunnels, remote SOCKS forwards and adding keys to an agent, whatever a `Host *` of yours says, and it asks for no remote forward. devvm can't turn off a `RemoteForward` of yours or an `ssh -R` you type, so don't forward into a VM you don't trust. The sshd also allows local forwarding (`ssh -L` and `-W`, which VS Code uses), where the VM makes the connection from its own network, so with network policy it reaches only the proxy. It allows remote forwards only on addresses in `127.77.0.0/16`, which devvm keeps for links between VMs, so a remote forward on the VM's `localhost` is refused. Those settings only protect an honest VM, because root in the VM can change its sshd.
|
||||
|
||||
Agent forwarding follows the entry, as on Lima. `ForwardAgent` is set by the [SSH agent](../using/ssh.md#agent-forwarding) choice that the VM's current start was made with. smolvm also forwards an agent of its own ([below](#ssh-agent-forwarding)).
|
||||
|
||||
Sessions get the same environment as devvm's own commands: `/etc/environment` and, with network policy, the proxy's settings, in a login shell or not.
|
||||
|
||||
A VM that has been running since a start without ssh gets no entry, and `devvm host` tells you to restart it (`vm_no_ssh`). A VM whose image has no sshd starts and runs without ssh, with a warning (`vm_no_sshd`). A VM made after `devvm rebuild` has it.
|
||||
|
||||
## Ports
|
||||
|
||||
Forwarding ports, every one or only the ones you list, is emulated, and reviewed ([design](design.md#ports-on-smolvm)). smolvm's own forwards reach only servers listening on all of the VM's addresses (`0.0.0.0`), and a machine has at most 64 of them. Each one also shares a port that a program on your machine has on every address (`SO_REUSEADDR`), and takes that program's `localhost` connections. So smolvm forwards none of a VM's ports, and devvm's forwarder runs on your machine instead, by the rules that [Port forwarding](ports.md) sets out for every backend.
|
||||
|
||||
Unlike smolvm's own forwards, devvm's forwarder also reaches servers on the VM's loopback (`127.0.0.1` or `::1`), both with every port (`--ports all`, the default) and with listed ones (`--ports 5173,8000-8010`).
|
||||
|
||||
The forwarder reaches the VM over its [ssh](#ssh-for-editors), with the VM's own key and the host key devvm read through smolvm. The VM sees each forwarded connection only as one to its own loopback, and with network policy it still reaches only its proxy.
|
||||
|
||||
Which ports a VM forwards is in devvm's record for the VM, so `devvm ports` changes the record and no forward of smolvm's. [Its process and files](ports.md#its-process-and-files) lists the record's path and the forwarder's log.
|
||||
|
||||
The forwarder starts after the VM's sshd and ends with it. When you change a running VM's ports, devvm starts it again with the new ones, unless the VM was started outside devvm since devvm last started it. Such a VM runs no sshd of devvm's, so devvm warns about that instead (`ports_no_ssh`). A VM without ssh, because its image has no sshd, forwards no ports, with the same warning.
|
||||
|
||||
## SSH agent forwarding
|
||||
|
||||
smolvm forwards an SSH agent into a VM made with `--ssh-agent` for as long as the VM runs, whether or not you're connected. The agent is at `/tmp/ssh-agent.sock` in the VM, and it reaches the agent that `SSH_AUTH_SOCK` names when the VM starts. smolvm sets forwarding only when it makes a VM, so devvm emulates turning it on or off later (`devvm ssh-agent on`, `devvm` or `off`), and the emulation is reviewed ([design](design.md#ssh-agent-toggling-on-smolvm)):
|
||||
|
||||
- **Every new VM is made forwarding,** and each start gives it the agent its choice names: yours (`SSH_AUTH_SOCK` in your shell), devvm's own, or none. If you chose yours and your shell has none, the start stops (`smolvm_no_agent`).
|
||||
- **None** is a path where no socket can be (`/dev/null/devvm-no-agent`). The VM's connections to its agent fail, so it lists no keys and can't add any.
|
||||
- **A change** applies from the VM's next start (`devvm restart`), to smolvm's agent, your shell and the ssh config's entry alike, as on Lima.
|
||||
- **A VM started outside devvm** gets the agent your shell has, whatever its choice, because `smolvm machine start` from your shell passes it on, and fails without one. When devvm, `devvm host`, `devvm code` or `devvm history export` finds the VM running on a process devvm didn't start, it stops the VM and says so (`agent_unchosen_stop`), unless the VM uses your agent anyway. The next devvm starts it with its own choice. Until then the VM has your shell's agent, so start devvm's VMs with devvm.
|
||||
- **A VM made without forwarding** can't have it turned on (`agent_fixed`). Run `devvm rm`, then `devvm --ssh-agent`.
|
||||
|
||||
## No init system
|
||||
|
||||
A machine runs its image as a container, and nothing starts at boot. After each start, devvm does these as root:
|
||||
|
||||
- It makes the loop devices that the shared tools are mounted with, because `/dev` has none, and then mounts the tools.
|
||||
- It starts the VM's [sshd](#ssh-for-editors) with new host keys, logging to `/var/log/devvm-sshd.log`.
|
||||
- In a VM with the [docker layer](../using/images.md#built-in-layers), it starts Docker's daemon in the background, logging to `/var/log/dockerd.log`, with its pid in `/run/docker.pid`. The layer's script also starts the daemon when you add the layer to a running VM. devvm's setup restarts it the same way when a launch changes the VM's [network policy](../safety/network.md) settings, which on Alpine the daemon reads from `/etc/conf.d/docker`. `/run` outlives a stop here, so the pid file can name a process that isn't Docker's daemon, which took the pid since. The start counts the daemon as running only when that process is named `dockerd`, and the restart stops only such a process. Both delete the pid file and Docker's run folder, `/run/docker`, before the daemon starts, as a boot would.
|
||||
- In a VM with the [nix layer](images.md#the-nix-layer), it starts Nix's daemon in the background, logging to `/var/log/nix-daemon.log`, with its pid in `/run/nix-daemon.pid`. The daemon reads its settings from `/etc/conf.d/nix-daemon`, which devvm's setup writes with the VM's proxy when network policy is on and removes when it's off, and the setup restarts the daemon when that file changes. The layer's script also starts the daemon when you add the layer to a running VM.
|
||||
|
||||
devvm's commands in a VM, such as its setup and your shell, run as the VM's user with the environment a login would give: `HOME`, `USER`, and `/etc/environment`, which smolvm doesn't read.
|
||||
|
||||
## File watchers
|
||||
|
||||
smolvm watches each mounted folder on the host, with FSEvents on macOS, and for each change it fires an event on the matching file in the VM, so watchers there see [your edits](../backends/smolvm.md#whats-different), though not your deletions, within about a tenth of a second, even on a busy host. An event for a new file names the file to a watch on its folder. An event for a change to an existing file reaches a watch on that file, but a watch on its folder gets only an event for the folder itself, without the file's name. A change made within a few seconds of the file's creation is the exception, because macOS still reports it together with the creation, and the folder's watch sees it as a new file.
|
||||
|
||||
## Shared tools
|
||||
|
||||
On smolvm, the shared tools are images of their own, in uncompressed EROFS, because smolvm's kernel mounts no other format. A tool image's key includes the format, so Lima's and smolvm's VMs each get their own tool images from the one share.
|
||||
@@ -59,7 +59,7 @@ flowchart TB
|
||||
| `.git` hooks and config | devvm locks them on macOS, and it reports what a lock can't stop without preventing it ([details](git-protection.md)). With `--clone` they're out of reach. |
|
||||
| Your agents' config (skills, settings, logins) | The VM mounts its folders read-only and gets copies of its files, but never your agents' history ([details](../using/coding-agents.md)). |
|
||||
| The rest of your home folder, other projects | The VM doesn't mount them. |
|
||||
| Your SSH keys | Only with `devvm ssh-agent on`, and only while you're connected, though on smolvm it's while the VM runs. With `devvm ssh-agent devvm`, the VM can use only the keys you added to devvm's own agent ([details](../using/ssh.md#agent-forwarding), [smolvm](../internals/smolvm.md#ssh-agent-forwarding)). |
|
||||
| Your SSH keys | Only with `devvm ssh-agent on`, and only while you're connected. With `devvm ssh-agent devvm`, the VM can use only the keys you added to devvm's own agent ([details](../using/ssh.md#agent-forwarding)). |
|
||||
| The network, with network policy | The VM reaches allowlisted hosts only, through a proxy on this machine ([details](network.md)). |
|
||||
| Your secrets, with network policy | Your GitHub token, Claude Code's token, Codex and opencode logins and Claude Code's MCP secrets stay on this machine, and the proxy puts them into requests ([details](network.md#secrets)). |
|
||||
| The network, without network policy | The VM reaches everything this machine reaches, including this machine's own services on `localhost`. |
|
||||
|
||||
@@ -37,10 +37,10 @@ Some protections hold only with [network policy](network.md) or only on macOS, a
|
||||
### Getting out over the network, with network policy
|
||||
|
||||
- **Sending data to the attacker's server.** Most attacks end by sending what they stole to a server the attacker runs. A VM with network policy reaches only its proxy, and the proxy allows only the hosts on the VM's allowlist. devvm leaves storage and paste sites out of the default allowlist on purpose, because they're easy ways to send data out ([allowlists](network.md#allowlists)).
|
||||
- **DNS tunnelling.** An attacker can encode data into names and look them up at a DNS server of their own. A VM sends no DNS queries of its own, because names resolve in the proxy on this machine. smolvm leaves [one narrow channel](#network).
|
||||
- **DNS tunnelling.** An attacker can encode data into names and look them up at a DNS server of their own. A VM sends no DNS queries of its own, because names resolve in the proxy on this machine.
|
||||
- **Services on this machine and your network.** Code in a VM could attack what developers leave open on `localhost`, such as databases, dev servers, Docker's API and other VMs' ports. It could also attack your router, a NAS, or a cloud provider's metadata service at `169.254.169.254`. The proxy refuses this machine's own addresses and internal ones, such as loopback, private, link-local and CGNAT ranges, unless a rule names the address ([the proxy](../internals/network.md#the-proxy)).
|
||||
- **DNS rebinding and address tricks.** A name can resolve to a public address when it's checked and to an internal one when it's dialed, and an internal address can hide in an IPv6 or NAT64 form. The proxy dials only the address it checked, and it sees through NAT64 forms ([the proxy](../internals/network.md#the-proxy)).
|
||||
- **Going around the proxy.** Root in a VM can change its routes and firewall, but devvm confines the VM from outside it, so nothing in the VM reaches anything but the proxy ([confinement](../internals/lima.md#confinement)). devvm catches a VM started outside devvm, or one given a second network, with [the self-check](../internals/network.md#the-self-check), and stops it. On smolvm, network policy is emulated and reviewed.
|
||||
- **Going around the proxy.** Root in a VM can change its routes and firewall, but devvm confines the VM from outside it, so nothing in the VM reaches anything but the proxy ([confinement](../internals/lima.md#confinement)). devvm catches a VM started outside devvm, or one given a second network, with [the self-check](../internals/network.md#the-self-check), and stops it.
|
||||
|
||||
### Spreading beyond the VM
|
||||
|
||||
@@ -84,7 +84,7 @@ The attacks in this section run the attacker's code, and devvm doesn't stop that
|
||||
|
||||
- **Worms that use your GitHub token.** Shai-Hulud (2025) spread through npm install scripts. It collected npm, GitHub and cloud credentials, then used them to publish repos and new versions of packages. A VM holds no npm or cloud credentials, and with network policy its GitHub token is a placeholder. The proxy still puts the real GitHub token into every request to GitHub's hosts, so a worm in the VM can push, make repos and do whatever else the GitHub token's scope allows. Use a fine-grained GitHub token scoped to the repos the VM needs, or bind none ([saving and binding secrets](network.md#saving-and-binding-secrets)).
|
||||
- **Minting credentials with a secret.** A VM that can use a secret can use it to make another credential that outlasts it. The proxy refuses GitHub REST calls that add an SSH key, a deploy key, a self-hosted runner or a webhook with `403`, but it can't refuse everything, such as GitHub's GraphQL API, an OAuth app grant or other services. If a VM may have done this, rotate the secret and check the service's keys, access tokens and runners.
|
||||
- **Your SSH agent.** While [agent forwarding](../using/ssh.md#agent-forwarding) is on, anything in the VM can use the agent's keys to push or log in to servers, though it can't copy them. The VM has the agent while you're connected, and on smolvm the whole time the VM runs. `devvm ssh-agent devvm` limits it to the keys you add to [devvm's own agent](../using/ssh.md#devvms-own-agent), and an agent that asks you to approve each use, such as 1Password's or Secretive, narrows it further.
|
||||
- **Your SSH agent.** While [agent forwarding](../using/ssh.md#agent-forwarding) is on, anything in the VM can use the agent's keys to push or log in to servers, though it can't copy them. The VM has the agent while you're connected. `devvm ssh-agent devvm` limits it to the keys you add to [devvm's own agent](../using/ssh.md#devvms-own-agent), and an agent that asks you to approve each use, such as 1Password's or Secretive, narrows it further.
|
||||
|
||||
### Git
|
||||
|
||||
@@ -94,7 +94,6 @@ The attacks in this section run the attacker's code, and devvm doesn't stop that
|
||||
### Network
|
||||
|
||||
- **Domain fronting.** The proxy checks the host name that a TLS connection asks for, but not the `Host` inside the encrypted traffic, so a CDN that serves many sites on one address can route an allowed connection to a site that isn't allowed. The proxy reads the connections to hosts with a bound secret, and it refuses a request in them that names another host.
|
||||
- **DNS from smolvm.** On the experimental [smolvm](../internals/smolvm.md#network-policy) backend, a VM's DNS answers only `devvm.invalid`, but smolvm still asks your resolver about that name, which is a narrow way out.
|
||||
- **Ports the VM listens on.** devvm forwards the VM's ports to this machine's `localhost`, so a VM could take a port that a program on this machine trusts while that port is free. devvm's forwarder never takes a port that a program on this machine already has, or one that devvm records for a VM, but a program that binds a port on all addresses after devvm forwarded it gets its `localhost` connections sent to the VM. `devvm ports` limits what a VM forwards, and `devvm ports none` forwards nothing ([ports](../using/ports-size.md#ports)).
|
||||
- **VS Code's relays.** Over Remote-SSH, VS Code forwards ports and answers git's prompts with your GitHub sign-in. devvm turns both off in the VM's VS Code settings, but the VM can turn them back on, so turn them off in your own VS Code settings as well ([VS Code](../using/ssh.md#vs-code)).
|
||||
|
||||
@@ -128,6 +127,6 @@ The VM can write anything in the project folder, and devvm locks only `.git`. An
|
||||
### The platform
|
||||
|
||||
- **`.git` on Linux hosts.** Linux has no flag a user can set to lock a file, so VMs on Linux hosts have no `.git` protection, and the VM can change hooks and config that run on the host. Use `--clone` there ([Linux hosts](git-protection.md#linux-hosts)).
|
||||
- **Escaping the VM.** A bug in Lima, Apple's Virtualization framework or QEMU, or on smolvm in smolvm or libkrun, could let code out of the VM.
|
||||
- **Escaping the VM.** A bug in Lima, Apple's Virtualization framework or QEMU could let code out of the VM.
|
||||
|
||||
Found a way out of a VM? See [SECURITY.md](https://github.com/w3cj/devvm/blob/main/SECURITY.md).
|
||||
@@ -187,9 +187,9 @@ The company proxy sees the name and port of every host the VM reaches, and if it
|
||||
|
||||
### Without network policy
|
||||
|
||||
A Lima VM without network policy gets your proxy settings in its environment when it starts and uses the company proxy directly, while smolvm VMs don't get them.
|
||||
A VM without network policy gets your proxy settings in its environment when it starts and uses the company proxy directly.
|
||||
|
||||
Builds never get your company proxy's settings, and images never keep them. When devvm builds an image, builds the shared tools or converts a `--from` container image on Lima behind a company proxy, the build goes through a proxy of devvm's on this machine, made for that build alone, which goes through your company proxy. The build's commands get only that proxy's address, with a password devvm makes for the build, while they run, and devvm stops the proxy when the build ends. So the code a build runs, which includes a container image's own, never sees your company proxy's address or password. That proxy also runs on this machine, so a company proxy on `localhost`, such as one a VPN client runs, works for builds too. smolvm builds don't get your proxy settings at all.
|
||||
Builds never get your company proxy's settings, and images never keep them. When devvm builds an image, builds the shared tools or converts a `--from` container image on Lima behind a company proxy, the build goes through a proxy of devvm's on this machine, made for that build alone, which goes through your company proxy. The build's commands get only that proxy's address, with a password devvm makes for the build, while they run, and devvm stops the proxy when the build ends. So the code a build runs, which includes a container image's own, never sees your company proxy's address or password. That proxy also runs on this machine, so a company proxy on `localhost`, such as one a VPN client runs, works for builds too.
|
||||
|
||||
A build's proxy allows any host, as `**` does. It sends a name that this machine can't look up on to the company proxy, so builds work where only the company proxy looks up outside names.
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ devvm setup --features omb,fzf,cli-tools,desktop
|
||||
|
||||
The new choice rebuilds `base`, and the images built on it, the next time they're used. A VM keeps the image it was made from, so a VM made before you chose the desktop has none, and `devvm desktop` says so. To give it one, save any work the VM holds outside the project folder, then run `devvm rm` and `devvm` to make a new VM.
|
||||
|
||||
The desktop works on every backend, Lima and smolvm, and on a base made `--from` a Debian, Ubuntu or Alpine image.
|
||||
The desktop works on base, and on a base made `--from` a Debian, Ubuntu or Alpine image.
|
||||
|
||||
## Opening it
|
||||
|
||||
|
||||
@@ -44,4 +44,4 @@ If the image's tag moves to another image while devvm builds, for example becaus
|
||||
|
||||
## Backends
|
||||
|
||||
Every backend can start `base` from a container image. Lima converts the image into a disk, and smolvm boots images that a registry gives it ([backends](../internals/backends.md#features)).
|
||||
Lima starts `base` from a container image by converting the image into a disk ([backends](../internals/backends.md#features)).
|
||||
@@ -47,13 +47,13 @@ The `docker` layer installs Docker's engine, CLI, BuildKit and Compose from Dock
|
||||
|
||||
The `nix` layer installs [Nix](https://nixos.org) with flakes and the `nix` command turned on, and [direnv](https://direnv.net) with [nix-direnv](https://github.com/nix-community/nix-direnv), so a project's `flake.nix`, `shell.nix` or `devenv.nix` can supply its toolchain. Each VM has a Nix store and daemon of its own, which no other VM and nothing on this machine shares. With network policy, VMs share their downloads from Nix's binary cache through a cache on this machine that only devvm fills. [Nix projects](toolchains.md#nix-projects) explains that cache, and how a flake's dev shell and the shared tools work together.
|
||||
|
||||
The `nix` layer works on Lima and smolvm, on a base from Ubuntu, Debian or Alpine. On a base made `--from alpine`, it installs Alpine's `xz` package, which isn't pinned, and runs Nix's daemon as an OpenRC service.
|
||||
The `nix` layer works on a base from Ubuntu, Debian or Alpine. On a base made `--from alpine`, it installs Alpine's `xz` package, which isn't pinned, and runs Nix's daemon as an OpenRC service.
|
||||
|
||||
## Shared tools
|
||||
|
||||
The toolchains and coding agents are shared tools, not image layers. A VM of any image can have them, in any mix, such as node, python and Claude Code on base, or go and Codex on `foo`. A VM's state lists its shared tools apart from its image. [Toolchains](toolchains.md) lists node, python, rust and go, with what each brings, and [supported agents](coding-agents.md#supported-agents) lists claude, codex and opencode.
|
||||
|
||||
devvm builds each tool version once and mounts it read-only into every VM that has it, so any mix of tools works without building anything new, and ten VMs with node share one copy of it. The builds are in `~/.local/share/devvm/tools`. Each backend and each C library gets a build of its own, so when a Lima VM and a smolvm VM both have node 24, or an Alpine VM has it too, `devvm images` lists more than one build of that version ([what devvm keeps](space.md#shared-tools)). [mise](https://mise.jdx.dev) runs the tools:
|
||||
devvm builds each tool version once and mounts it read-only into every VM that has it, so any mix of tools works without building anything new, and ten VMs with node share one copy of it. The builds are in `~/.local/share/devvm/tools`. Each backend and each C library gets a build of its own, so when an Alpine VM and an Ubuntu VM both have node 24, `devvm images` lists two builds of that version ([what devvm keeps](space.md#shared-tools)). [mise](https://mise.jdx.dev) runs the tools:
|
||||
|
||||
- **They work as usual.** `node`, `npm i -g` (into `~/.npm-global`), `pnpm`, `yarn`, `pip` and `uv`, `go install` (into `~/go/bin`) and `cargo` work from any shell, including `bash -c` from agents and from editors over SSH.
|
||||
- **A project's own version files win.** `.nvmrc`, `.node-version`, `.python-version`, `rust-toolchain.toml` and the `toolchain` line in `go.mod` pick their version, which installs into the VM the first time it's used. mise also reads a `mise.toml` in the project folder, and devvm trusts it without asking, because the folder is yours.
|
||||
@@ -209,8 +209,8 @@ After the tables, devvm says on stderr how many images are stale or unfinished a
|
||||
- `devvm gc --orphans` also deletes what devvm keeps for VMs that their backend no longer has, such as one you deleted with `limactl delete` instead of `devvm rm`, and with it the hold their state has on their shared tools ([leftovers](space.md#leftovers-of-a-vm-deleted-outside-devvm)).
|
||||
- `devvm gc --caches` then frees devvm's share of the backends' own caches, such as Lima's downloads of Ubuntu's cloud image, asking for each backend apart, or without asking with `--force`, which it needs without a terminal ([the backends' caches](space.md#the-backends-caches)).
|
||||
- `devvm gc --retention` then applies the [retention settings](settings.md#retention) at once, which devvm otherwise applies at most once a day. They're all off until you set them.
|
||||
- `devvm gc --backend NAME` acts on that backend alone, for example once you stop using smolvm. It deletes all of that backend's images, the current ones too, and its shared tools that are `unused`, and it leaves every other backend's images and devvm's own mise as they are. Without `--backend`, gc acts on every backend, whichever backend new VMs get by default. An image that a smolvm VM was made from stays, and devvm names the VMs that use it.
|
||||
- When a backend that one of your VMs uses can't list its images, for example because smolvm isn't installed, gc warns and leaves that backend's images, shared tools, VM leftovers and caches alone. It also leaves the shared tools whose record doesn't name the backend that built them, because they may be that backend's. gc goes on with the other backends and succeeds, so run `devvm doctor` to see what's wrong with that backend, then run gc again once it answers. `devvm images` fails instead, because it lists every backend's images or none.
|
||||
- `devvm gc --backend NAME` acts on that backend alone. It deletes all of that backend's images, the current ones too, and its shared tools that are `unused`, and it leaves devvm's own mise as it is. Without `--backend`, gc acts on every backend, whichever backend new VMs get by default.
|
||||
- When a backend that one of your VMs uses can't list its images, for example because Lima isn't installed, gc warns and leaves that backend's images, shared tools, VM leftovers and caches alone. It also leaves the shared tools whose record doesn't name the backend that built them, because they may be that backend's. gc still succeeds, so run `devvm doctor` to see what's wrong with that backend, then run gc again once it answers. `devvm images` fails instead, because it lists every backend's images or none.
|
||||
- gc never deletes VMs. Without `--backend` it keeps current images, and without `--tool-images` the current shared tools. It always keeps every shared tool that any VM has, including a stopped VM's and that of a VM deleted outside devvm whose state is left, until `--orphans` deletes that state.
|
||||
- On Linux hosts, a stale image whose disk VMs are overlays of stays, and devvm says which VMs use it.
|
||||
- After an Alpine VM is gone, the shared tools built for Alpine are unused, unless you give gc that `--from`.
|
||||
|
||||
@@ -24,12 +24,3 @@ These are the things devvm can't do, everywhere and then by host and backend.
|
||||
- Set-id bits that root in a VM sets on files in the project folder reach the host, and devvm names such files at each launch and stop ([what to do](troubleshooting.md#devvm-names-set-id-files)).
|
||||
- devvm keeps your secrets in files under `~/.local/share/devvm/secrets/`, which only you can read, instead of the Keychain ([details](settings.md#devvms-state)).
|
||||
- devvm has no Time Machine to keep its CA out of, so keep `~/.local/share/devvm/ca` out of your backups ([details](../internals/security.md#secrets-stay-on-the-host)).
|
||||
|
||||
## smolvm
|
||||
|
||||
smolvm is experimental.
|
||||
|
||||
- Network policy has one narrow way out, through DNS ([details](../internals/smolvm.md#network-policy)).
|
||||
- A VM that forwards your SSH agent has it the whole time it runs, not only while you're connected ([details](../backends/smolvm.md#whats-different)).
|
||||
- Project paths can't contain colons ([details](../backends/smolvm.md#whats-different)).
|
||||
- File watchers in a VM see the files you make on this machine, and a file you change when they watch that file itself and not only its folder, but they don't see the files you delete here ([details](../backends/smolvm.md#whats-different)).
|
||||
@@ -97,18 +97,18 @@ A VM's disk size is how far the disk can grow, not how much space it takes. A pr
|
||||
|
||||
Before devvm builds an image or makes a VM, it checks the free space on the disk that will hold it, and it refuses to start the step when there's less free than the step needs:
|
||||
|
||||
| Step | Lima on macOS | Lima on Linux | smolvm |
|
||||
| --- | --- | --- | --- |
|
||||
| building `base` | 8 GiB | 8 GiB | 4 GiB |
|
||||
| building any other image | 2 GiB | 8 GiB | 4 GiB |
|
||||
| building shared tool images | 3 GiB, and 0.5 GiB for each tool | 9 GiB, and 0.5 GiB for each tool | 4 GiB, and 0.5 GiB for each tool |
|
||||
| making a VM | 2 GiB | 2 GiB | 4 GiB |
|
||||
| Step | macOS | Linux |
|
||||
| --- | --- | --- |
|
||||
| building `base` | 8 GiB | 8 GiB |
|
||||
| building any other image | 2 GiB | 8 GiB |
|
||||
| building shared tool images | 3 GiB, and 0.5 GiB for each tool | 9 GiB, and 0.5 GiB for each tool |
|
||||
| making a VM | 2 GiB | 2 GiB |
|
||||
|
||||
devvm rounds each number up to whole GiB, so building one shared tool with Lima on macOS needs 4 GiB, and building all ten needs 8 GiB. Each build checks again before it starts, so the first VM on a Mac, which builds base, needs 8 GiB free.
|
||||
|
||||
The numbers leave a margin over what each step took when devvm's tests measured the free space before, during and after it. Most of a step's space is only needed while it runs. On Lima on macOS, base took about 1 GiB with Ubuntu's cloud image already downloaded, and downloading the image takes up to another 0.9 GiB. base's features add up to 2.5 GiB. A build of all ten shared tools took 6 GiB at its peak and kept 1.5 GiB of images. On macOS, an image built on another and a new VM take only what they write. On Linux hosts, an image and the VM that builds shared tools start as a full copy of their parent's disk, but a new VM's disk holds only its own changes. On smolvm, building base or the docker layer, and making a VM from the docker layer, each took about 2 GiB while it ran but kept less than 0.5 GiB, so its numbers are the same for every step. A VM then grows as you work in it, and its disk never shrinks.
|
||||
The numbers leave a margin over what each step took when devvm's tests measured the free space before, during and after it. Most of a step's space is only needed while it runs. On Lima on macOS, base took about 1 GiB with Ubuntu's cloud image already downloaded, and downloading the image takes up to another 0.9 GiB. base's features add up to 2.5 GiB. A build of all ten shared tools took 6 GiB at its peak and kept 1.5 GiB of images. On macOS, an image built on another and a new VM take only what they write. On Linux hosts, an image and the VM that builds shared tools start as a full copy of their parent's disk, but a new VM's disk holds only its own changes. A VM then grows as you work in it, and its disk never shrinks.
|
||||
|
||||
devvm checks the disk that holds the backend's images and VMs. On Lima, that's the disk of devvm's Lima home. On smolvm, it's the disk of devvm's data folder, and on macOS also that of your home folder, where smolvm keeps its machines. Shared tool images come out into devvm's data folder on every backend, so a tools build also checks that folder's disk, which needs 0.5 GiB and 0.25 GiB for each tool, rounded up: 1 GiB for one tool and 3 GiB for all ten. When devvm's data folder is on a small temporary disk, such as a tmpfs `/tmp` on Linux, devvm checks that disk.
|
||||
devvm checks the disk that holds the images and VMs, which is the disk of devvm's Lima home. Shared tool images come out into devvm's data folder, so a tools build also checks that folder's disk, which needs 0.5 GiB and 0.25 GiB for each tool, rounded up: 1 GiB for one tool and 3 GiB for all ten. When devvm's data folder is on a small temporary disk, such as a tmpfs `/tmp` on Linux, devvm checks that disk.
|
||||
|
||||
`devvm doctor` also warns when that disk has less free space than building base needs, but the warning doesn't make doctor fail. When devvm refuses, see [Not enough free space](troubleshooting.md#not-enough-free-space) for how to make room.
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ Upgrading devvm keeps this folder as it is. Back it up, such as in a dotfiles re
|
||||
`~/.config/devvm/config.toml` sets the defaults that new VMs get, and the retention settings, in a file you write by hand. devvm reads it and never writes it. Every key is optional, and devvm has no `config.toml` until you write one. This example sets every key:
|
||||
|
||||
```toml
|
||||
# The backend new VMs get: lima or smolvm.
|
||||
# The backend new VMs get: lima.
|
||||
backend = "lima"
|
||||
|
||||
# Whether new VMs get network policy: ask, on or off.
|
||||
@@ -97,7 +97,7 @@ devvm reads all of `config.toml` each time it needs a default, and it checks eve
|
||||
|
||||
```sh
|
||||
devvm setup # asks all five questions
|
||||
devvm setup --backend smolvm # the default backend, without asking
|
||||
devvm setup --backend lima # the default backend, without asking
|
||||
devvm setup --features fzf,omb # base's features, without asking
|
||||
devvm setup --features none # base gets no features
|
||||
devvm setup --agents claude,codex # new VMs' coding agents, without asking
|
||||
|
||||
@@ -23,7 +23,7 @@ Sizes count each file's blocks once, as `du` does. On macOS a Lima VM's disk sha
|
||||
|
||||
### The backends' caches
|
||||
|
||||
The second table lists the caches that belong to the backends, with the backend, what each cache holds, how many entries it has, its size and where it is. These are Lima's download cache and smolvm's caches on macOS. devvm's builds fill them, but they can also hold your own downloads, so they aren't in the total. The sections below say what each one holds.
|
||||
The second table lists the caches that belong to the backends, with the backend, what each cache holds, how many entries it has, its size and where it is. That's Lima's download cache. devvm's builds fill them, but they can also hold your own downloads, so they aren't in the total. The sections below say what each one holds.
|
||||
|
||||
devvm never prunes these caches on its own. `devvm gc --caches` frees devvm's share of them, which is what devvm's builds put there and nothing of devvm's needs. For each backend in turn, it lists the entries it would delete with their sizes and asks. Without a terminal it refuses unless you give `--force`, which frees them without asking. With `--backend NAME`, it asks only about that backend's cache.
|
||||
|
||||
@@ -113,9 +113,8 @@ devvm keeps its state in `~/.local/share/devvm`, or in `$XDG_DATA_HOME/devvm` wh
|
||||
| `making.lock` | an empty file that each devvm making a VM locks, so that `devvm gc --tool-images` can tell a VM is [being made](images.md#cleaning-up) | it stays, and takes no space |
|
||||
| `retention.lock` | an empty file that the devvm applying the [retention settings](settings.md#retention) locks, so that one at a time applies them | it stays, and takes no space |
|
||||
| `lima/` | devvm's own [Lima home](../backends/lima.md#devvms-lima-home), with its VMs and images, unless `DEVVM_LIMA_HOME` moves it | see [Lima](#lima) |
|
||||
| `smolvm/` | the smolvm backend's images, which are packs | see [smolvm](#smolvm) |
|
||||
|
||||
What a backend sets on each VM is in the VM's own folder, in `vms/<hash>/backend/`. For a Lima VM that's which ports it forwards and its port forwarder's files, and for a smolvm VM it's what the backend set on the VM, the ssh key devvm logs in with and the port forwarder's files. `devvm rm` deletes them with the VM.
|
||||
What the backend sets on each VM is in the VM's own folder, in `vms/<hash>/backend/`: which ports it forwards and its port forwarder's files. `devvm rm` deletes them with the VM.
|
||||
|
||||
The [retention settings](settings.md#retention), which are all off until you set them, make devvm delete some of these on its own: `logs.runs` keeps that many run logs instead of 20, `history.age` and `history.count` delete old exports of agents' history, `tools.unused-age` deletes current shared tools that no VM has had for that long, and `orphans.age` forgets VMs that their backend no longer has. `nix-cache.size` sets the shared Nix cache's cap, and each time retention runs, it deletes the cache's least recently used files while it takes more than that. Retention also writes `retention.run` in the data folder, when it last ran, and records in each current shared tool's record since when no VM has had it. It never deletes anything in `cache/` but the shared Nix cache's files.
|
||||
|
||||
@@ -123,7 +122,7 @@ A build also makes a temporary folder in the data folder, `tools-build.<random>`
|
||||
|
||||
### Shared tools
|
||||
|
||||
Each tool version is built once for each kind of VM that uses it, so `tools/` can hold more than one build of the same version. Lima's VMs mount compressed images, and smolvm's need uncompressed ones. A base on Alpine also needs its tools built for its C library, musl, rather than glibc. A node 24 that both a Lima VM and a smolvm VM use is therefore two builds, and `devvm images` lists both. [Cleaning up](images.md#cleaning-up) says which ones `devvm gc` deletes.
|
||||
Each tool version is built once for each kind of VM that uses it, so `tools/` can hold more than one build of the same version. A base on Alpine needs its tools built for its C library, musl, rather than glibc, so a node 24 that both an Ubuntu VM and an Alpine VM use is two builds, and `devvm images` lists both. [Cleaning up](images.md#cleaning-up) says which ones `devvm gc` deletes.
|
||||
|
||||
### Exports
|
||||
|
||||
@@ -131,12 +130,12 @@ Each tool version is built once for each kind of VM that uses it, so `tools/` ca
|
||||
|
||||
### Leftovers of a VM deleted outside devvm
|
||||
|
||||
When you delete a VM with its backend's own command instead of `devvm rm`, such as `limactl delete` or `smolvm machine delete`, devvm still keeps the VM's folder, with its state, its logs and its backend's files, the VM's sockets in `run/`, its ssh config entry and its host keys. `devvm gc` also keeps the shared tools that the VM's state names. `devvm rm` deletes these only together with the VM, so once the VM is gone it says the folder has no VM.
|
||||
When you delete a VM with its backend's own command instead of `devvm rm`, such as `limactl delete`, devvm still keeps the VM's folder, with its state, its logs and its backend's files, the VM's sockets in `run/`, its ssh config entry and its host keys. `devvm gc` also keeps the shared tools that the VM's state names. `devvm rm` deletes these only together with the VM, so once the VM is gone it says the folder has no VM.
|
||||
|
||||
`devvm gc --orphans` deletes what devvm keeps for such a VM, as `devvm rm` does after it deletes a VM. That includes, for a `--clone` VM, the `devvm` remote in your repo. gc first asks each VM's backend whether it still has the VM, lists the VMs it would forget with their project folders, and in a terminal asks. It never deletes a VM, and it leaves a VM's state alone in these cases, saying why:
|
||||
|
||||
- **The backend doesn't answer**, for example because it isn't installed. When a backend that one of your VMs uses can't list its images, gc warns and leaves all of that backend's VMs' state alone, as it does the rest of that backend's ([cleaning up](images.md#cleaning-up)).
|
||||
- **The VM was made elsewhere.** devvm records where each new VM's backend keeps it: the Lima home, which `DEVVM_LIMA_HOME` moves, or your home folder for smolvm on macOS. When this run looks somewhere else, the VM may still exist there. A VM whose state doesn't record it counts as made in the backend's default place, so while `DEVVM_LIMA_HOME` is set, gc leaves such a VM alone.
|
||||
- **The VM was made elsewhere.** devvm records where each new VM's backend keeps it: the Lima home, which `DEVVM_LIMA_HOME` moves. When this run looks somewhere else, the VM may still exist there. A VM whose state doesn't record it counts as made in the backend's default place, so while `DEVVM_LIMA_HOME` is set, gc leaves such a VM alone.
|
||||
- **Its state changed in the last hour,** because the VM may still be being made.
|
||||
|
||||
Forgetting a VM also removes your other VMs' [links](links.md) to it, as `devvm rm` does. `devvm gc --orphans` also removes links to VMs whose state is already gone, naming each one, and deletes the sockets that a link session leaves on your machine when it's killed, which are the ones nothing listens on.
|
||||
@@ -145,7 +144,7 @@ Once a VM's state is gone, `devvm gc` treats its shared tools like any others. `
|
||||
|
||||
### VMs devvm has no state for
|
||||
|
||||
A VM can also be the other way around: the backend has it, with devvm's label, but devvm has no state for it. Usually it belongs to another devvm, such as one run with another `XDG_DATA_HOME` for a test or a sandbox, which on macOS shares your smolvm machines. `devvm space` names each one, with the data folder its label names, and devvm never deletes it, because the other devvm may still use it. To delete one yourself, run `smolvm machine delete --name NAME` for smolvm, or `devvm limactl delete NAME` for Lima.
|
||||
A VM can also be the other way around: the backend has it, with devvm's label, but devvm has no state for it. Usually it belongs to another devvm, such as one run with another `XDG_DATA_HOME` for a test or a sandbox. `devvm space` names each one, with the data folder its label names, and devvm never deletes it, because the other devvm may still use it. To delete one yourself, run `devvm limactl delete NAME`.
|
||||
|
||||
## Your settings
|
||||
|
||||
@@ -157,12 +156,6 @@ The Lima backend's VMs and images are in devvm's Lima home, `~/.local/share/devv
|
||||
|
||||
Lima keeps a download cache of its own, `~/Library/Caches/lima` on macOS and `~/.cache/lima` on Linux, or `$XDG_CACHE_HOME/lima` when `XDG_CACHE_HOME` is set. When devvm builds base, Lima downloads Ubuntu's cloud image into that cache, which is 600 to 900 MB for each release, and on macOS it also keeps a copy converted to a raw disk, which takes about 2.4 GB more. The cache is Lima's and it isn't in devvm's Lima home, so your own Lima VMs' downloads share it. devvm deletes something in it only when you run `devvm gc --caches`. Lima keeps each download in a folder named by the SHA-256 of its address, and gc frees only the folders of Ubuntu's cloud images at the address devvm downloads base from, for its Ubuntu release, that no image record of devvm's names and that haven't changed in the last hour. A cloud image that one of your own Lima VMs downloaded from that same address can be among them, and Lima downloads it again the next time it needs it. No VM needs its entry once it's made, because Lima copies the disk out of the cache. `limactl prune` deletes the whole cache, your own downloads included, so devvm never runs it.
|
||||
|
||||
## smolvm
|
||||
|
||||
The smolvm backend keeps each image as a pack in `~/.local/share/devvm/smolvm/images/<key>`, and base's is about 450 MB. A VM is a smolvm machine made from its image's pack. The machine reads the pack when its disk grows, so devvm doesn't delete an image that a VM was made from. What devvm sets on each VM is in the VM's folder, in `vms/<hash>/backend/`. `devvm rm` deletes a VM, `devvm gc` and `devvm images rm` delete images, and `devvm gc --backend smolvm` deletes all of them but those a VM was made from.
|
||||
|
||||
On macOS, smolvm keeps every machine, devvm's and your own, in its own folders under `~/Library/Caches/smolvm`, and devvm marks its machines with a label. That folder also holds smolvm's caches, which grow with every pack that a machine is made from. smolvm unpacks a pack's disk once, which takes 1 to 3 GB, and keeps it for the next machine made from that pack. Those copies stay after devvm deletes the pack. Each one's name holds the SHA-256 of its pack, and devvm records the SHA-256 of every pack it makes, so `devvm gc --caches` frees the copies of devvm's packs that no machine of devvm's was made from and that haven't changed in the last hour. A copy whose pack is gone and isn't in that record can't be tied to devvm, so it stays, as do the copies of your own packs and smolvm's other caches. Because the folder also holds the machines' own disks, never delete it by hand. [Cleaning smolvm's caches](../backends/smolvm.md#cleaning-smolvms-caches) says what smolvm's own commands clean. On Linux, smolvm's state and caches belong to devvm alone, in `~/.local/share/devvm/smolvm/state`.
|
||||
|
||||
## Outside devvm's folders
|
||||
|
||||
devvm also changes a few things outside its own folders:
|
||||
|
||||
@@ -41,17 +41,17 @@ The VM can change that file back, so for a VM you don't trust, also set the thre
|
||||
|
||||
## Agent forwarding
|
||||
|
||||
SSH agent forwarding is off by default. While it's on and you're connected, or on smolvm whenever the VM runs, anything in the VM, coding agents included, can *use* the agent's keys, for example to push or to log in to servers. It can't copy them. Turn it on for one VM when you need git over SSH there.
|
||||
SSH agent forwarding is off by default. While it's on and you're connected, anything in the VM, coding agents included, can *use* the agent's keys, for example to push or to log in to servers. It can't copy them. Turn it on for one VM when you need git over SSH there.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
choice{{"devvm ssh-agent"}}
|
||||
choice -- "off, the default" --> off["no agent:<br>git over SSH fails"]
|
||||
choice -- "on" --> on["your agent, while<br>you're connected,<br>or on smolvm while<br>the VM runs"]
|
||||
choice -- "on" --> on["your agent, while<br>you're connected"]
|
||||
choice -- "devvm" --> own["devvm's own agent,<br>with only the keys<br>you added"]
|
||||
```
|
||||
|
||||
- `devvm --ssh-agent` creates the VM forwarding your agent. `devvm ssh-agent on`, `devvm` or `off` changes it for an existing VM from its next start, which for a running VM is `devvm restart`, and `devvm ssh-agent` shows it. On smolvm, the VM has the agent the whole time it runs, not only while you're connected ([smolvm](../internals/smolvm.md#ssh-agent-forwarding)).
|
||||
- `devvm --ssh-agent` creates the VM forwarding your agent. `devvm ssh-agent on`, `devvm` or `off` changes it for an existing VM from its next start, which for a running VM is `devvm restart`, and `devvm ssh-agent` shows it.
|
||||
- The choice applies to devvm's shells and to the ssh entries alike, both as the VM's current start was made with, so a change reaches neither until the VM next starts, whichever folder devvm runs from. For a VM started outside devvm, such as with `limactl start`, they follow the current choice. When forwarding is off, an entry says `ForwardAgent no`, whatever your own `Host *` settings say, and none of devvm's own connections to the VM carry your agent.
|
||||
- With forwarding off, git over SSH in the VM fails. devvm says so when it creates a VM for a repo whose `origin` is an SSH URL. Use an HTTPS remote with a GitHub token instead, or turn forwarding on.
|
||||
- **No keys loaded.** When a VM forwards your agent, the agent has no keys and `~/.ssh` has one, devvm offers to load it (`ssh-add --apple-use-keychain` on macOS). To keep it loaded across reboots, add `AddKeysToAgent yes`, and `UseKeychain yes` on macOS, under `Host *` in `~/.ssh/config`.
|
||||
|
||||
@@ -56,7 +56,7 @@ A project whose toolchain comes from Nix gets the [`nix` layer](images.md#nix),
|
||||
|
||||
### Sharing a team's packages
|
||||
|
||||
When your team's projects use one flake for their dev shell, you can put that dev shell's packages into an image, so every VM made from the image starts with them in its store and downloads none of them. VMs made from one image share its disk, because on macOS each VM's disk is a copy-on-write clone of the image's, and on Linux hosts it's an overlay of the image's, so the packages take their space once. This works with the stable Nix that the `nix` layer installs, with network policy or without it, on every backend that has the `nix` layer, which are Lima and smolvm.
|
||||
When your team's projects use one flake for their dev shell, you can put that dev shell's packages into an image, so every VM made from the image starts with them in its store and downloads none of them. VMs made from one image share its disk, because on macOS each VM's disk is a copy-on-write clone of the image's, and on Linux hosts it's an overlay of the image's, so the packages take their space once. This works with the stable Nix that the `nix` layer installs, with network policy or without it.
|
||||
|
||||
To do it, make a [layer of your own](customizing.md#your-own-layers) that builds the dev shell while the image builds, and give it after `nix`, so that it runs on top of the `nix` layer:
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ When an image's build fails in its script, or as the build VM starts or stops, d
|
||||
devvm limactl shell --start devvm-img-<key>
|
||||
```
|
||||
|
||||
`--start` starts the VM first, outside the build's confinement. On smolvm, start and open the machine with smolvm's own commands ([looking inside](../backends/smolvm.md#looking-inside)).
|
||||
`--start` starts the VM first, outside the build's confinement.
|
||||
|
||||
The next build of that image deletes the VM and starts over, and `devvm gc` also deletes it. A build whose create or clone fails deletes the image, once devvm has shown the end of the log, because there's nothing in the image to look at.
|
||||
|
||||
@@ -57,7 +57,7 @@ Either way, the images under it, which are already built, stay. devvm deletes an
|
||||
|
||||
## Not enough free space
|
||||
|
||||
Before each build and each new VM, devvm checks the free space on the disk that will hold it, and it refuses when there's less than the step needs. With Lima on macOS, that's 8 GiB for base, 2 GiB for another image or a VM, and from 4 GiB for one shared tool to 8 GiB for all ten, and [free space](ports-size.md#free-space) gives the numbers for Linux hosts and smolvm. The message says which folder's disk it checked, how much is free and how much the step needs. Nothing has been built or made yet, so you can make room and run the same command again:
|
||||
Before each build and each new VM, devvm checks the free space on the disk that will hold it, and it refuses when there's less than the step needs. With Lima on macOS, that's 8 GiB for base, 2 GiB for another image or a VM, and from 4 GiB for one shared tool to 8 GiB for all ten, and [free space](ports-size.md#free-space) gives the numbers for Linux hosts. The message says which folder's disk it checked, how much is free and how much the step needs. Nothing has been built or made yet, so you can make room and run the same command again:
|
||||
|
||||
- `devvm gc` deletes stale and unfinished images and unused shared tool images ([cleaning up](images.md#cleaning-up)).
|
||||
- `devvm images` lists the images and shared tool images with the space each takes, and `devvm images rm` deletes those you don't need ([deleting images](images.md#deleting-images)).
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Package backend is what runs devvm's VMs: one interface every backend
|
||||
// implements (Lima, smolvm), the features each one has (Caps), the
|
||||
// implements (Lima's), the features each one has (Caps), the
|
||||
// registry of backends and the choice of backend for a VM.
|
||||
//
|
||||
// A backend only runs what it's told. What a VM is made of (its image, its
|
||||
@@ -102,8 +102,8 @@ type Backend interface {
|
||||
SetSize(ctx context.Context, vm string, s Size) error
|
||||
// SetPorts changes which of a VM's ports are forwarded: a stopped
|
||||
// VM's from its next start, a running one's at once, its forwarder
|
||||
// started again as Start starts it with c (HostKey, ProxyPort,
|
||||
// Decider, Free) while the VM runs on. Connections open through its
|
||||
// started again as Start starts it with c (HostKey, ProxyPort, Free)
|
||||
// while the VM runs on. Connections open through its
|
||||
// old forwarder end.
|
||||
SetPorts(ctx context.Context, vm string, p Ports, c Confinement) error
|
||||
// SetAgentDirs replaces a stopped VM's agent folder mounts.
|
||||
@@ -120,44 +120,6 @@ type KeyFiles interface {
|
||||
KeyFiles() map[string][]byte
|
||||
}
|
||||
|
||||
// Decider is a backend that confines a VM with network policy by asking
|
||||
// devvm's proxy about each connection the VM opens (smolvm's mediated
|
||||
// egress): the proxy's decider takes over only those to the proxy's address
|
||||
// in the VM (ProxyURL's host and port) and refuses the rest. Start with
|
||||
// NetProxy then needs Confinement's Decider and DeciderToken. A backend that
|
||||
// confines VMs some other way doesn't implement it.
|
||||
type Decider interface {
|
||||
UsesDecider() bool
|
||||
}
|
||||
|
||||
// UsesDecider reports whether b confines VMs through devvm's decider.
|
||||
func UsesDecider(b Backend) bool {
|
||||
d, ok := b.(Decider)
|
||||
return ok && d.UsesDecider()
|
||||
}
|
||||
|
||||
// AgentStarter is a backend whose VM forwards whatever SSH agent the
|
||||
// command that starts it names (smolvm's machine start), so a VM started
|
||||
// some other way than by Start can have one devvm didn't choose for it. A
|
||||
// backend whose agent is the VM's config, or fixed when it's made,
|
||||
// doesn't implement it.
|
||||
type AgentStarter interface {
|
||||
// AgentUnchosen reports whether a running VM may forward an agent
|
||||
// devvm didn't choose: made forwarding one, and not running on the
|
||||
// process Start last started.
|
||||
AgentUnchosen(ctx context.Context, vm string) (bool, error)
|
||||
}
|
||||
|
||||
// AgentUnchosen reports whether b's running VM may forward an agent devvm
|
||||
// didn't choose for it (AgentStarter); never on other backends.
|
||||
func AgentUnchosen(ctx context.Context, b Backend, vm string) (bool, error) {
|
||||
a, ok := b.(AgentStarter)
|
||||
if !ok {
|
||||
return false, nil
|
||||
}
|
||||
return a.AgentUnchosen(ctx, vm)
|
||||
}
|
||||
|
||||
// Problem is something a backend needs that the host lacks, as devvm
|
||||
// doctor reports it.
|
||||
type Problem struct {
|
||||
@@ -319,11 +281,6 @@ type Confinement struct {
|
||||
// password the guest's proxy settings carry, with ProxyUser (ProxyURL).
|
||||
ProxyPort int
|
||||
ProxyPassword string
|
||||
// NetProxy on a backend with a decider (Decider): the proxy's decider,
|
||||
// on host loopback (127.0.0.1:PORT), and the token, 64 hex digits, the
|
||||
// backend proves itself to it with. Never in the VM.
|
||||
Decider string
|
||||
DeciderToken string
|
||||
// Env is more guest environment, for every login (the proxy's CA
|
||||
// files, NO_PROXY).
|
||||
Env map[string]string
|
||||
|
||||
@@ -40,7 +40,6 @@ type Fake struct {
|
||||
LifelineFile string // Lifeline's answer
|
||||
Missing []backend.Problem // Problems' answer
|
||||
Format string // ToolFormat's answer
|
||||
Decides bool // UsesDecider's answer
|
||||
// ExecFunc, when set, is what Exec returns after recording the call
|
||||
// (Errs aside).
|
||||
ExecFunc func(vm string, argv []string, o backend.ExecOpts) error
|
||||
@@ -340,9 +339,6 @@ func (f *Fake) bump(vm string) {
|
||||
f.starts[vm]++
|
||||
}
|
||||
|
||||
// UsesDecider returns Decides.
|
||||
func (f *Fake) UsesDecider() bool { return f.Decides }
|
||||
|
||||
// ProxyURL returns the proxy at proxy.test on c's port, with its user and
|
||||
// password.
|
||||
func (f *Fake) ProxyURL(c backend.Confinement) string {
|
||||
|
||||
@@ -103,7 +103,7 @@ type Caps map[Feature]Support
|
||||
// refuses every unreviewed emulation.
|
||||
type Review struct {
|
||||
// Unreviewed is the unreviewed emulations Require lets through anyway,
|
||||
// as backend:feature (smolvm:egress-proxy): for the end-to-end checks
|
||||
// as backend:feature (lima:ports): for the end-to-end checks
|
||||
// that an emulation's review needs, which set DEVVM_UNREVIEWED.
|
||||
Unreviewed map[string]bool
|
||||
// Warn is told each time one is let through.
|
||||
|
||||
@@ -37,8 +37,7 @@ func count(n int) uint64 {
|
||||
// devvm's data folder, where the images come out on every backend: the
|
||||
// images alone, measured with statfs (the folder on its own tmpfs: 184 MB
|
||||
// for claude, 194 MB for node, pnpm and bun). Ten tools came to 1.5 GiB as images on Lima, rust alone, the largest,
|
||||
// to 0.6 GiB, and seven to 2.6 GiB uncompressed for smolvm, whose own
|
||||
// floors are checked on that disk too.
|
||||
// to 0.6 GiB.
|
||||
func ToolImages(n int) uint64 { return 512<<20 + count(n)*(256<<20) }
|
||||
|
||||
// Storage is a backend whose images and VMs are files on the host's own
|
||||
|
||||
@@ -7,8 +7,7 @@ import (
|
||||
)
|
||||
|
||||
// Locator is a backend whose VMs live somewhere that can change between
|
||||
// runs of devvm: Lima's home (DEVVM_LIMA_HOME), smolvm's user on macOS
|
||||
// (HOME). A VM records
|
||||
// runs of devvm: Lima's home (DEVVM_LIMA_HOME). A VM records
|
||||
// where it was made (LocationOf), so a run that looks elsewhere never
|
||||
// takes it for one its backend lost. A backend whose VMs can't move
|
||||
// doesn't implement it.
|
||||
|
||||
@@ -135,5 +135,5 @@ func (r *Registry) For(d paths.Dirs, vm *state.VM, flag string) (Choice, error)
|
||||
return Choice{Backend: b}, nil
|
||||
}
|
||||
|
||||
// list is the backends' names for a message: lima, smolvm.
|
||||
// list is the backends' names for a message: lima, qemu.
|
||||
func (r *Registry) list() string { return strings.Join(r.Names(), ", ") }
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
|
||||
"github.com/w3cj/devvm/internal/backend"
|
||||
"github.com/w3cj/devvm/internal/backend/lima"
|
||||
"github.com/w3cj/devvm/internal/backend/smolvm"
|
||||
"github.com/w3cj/devvm/internal/paths"
|
||||
"github.com/w3cj/devvm/internal/platform"
|
||||
"github.com/w3cj/devvm/internal/settings"
|
||||
@@ -32,20 +31,19 @@ type Overrides struct {
|
||||
// UI is what every backend needs of devvm's UI.
|
||||
type UI interface {
|
||||
lima.UI
|
||||
smolvm.UI
|
||||
}
|
||||
|
||||
// New returns the registry of devvm's backends, on devvm's folders, its
|
||||
// own files (assets) and u: lima, the default (backend.Default), and
|
||||
// smolvm (experimental), with a test build's overrides o in place of their
|
||||
// own. The registry's Host is o's (platform.NewHost).
|
||||
// own files (assets) and u: lima, the default (backend.Default), with a
|
||||
// test build's overrides o in place of its own. The registry's Host is
|
||||
// o's (platform.NewHost).
|
||||
func New(d paths.Dirs, assets fs.FS, u UI, o Overrides) (*backend.Registry, error) {
|
||||
host := platform.NewHost(o.Host)
|
||||
l, s := lima.New(d, assets, u, host, o.UbuntuURL), smolvm.New(d, assets, u, host)
|
||||
l := lima.New(d, assets, u, host, o.UbuntuURL)
|
||||
if o.KVM != "" {
|
||||
l.KVM, s.KVM = o.KVM, o.KVM
|
||||
l.KVM = o.KVM
|
||||
}
|
||||
r, err := backend.NewRegistry(l, s)
|
||||
r, err := backend.NewRegistry(l)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -66,8 +64,4 @@ func defaultBackend(d paths.Dirs) (name, file string, err error) {
|
||||
|
||||
// Names are every backend's name, sorted, as New registers them: what
|
||||
// --backend takes.
|
||||
func Names() []string { return []string{lima.Name, smolvm.Name} }
|
||||
|
||||
// Experimental reports whether the backend by that name is experimental:
|
||||
// smolvm.
|
||||
func Experimental(name string) bool { return name == smolvm.Name }
|
||||
func Names() []string { return []string{lima.Name} }
|
||||
@@ -12,7 +12,6 @@ import (
|
||||
"github.com/w3cj/devvm/assets"
|
||||
"github.com/w3cj/devvm/internal/backend"
|
||||
"github.com/w3cj/devvm/internal/backend/lima"
|
||||
"github.com/w3cj/devvm/internal/backend/smolvm"
|
||||
"github.com/w3cj/devvm/internal/backend/vmssh"
|
||||
"github.com/w3cj/devvm/internal/msg"
|
||||
"github.com/w3cj/devvm/internal/paths"
|
||||
@@ -40,7 +39,7 @@ func (quietUI) StdinIsTerminal() bool { retu
|
||||
// them, the backends keep their own, whatever the environment says.
|
||||
func TestOverrides(t *testing.T) {
|
||||
for k, v := range map[string]string{
|
||||
"DEVVM_KVM": "/x/kvm", "DEVVM_UBUNTU_URL": "file:///x/ubuntu", "DEVVM_UNREVIEWED": "smolvm:egress-proxy",
|
||||
"DEVVM_KVM": "/x/kvm", "DEVVM_UBUNTU_URL": "file:///x/ubuntu", "DEVVM_UNREVIEWED": "lima:egress-proxy",
|
||||
platform.TestCPUs: "1234",
|
||||
} {
|
||||
t.Setenv(k, v)
|
||||
@@ -48,7 +47,7 @@ func TestOverrides(t *testing.T) {
|
||||
d := paths.Dirs{Data: t.TempDir(), Config: t.TempDir(), Lima: t.TempDir()}
|
||||
o := Overrides{
|
||||
Host: platform.Overrides{CPUs: "1234", MemoryGiB: "4321", FreeGiB: "0"},
|
||||
Unreviewed: "smolvm:egress-proxy",
|
||||
Unreviewed: "lima:egress-proxy",
|
||||
KVM: "/x/kvm", UbuntuURL: "file:///x/ubuntu/",
|
||||
}
|
||||
for _, c := range []struct {
|
||||
@@ -60,27 +59,24 @@ func TestOverrides(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lb, _ := r.Lookup("lima")
|
||||
sb, _ := r.Lookup("smolvm")
|
||||
l, s := lb.(*lima.Lima), sb.(*smolvm.Smolvm)
|
||||
l := lb.(*lima.Lima)
|
||||
mem, _ := r.Host.Memory()
|
||||
free, _ := r.Host.FreeSpace(t.TempDir())
|
||||
for what, got := range map[string]bool{
|
||||
"let through": r.Unreviewed["smolvm:egress-proxy"],
|
||||
"let through": r.Unreviewed["lima:egress-proxy"],
|
||||
"lima's KVM": l.KVM == "/x/kvm",
|
||||
"smolvm's KVM": s.KVM == "/x/kvm",
|
||||
"lima's Ubuntu": l.UbuntuURL == "file:///x/ubuntu",
|
||||
"the registry's CPUs": r.Host.CPUs() == 1234,
|
||||
"the registry's memory": mem == 4321<<30,
|
||||
"the registry's free": free == 0,
|
||||
"lima's CPUs": l.CPUs() == 1234,
|
||||
"smolvm's CPUs": s.CPUs() == 1234,
|
||||
} {
|
||||
if got != c.want {
|
||||
t.Errorf("overrides %v: %s overridden = %v", c.want, what, got)
|
||||
}
|
||||
}
|
||||
if !c.want && (l.KVM != "/dev/kvm" || s.KVM != "/dev/kvm" || l.UbuntuURL != ubuntu.DefaultURL) {
|
||||
t.Errorf("none: KVM %q %q, Ubuntu %q", l.KVM, s.KVM, l.UbuntuURL)
|
||||
if !c.want && (l.KVM != "/dev/kvm" || l.UbuntuURL != ubuntu.DefaultURL) {
|
||||
t.Errorf("none: KVM %q, Ubuntu %q", l.KVM, l.UbuntuURL)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -111,16 +107,6 @@ func TestLimaIsTheDefault(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// smolvm is experimental, and Lima and a name that isn't a backend aren't.
|
||||
func TestExperimental(t *testing.T) {
|
||||
t.Parallel()
|
||||
for name, want := range map[string]bool{"smolvm": true, "lima": false, "nope": false, "": false} {
|
||||
if got := Experimental(name); got != want {
|
||||
t.Errorf("Experimental(%q) = %v, want %v", name, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A new VM's backend is settings.json's, then config.toml's over it, and
|
||||
// one that isn't registered names the file that set it.
|
||||
func TestDefaultBackendFiles(t *testing.T) {
|
||||
@@ -134,15 +120,15 @@ func TestDefaultBackendFiles(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := settings.Save(d, settings.Values{Backend: settings.Of("smolvm")}); err != nil {
|
||||
if _, err := settings.Save(d, settings.Values{Backend: settings.Of("qemu")}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c, err := r.For(d, vm, ""); err != nil || c.Backend.Name() != "smolvm" {
|
||||
t.Errorf("settings.json's: %+v, %v", c, err)
|
||||
if _, err := r.For(d, vm, ""); msg.NamesOf(err) != "backend_unknown_default backends=lima file="+d.Settings()+" name=qemu" {
|
||||
t.Errorf("settings.json's: %v", msg.NamesOf(err))
|
||||
}
|
||||
for _, tc := range []struct{ file, want string }{
|
||||
{"backend = \"lima\"\n", "lima"},
|
||||
{"backend = \"qemu\"\n", "backend_unknown_default backends=lima, smolvm file=" + d.ConfigFile() + " name=qemu"},
|
||||
{"backend = \"qemu\"\n", "backend_unknown_default backends=lima file=" + d.ConfigFile() + " name=qemu"},
|
||||
} {
|
||||
if err := os.WriteFile(d.ConfigFile(), []byte(tc.file), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -162,7 +148,7 @@ func TestDefaultBackendFiles(t *testing.T) {
|
||||
// ~/.local/share/devvm) keeps every socket devvm makes within the limit:
|
||||
// a VM's folder holds none, and those in the run folder are named by
|
||||
// hashes, so no VM's name lengthens them.
|
||||
const homeMax = 35
|
||||
const homeMax = 37
|
||||
|
||||
// Every socket devvm makes for a VM, the longest VM name's included, fits
|
||||
// a socket's path under the longest home: devvm's agent, the port
|
||||
@@ -185,11 +171,10 @@ func TestSocketsFit(t *testing.T) {
|
||||
vm := "devvm-" + strings.Repeat("a", 20) + "-0123456789abcd" // the longest folder part
|
||||
target := "devvm-" + strings.Repeat("b", 20) + "-0123456789abce"
|
||||
lb, _ := r.Lookup("lima")
|
||||
sb, _ := r.Lookup("smolvm")
|
||||
l, s := lb.(*lima.Lima), sb.(*smolvm.Smolvm)
|
||||
l := lb.(*lima.Lima)
|
||||
links := vmssh.Links{VM: vm, Dir: d.Run()}
|
||||
ctls := []string{
|
||||
l.Forwards.Control(vm), s.Forwards.Control(vm),
|
||||
l.Forwards.Control(vm),
|
||||
links.Control("", ""), links.Control(target, "12345 2026-11-03T00:00:00.000000000Z"),
|
||||
}
|
||||
for _, p := range ctls {
|
||||
@@ -215,8 +200,7 @@ func TestSocketsFit(t *testing.T) {
|
||||
t.Error("a control socket's length depends on the VM's name")
|
||||
}
|
||||
// One more character of home and a control socket is too long.
|
||||
if over := len(l.Forwards.Control(vm)) + 1; over <= vmssh.ControlMax && len(links.Control(target, "x"))+1 <= vmssh.ControlMax &&
|
||||
len(s.Forwards.Control(vm))+1 <= vmssh.ControlMax {
|
||||
if over := len(l.Forwards.Control(vm)) + 1; over <= vmssh.ControlMax && len(links.Control(target, "x"))+1 <= vmssh.ControlMax {
|
||||
t.Errorf("homeMax %d isn't the longest: raise it", homeMax)
|
||||
}
|
||||
}
|
||||
@@ -38,15 +38,15 @@ func testRegistry(t *testing.T, names ...string) *backend.Registry {
|
||||
}
|
||||
|
||||
func TestRegistry(t *testing.T) {
|
||||
r := testRegistry(t, "smolvm", "lima")
|
||||
if got := r.Names(); len(got) != 2 || got[0] != "lima" || got[1] != "smolvm" {
|
||||
r := testRegistry(t, "vz", "lima")
|
||||
if got := r.Names(); len(got) != 2 || got[0] != "lima" || got[1] != "vz" {
|
||||
t.Errorf("Names: %q", got)
|
||||
}
|
||||
if all := r.All(); len(all) != 2 || all[0].Name() != "lima" || all[1].Name() != "smolvm" {
|
||||
if all := r.All(); len(all) != 2 || all[0].Name() != "lima" || all[1].Name() != "vz" {
|
||||
t.Errorf("All: %v", all)
|
||||
}
|
||||
if b, ok := r.Lookup("smolvm"); !ok || b.Name() != "smolvm" {
|
||||
t.Errorf("Lookup(smolvm): %v, %v", b, ok)
|
||||
if b, ok := r.Lookup("vz"); !ok || b.Name() != "vz" {
|
||||
t.Errorf("Lookup(vz): %v, %v", b, ok)
|
||||
}
|
||||
if _, ok := r.Lookup("fake"); ok {
|
||||
t.Error("Lookup(fake): found")
|
||||
@@ -68,18 +68,18 @@ func TestFor(t *testing.T) {
|
||||
ignored bool
|
||||
}{
|
||||
{name: "a new VM, nothing set", want: "lima"},
|
||||
{name: "a new VM, the default file", file: "smolvm", want: "smolvm"},
|
||||
{name: "a new VM, --backend", file: "smolvm", flag: "fake", want: "fake"},
|
||||
{name: "an existing VM keeps its backend", file: "fake", recorded: "smolvm", want: "smolvm"},
|
||||
{name: "an existing VM ignores --backend", recorded: "smolvm", flag: "fake", want: "smolvm", ignored: true},
|
||||
{name: "--backend naming its own", recorded: "smolvm", flag: "smolvm", want: "smolvm"},
|
||||
{name: "an unknown --backend", flag: "sbx", want: "backend_unknown backends=fake, lima, smolvm name=sbx"},
|
||||
{name: "an unknown default", file: "sbx", want: "backend_unknown_default backends=fake, lima, smolvm file=/c/config.toml name=sbx"},
|
||||
{name: "a new VM, the default file", file: "vz", want: "vz"},
|
||||
{name: "a new VM, --backend", file: "vz", flag: "fake", want: "fake"},
|
||||
{name: "an existing VM keeps its backend", file: "fake", recorded: "vz", want: "vz"},
|
||||
{name: "an existing VM ignores --backend", recorded: "vz", flag: "fake", want: "vz", ignored: true},
|
||||
{name: "--backend naming its own", recorded: "vz", flag: "vz", want: "vz"},
|
||||
{name: "an unknown --backend", flag: "sbx", want: "backend_unknown backends=fake, lima, vz name=sbx"},
|
||||
{name: "an unknown default", file: "sbx", want: "backend_unknown_default backends=fake, lima, vz file=/c/config.toml name=sbx"},
|
||||
{name: "an existing VM on a backend not here", recorded: "qemu", want: "backend_unknown_vm backend=qemu vm=devvm-x-0123456789abcd"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
d := testDirs(t)
|
||||
r := testRegistry(t, "lima", "smolvm", "fake")
|
||||
r := testRegistry(t, "lima", "vz", "fake")
|
||||
if tc.file != "" {
|
||||
r.DefaultBackend = func() (string, string, error) { return tc.file, "/c/config.toml", nil }
|
||||
}
|
||||
@@ -109,14 +109,14 @@ func TestUsed(t *testing.T) {
|
||||
}{
|
||||
{name: "no VMs", want: ""},
|
||||
{name: "one backend's", vms: []string{"lima", "lima"}, want: "lima"},
|
||||
{name: "two backends', sorted", vms: []string{"smolvm", "fake", "lima"}, want: "fake lima smolvm"},
|
||||
{name: "unrecorded and unknown backends", vms: []string{"", "qemu", "smolvm"}, want: "smolvm"},
|
||||
{name: "two backends', sorted", vms: []string{"vz", "fake", "lima"}, want: "fake lima vz"},
|
||||
{name: "unrecorded and unknown backends", vms: []string{"", "qemu", "vz"}, want: "vz"},
|
||||
{name: "a VM's policy file", vms: []string{"lima"}, files: "0123456789abc0/policy", want: "lima"},
|
||||
{name: "a folder that isn't a VM's", vms: []string{"lima"}, files: "other/state", want: "lima"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
d := testDirs(t)
|
||||
r := testRegistry(t, "lima", "smolvm", "fake")
|
||||
r := testRegistry(t, "lima", "vz", "fake")
|
||||
for i, b := range tc.vms {
|
||||
if _, err := state.CreateVM(d, "devvm-x-0123456789abc"+strconv.Itoa(i), state.NewVM{Image: "base", Backend: b}); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -160,9 +160,9 @@ func readVM(t *testing.T, d paths.Dirs, recorded string) *state.VM {
|
||||
|
||||
func TestForWithoutTheDefault(t *testing.T) {
|
||||
d := testDirs(t)
|
||||
r := testRegistry(t, "smolvm")
|
||||
r := testRegistry(t, "vz")
|
||||
_, err := r.For(d, readVM(t, d, ""), "")
|
||||
if got, want := msg.NamesOf(err), "backend_unknown backends=smolvm name=lima"; got != want {
|
||||
if got, want := msg.NamesOf(err), "backend_unknown backends=vz name=lima"; got != want {
|
||||
t.Errorf("got %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,83 +0,0 @@
|
||||
package smolvm
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/w3cj/devvm/internal/backend"
|
||||
"github.com/w3cj/devvm/internal/msg"
|
||||
)
|
||||
|
||||
// smolvm sets a machine's SSH agent forwarding only when it's made
|
||||
// (--ssh-agent), and forwards the agent SSH_AUTH_SOCK names when it starts:
|
||||
// its process connects to that path again for each of the VM's connections
|
||||
// to the agent. So turning forwarding on or off later (agent-toggle) is
|
||||
// emulated, reviewed: a machine made while devvm lets it through
|
||||
// (VMSpec.AgentToggle) forwards from the start, and each start gives it
|
||||
// the agent devvm's choice names: the user's (SSH_AUTH_SOCK), devvm's own
|
||||
// (Confinement.AgentSocket), or none (noAgent). One started any other way
|
||||
// is caught by its lifeline (AgentUnchosen), and devvm stops it.
|
||||
|
||||
// noAgent is the agent a machine that forwards one gets for none: a path
|
||||
// under /dev/null, which is a device, not a folder, so no socket can ever
|
||||
// be there, and each of the VM's connections to its agent fails. Nothing
|
||||
// listens for it: no agent to add keys to, or to sign with.
|
||||
const noAgent = "/dev/null/devvm-no-agent"
|
||||
|
||||
// SetAgentForwarding turns a stopped VM's forwarding on or off from its
|
||||
// next start: only for one made forwarding, as smolvm can't add it to one
|
||||
// made without (agent_fixed).
|
||||
func (s *Smolvm) SetAgentForwarding(ctx context.Context, vm string, on bool) error {
|
||||
_, r, err := s.stopped(ctx, vm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch {
|
||||
case !r.Forwarding && !on, r.Forwarding && r.AgentOff != on:
|
||||
return nil
|
||||
case !r.Forwarding:
|
||||
return msg.AgentFixed(Name, vm)
|
||||
}
|
||||
r.AgentOff = !on
|
||||
return s.writeRecord(vm, r)
|
||||
}
|
||||
|
||||
// AgentUnchosen reports whether a running machine made forwarding may
|
||||
// forward an agent devvm didn't choose: one not running on the process
|
||||
// Start last started (smolvm machine start from the user's shell forwards
|
||||
// that shell's). A machine made without forwarding has no agent however
|
||||
// it's started, and a stopped one none.
|
||||
func (s *Smolvm) AgentUnchosen(ctx context.Context, vm string) (bool, error) {
|
||||
r, err := s.readRecord(vm)
|
||||
if err != nil || !r.Forwarding {
|
||||
return false, err
|
||||
}
|
||||
m, err := s.inspect(ctx, vm)
|
||||
if err != nil {
|
||||
return false, notFound(vm, err)
|
||||
}
|
||||
if m.status() != backend.StatusRunning {
|
||||
return false, nil
|
||||
}
|
||||
cur, err := s.lifeline(ctx, vm)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return !runsOn(cur, r.Started), nil
|
||||
}
|
||||
|
||||
// agentSocket is the agent a machine made forwarding starts with: none
|
||||
// when its record or c says so (either is enough); else devvm's own when c
|
||||
// names it, else the user's (SSH_AUTH_SOCK, read with getenv), and
|
||||
// without one the start is refused.
|
||||
func agentSocket(vm string, r record, c backend.Confinement, getenv func(string) string) (string, error) {
|
||||
switch {
|
||||
case r.AgentOff || c.NoAgent:
|
||||
return noAgent, nil
|
||||
case c.AgentSocket != "":
|
||||
return c.AgentSocket, nil
|
||||
}
|
||||
if sock := getenv("SSH_AUTH_SOCK"); sock != "" {
|
||||
return sock, nil
|
||||
}
|
||||
return "", msg.SmolvmNoAgent(vm)
|
||||
}
|
||||
@@ -1,515 +0,0 @@
|
||||
package smolvm
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/w3cj/devvm/internal/backend"
|
||||
"github.com/w3cj/devvm/internal/from"
|
||||
"github.com/w3cj/devvm/internal/image"
|
||||
"github.com/w3cj/devvm/internal/msg"
|
||||
"github.com/w3cj/devvm/internal/platform"
|
||||
"github.com/w3cj/devvm/internal/ubuntu"
|
||||
)
|
||||
|
||||
// dockerDir is a folder on a machine's own disk, not its overlay root,
|
||||
// which Docker's storage needs.
|
||||
const dockerDir = "/var/lib/docker"
|
||||
|
||||
// BuildImage builds an image's pack. Base is a machine made from Ubuntu's
|
||||
// pinned container image (or spec.From's), by its digest, prepared as Lima's cloud
|
||||
// image comes (prepare.sh: sudo, CA certificates, the VM's user; after its
|
||||
// scripts, sshd.sh: sshd, without host keys); a layer
|
||||
// a machine made from its parent's pack. Neither mounts anything from the
|
||||
// host. It starts with the network spec.Net asks for, runs the scripts in
|
||||
// order as the VM's user (while shims.sh's stand-ins for systemctl and
|
||||
// rc-update are there), stops, and is packed into the image's folder; the
|
||||
// machine is deleted then.
|
||||
//
|
||||
// Until the machine exists, an interrupted run deletes it, and so does a
|
||||
// failed create: a cleanup on the ui stack. Once it exists, a failure keeps
|
||||
// it, stopped, for inspection; the next build deletes it (it has no
|
||||
// record).
|
||||
func (s *Smolvm) BuildImage(ctx context.Context, spec backend.ImageSpec) (backend.Built, error) {
|
||||
if spec.From != nil && spec.Parent != "" {
|
||||
return backend.Built{}, errors.New("smolvm: only base starts from a container image")
|
||||
}
|
||||
if spec.Net != backend.NetInternet && spec.Net != backend.NetNone {
|
||||
return backend.Built{}, fmt.Errorf("smolvm: builds are confined, not started with network %d", spec.Net)
|
||||
}
|
||||
for _, k := range []string{spec.Key, spec.Parent} {
|
||||
if k != "" && !image.IsKey(k) {
|
||||
return backend.Built{}, fmt.Errorf("smolvm: invalid image key %q", k)
|
||||
}
|
||||
}
|
||||
inst := ImagePrefix + spec.Key
|
||||
if err := s.absent(ctx, inst); err != nil {
|
||||
return backend.Built{}, err
|
||||
}
|
||||
if _, err := os.Stat(s.Dirs.SmolvmImage(spec.Key)); err == nil {
|
||||
return backend.Built{}, fmt.Errorf("smolvm: image %s exists already", spec.Key)
|
||||
}
|
||||
if spec.Parent != "" {
|
||||
if _, err := os.Stat(s.packFile(spec.Parent)); err != nil {
|
||||
return backend.Built{}, msg.ImageMissing(spec.Parent)
|
||||
}
|
||||
}
|
||||
name, uid, err := s.user()
|
||||
if err != nil {
|
||||
return backend.Built{}, err
|
||||
}
|
||||
cpus, mem, disk, err := s.baseSize()
|
||||
if err != nil {
|
||||
return backend.Built{}, err
|
||||
}
|
||||
if spec.MemoryGiB > 0 {
|
||||
mem = spec.MemoryGiB
|
||||
}
|
||||
|
||||
var created atomic.Bool // an interrupt's cleanups may run while this goes on
|
||||
remove := s.AddCleanup(func(ctx context.Context) {
|
||||
if !created.Load() || s.Interrupted() {
|
||||
s.unfinished(ctx, inst)
|
||||
}
|
||||
})
|
||||
// Its steps: create, start, the stand-ins, each script, the stand-ins
|
||||
// gone, stop, pack, delete; base's preparation first and its sshd
|
||||
// after its scripts.
|
||||
steps := 7 + len(spec.Scripts)
|
||||
if spec.Parent == "" {
|
||||
steps += 2
|
||||
}
|
||||
if !spec.Trust.None() {
|
||||
steps += 2 // the user's CAs added before the rest, and removed
|
||||
}
|
||||
ctx = s.WithSteps(ctx, steps)
|
||||
built := backend.Built{}
|
||||
args := []string{
|
||||
"machine", "create", "--name", inst, "--label", LabelKey + "=" + s.Dirs.Data,
|
||||
"--cpus", strconv.Itoa(cpus), "--mem", mib(mem), "--storage", gibCeil(disk), "-v", dockerDir,
|
||||
}
|
||||
if spec.Net == backend.NetInternet {
|
||||
// Not set later (Start's update): a pack carries its network.
|
||||
args = append(args, "--net")
|
||||
}
|
||||
step := msg.CloningImage(image.Parent(spec.Image))
|
||||
if spec.Parent == "" {
|
||||
ref, origin, err := s.baseImage(spec.From)
|
||||
if err != nil {
|
||||
return backend.Built{}, err
|
||||
}
|
||||
built.Origin = origin
|
||||
if built.Fitted, err = fitted(s.Assets, cpus, mem); err != nil {
|
||||
return backend.Built{}, err
|
||||
}
|
||||
args = append(args, "--image", ref)
|
||||
step = msg.CreatingFromImage(ref, inst)
|
||||
} else {
|
||||
args = append(args, "--from", s.packFile(spec.Parent))
|
||||
}
|
||||
if err := s.Runner.Run(ctx, step, s.smolvm(ctx, args...)); err != nil {
|
||||
return backend.Built{}, backend.Logged(msg.VMCreateFailed(inst))
|
||||
}
|
||||
if err := s.writeRecord(inst, record{Image: spec.Parent}); err != nil {
|
||||
return backend.Built{}, err
|
||||
}
|
||||
created.Store(true)
|
||||
// A failed start leaves it stopped.
|
||||
if err := s.Start(ctx, inst, backend.Confinement{Net: spec.Net}); err != nil {
|
||||
return backend.Built{}, err
|
||||
}
|
||||
// Once it's running, a failure stops it (unless the run was
|
||||
// interrupted: then it's deleted).
|
||||
failed := func(err error) (backend.Built, error) {
|
||||
if ctx.Err() == nil {
|
||||
_ = s.stop(ctx, inst)
|
||||
}
|
||||
return backend.Built{}, err
|
||||
}
|
||||
if err := s.runScript(ctx, inst, spec.Trust.Add, true); err != nil {
|
||||
return failed(err)
|
||||
}
|
||||
if spec.Parent == "" {
|
||||
if err := s.rootScript(ctx, inst, "prepare.sh", name, uid); err != nil {
|
||||
return failed(err)
|
||||
}
|
||||
out, err := s.Runner.Output(s.smolvm(ctx, "machine", "exec", "--name", inst, "--",
|
||||
"sh", "-c", "if command -v apk >/dev/null; then echo musl; else echo gnu; fi"))
|
||||
if err != nil {
|
||||
return failed(backend.Logged(msg.SmolvmScriptFailed("prepare.sh", inst)))
|
||||
}
|
||||
built.Libc = strings.TrimSpace(string(out))
|
||||
}
|
||||
if err := s.rootScript(ctx, inst, "shims.sh", "on"); err != nil {
|
||||
return failed(err)
|
||||
}
|
||||
for _, sc := range spec.Scripts {
|
||||
if err := s.runScript(ctx, inst, sc, false); err != nil {
|
||||
return failed(err)
|
||||
}
|
||||
}
|
||||
if spec.Parent == "" {
|
||||
if err := s.rootScript(ctx, inst, "sshd.sh"); err != nil {
|
||||
return failed(err)
|
||||
}
|
||||
}
|
||||
if err := s.runScript(ctx, inst, spec.Trust.Remove, true); err != nil {
|
||||
return failed(err)
|
||||
}
|
||||
if err := s.rootScript(ctx, inst, "shims.sh", "off"); err != nil {
|
||||
return failed(err)
|
||||
}
|
||||
if err := s.stop(ctx, inst); err != nil {
|
||||
return backend.Built{}, err
|
||||
}
|
||||
if err := s.packInto(ctx, inst, spec.Key); err != nil {
|
||||
return backend.Built{}, err
|
||||
}
|
||||
if err := s.remove(ctx, inst); err != nil {
|
||||
return backend.Built{}, err
|
||||
}
|
||||
remove()
|
||||
return built, nil
|
||||
}
|
||||
|
||||
// baseImage is the container image base starts from, by digest, and what
|
||||
// its record says it started from: spec's (as recorded), else Ubuntu's,
|
||||
// pinned. One only Docker has is refused: smolvm pulls from registries.
|
||||
func (s *Smolvm) baseImage(f *backend.From) (ref, origin string, err error) {
|
||||
if f != nil {
|
||||
if f.Digest == "" {
|
||||
return "", "", msg.NoDigest(f.Ref)
|
||||
}
|
||||
if !from.Valid(f.Ref) || !from.Valid(f.Digest) {
|
||||
return "", "", msg.BadFrom(f.Ref)
|
||||
}
|
||||
if !strings.Contains(f.Digest, "@") {
|
||||
return "", "", msg.SmolvmFromRegistryOnly(f.Ref)
|
||||
}
|
||||
return f.Digest, f.Digest, nil
|
||||
}
|
||||
return ubuntu.ContainerRef, ubuntu.ContainerOrigin, nil
|
||||
}
|
||||
|
||||
// rootScript runs one of devvm's scripts for images run as containers
|
||||
// (containerScript) as root in a running machine, fed to sh with args.
|
||||
func (s *Smolvm) rootScript(ctx context.Context, vm, name string, args ...string) error {
|
||||
script, err := s.containerScript(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cmd := s.asRoot(ctx, vm, args...)
|
||||
cmd.Stdin = bytes.NewReader(script)
|
||||
if err := s.Runner.Run(ctx, msg.RunningScript(name, vm), cmd); err != nil {
|
||||
return backend.Logged(msg.SmolvmScriptFailed(name, vm))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// runScript runs a script in the machine as its user, fed to bash, or
|
||||
// with root as root, fed to sh: a build's Trust scripts, of which an empty
|
||||
// one isn't run.
|
||||
func (s *Smolvm) runScript(ctx context.Context, vm string, sc backend.Script, root bool) error {
|
||||
var cmd *exec.Cmd
|
||||
if root {
|
||||
if len(sc.Data) == 0 {
|
||||
return nil
|
||||
}
|
||||
cmd = s.asRoot(ctx, vm)
|
||||
} else {
|
||||
args, err := s.userArgs(vm, "", true, false, []string{"bash", "-s"})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cmd = s.smolvm(ctx, args...)
|
||||
}
|
||||
cmd.Stdin = bytes.NewReader(sc.Data)
|
||||
if err := s.Runner.Run(ctx, msg.RunningScript(sc.Name, vm), cmd); err != nil {
|
||||
return backend.Logged(msg.SmolvmScriptFailed(sc.Name, vm))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// packInto packs a stopped machine into the image's folder: written beside
|
||||
// it, then renamed in, so a folder that's there is a whole pack. smolvm's
|
||||
// stub is kept with it: machines made from the pack read it when they grow.
|
||||
func (s *Smolvm) packInto(ctx context.Context, vm, key string) error {
|
||||
dir := s.Dirs.SmolvmImage(key)
|
||||
tmp := dir + ".tmp"
|
||||
if err := os.RemoveAll(tmp); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(tmp, 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
done := s.AddCleanup(func(context.Context) { _ = os.RemoveAll(tmp) })
|
||||
defer done()
|
||||
if err := s.Runner.Run(ctx, msg.PackingImage(vm),
|
||||
s.smolvm(ctx, "pack", "create", "--from-vm", vm, "-o", filepath.Join(tmp, "image"))); err != nil {
|
||||
_ = os.RemoveAll(tmp)
|
||||
return backend.Logged(msg.PackFailed(vm))
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(tmp, "image.smolmachine")); err != nil {
|
||||
_ = os.RemoveAll(tmp)
|
||||
return backend.Logged(msg.PackFailed(vm))
|
||||
}
|
||||
if err := os.Rename(tmp, dir); err != nil {
|
||||
return err
|
||||
}
|
||||
return packCache{s}.record(key)
|
||||
}
|
||||
|
||||
// unfinished deletes an image's build machine that didn't finish: on an
|
||||
// interrupt, or when its create failed.
|
||||
func (s *Smolvm) unfinished(ctx context.Context, inst string) {
|
||||
if _, err := s.inspect(ctx, inst); err != nil {
|
||||
return // never created, someone else's, or smolvm can't say
|
||||
}
|
||||
if s.Interrupted() {
|
||||
s.Info(msg.InterruptedImage(inst))
|
||||
} else {
|
||||
s.Info(msg.UnfinishedImage(inst))
|
||||
}
|
||||
_ = s.remove(ctx, inst)
|
||||
}
|
||||
|
||||
// Images lists the keys of devvm's images on smolvm: its packs, and the
|
||||
// build machines of those that didn't finish.
|
||||
func (s *Smolvm) Images(ctx context.Context) ([]string, error) {
|
||||
var keys []string
|
||||
entries, err := os.ReadDir(filepath.Join(s.Dirs.Smolvm(), "images"))
|
||||
if err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return nil, err
|
||||
}
|
||||
for _, e := range entries {
|
||||
if image.IsKey(e.Name()) && e.IsDir() {
|
||||
keys = append(keys, e.Name())
|
||||
}
|
||||
}
|
||||
ms, err := s.ours(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, m := range ms {
|
||||
if k, ok := imageKey(m.Name); ok && !slices.Contains(keys, k) {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
}
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
// ImageSize is the disk space of an image's pack, and of its build
|
||||
// machine while it has one.
|
||||
func (s *Smolvm) ImageSize(ctx context.Context, key string) (int64, error) {
|
||||
if !image.IsKey(key) {
|
||||
return 0, msg.NotAnImage(ImagePrefix + key)
|
||||
}
|
||||
var total int64
|
||||
found := false
|
||||
if n, err := platform.DiskUsage(s.Dirs.SmolvmImage(key)); err == nil {
|
||||
total, found = n, true
|
||||
} else if !errors.Is(err, fs.ErrNotExist) {
|
||||
return 0, err
|
||||
}
|
||||
if _, err := s.inspect(ctx, ImagePrefix+key); err == nil {
|
||||
if dir := s.dataDir(ctx, ImagePrefix+key); dir != "" {
|
||||
if n, err := platform.DiskUsage(dir); err == nil {
|
||||
total, found = total+n, true
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return 0, fmt.Errorf("image %s: %w", key, fs.ErrNotExist)
|
||||
}
|
||||
return total, nil
|
||||
}
|
||||
|
||||
// dataDir is smolvm's folder for a machine, "" when it can't say.
|
||||
func (s *Smolvm) dataDir(ctx context.Context, vm string) string {
|
||||
out, err := s.Runner.Output(s.smolvm(ctx, "machine", "data-dir", "--name", vm))
|
||||
dir := strings.TrimSpace(string(out))
|
||||
if err != nil || !filepath.IsAbs(dir) {
|
||||
return ""
|
||||
}
|
||||
return dir
|
||||
}
|
||||
|
||||
// DeleteImage deletes an image's pack and its build machine. One that VMs
|
||||
// were made from is refused: they read its pack when their disks grow.
|
||||
func (s *Smolvm) DeleteImage(ctx context.Context, key string) error {
|
||||
if !image.IsKey(key) {
|
||||
return msg.NotAnImage(ImagePrefix + key)
|
||||
}
|
||||
users, err := s.imageUsers(ctx, key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(users) > 0 {
|
||||
return msg.ImageInUse(key, strings.Join(users, " "))
|
||||
}
|
||||
if err := s.removeIfThere(ctx, ImagePrefix+key); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.RemoveAll(s.Dirs.SmolvmImage(key))
|
||||
}
|
||||
|
||||
// imageUsers are devvm's machines made from the image's pack.
|
||||
func (s *Smolvm) imageUsers(ctx context.Context, key string) ([]string, error) {
|
||||
ms, err := s.ours(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var users []string
|
||||
for _, m := range ms {
|
||||
if m.Name == ImagePrefix+key {
|
||||
continue
|
||||
}
|
||||
r, err := s.readRecord(m.Name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if r.Image == key {
|
||||
users = append(users, m.Name)
|
||||
}
|
||||
}
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// CreateVM makes a new, stopped machine from the image's pack, with
|
||||
// everything set: a pack would give it its build machine's network, CPUs
|
||||
// and memory. Its disk is at least base's. Its ports are its forwarder's
|
||||
// (forward.go), so smolvm forwards none of them.
|
||||
func (s *Smolvm) CreateVM(ctx context.Context, img string, spec backend.VMSpec) error {
|
||||
vm := spec.Name
|
||||
if !image.IsKey(img) {
|
||||
return fmt.Errorf("smolvm: invalid image key %q", img)
|
||||
}
|
||||
if _, err := os.Stat(s.packFile(img)); err != nil {
|
||||
return msg.ImageMissing(img)
|
||||
}
|
||||
if err := s.absent(ctx, vm); err != nil {
|
||||
return err
|
||||
}
|
||||
cpus, mem, disk, err := s.baseSize()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if spec.Size.CPUs > 0 {
|
||||
cpus = spec.Size.CPUs
|
||||
}
|
||||
if spec.Size.MemoryGiB > 0 {
|
||||
mem = spec.Size.MemoryGiB
|
||||
}
|
||||
disk = max(disk, spec.Size.DiskGiB)
|
||||
args := []string{
|
||||
"machine", "create", "--name", vm, "--label", LabelKey + "=" + s.Dirs.Data, "--from", s.packFile(img),
|
||||
"--cpus", strconv.Itoa(cpus), "--mem", mib(mem), "--storage", gibCeil(disk), "-v", dockerDir,
|
||||
}
|
||||
var vols []string
|
||||
if spec.Project != "" {
|
||||
v, err := volume(spec.Project, spec.Project, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
vols = append(vols, v)
|
||||
}
|
||||
for _, d := range spec.AgentDirs {
|
||||
v, err := volume(d, d, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
vols = append(vols, v)
|
||||
}
|
||||
if spec.Tools != "" {
|
||||
v, err := volume(spec.Tools, spec.ToolsAt, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
vols = append(vols, v)
|
||||
}
|
||||
for _, v := range vols {
|
||||
args = append(args, "-v", v)
|
||||
}
|
||||
// Forwarding is fixed now: a VM whose forwarding may change later
|
||||
// forwards from the start, given no agent while it's off (agent.go).
|
||||
forwarding := spec.AgentForwarding || spec.AgentToggle
|
||||
if forwarding {
|
||||
args = append(args, "--ssh-agent")
|
||||
}
|
||||
if err := s.Runner.Run(ctx, msg.Creating(vm), s.smolvm(ctx, args...)); err != nil {
|
||||
return backend.Logged(msg.VMCreateFailed(vm))
|
||||
}
|
||||
return s.writeRecord(vm, record{
|
||||
Image: img, Project: spec.Project, AgentDirs: slices.Clone(spec.AgentDirs), Tools: spec.Tools, ToolsAt: spec.ToolsAt,
|
||||
Forwarding: forwarding, AgentOff: forwarding && !spec.AgentForwarding,
|
||||
PortsAll: spec.Ports.All, Listed: listed(spec.Ports),
|
||||
})
|
||||
}
|
||||
|
||||
var (
|
||||
cpusLine = regexp.MustCompile(`(?m)^cpus:\s*([0-9]+)\s*$`)
|
||||
memoryLine = regexp.MustCompile(`(?m)^memory:\s*([0-9.]+)GiB\s*$`)
|
||||
diskLine = regexp.MustCompile(`(?m)^disk:\s*([0-9.]+)GiB\s*$`)
|
||||
)
|
||||
|
||||
// baseSize is what images and VMs get unless told otherwise: base.yaml's
|
||||
// CPUs, memory and disk, as Lima's base has them, its CPUs and memory
|
||||
// fitted to the host (backend.FitCPUs, backend.FitMemory).
|
||||
func (s *Smolvm) baseSize() (cpus int, mem, disk float64, err error) {
|
||||
want, err := baseYAML(s.Assets)
|
||||
if err != nil {
|
||||
return 0, 0, 0, err
|
||||
}
|
||||
host, err := s.Memory()
|
||||
if err != nil {
|
||||
return 0, 0, 0, err
|
||||
}
|
||||
return backend.FitCPUs(want.CPUs, s.CPUs()), backend.FitMemory(want.MemoryGiB, host), want.DiskGiB, nil
|
||||
}
|
||||
|
||||
// baseYAML is base.yaml's CPUs, memory and disk in assets, not fitted to
|
||||
// the host.
|
||||
func baseYAML(assets fs.FS) (backend.Size, error) {
|
||||
data, err := fs.ReadFile(assets, "base.yaml")
|
||||
if err != nil {
|
||||
return backend.Size{}, err
|
||||
}
|
||||
get := func(re *regexp.Regexp) (float64, error) {
|
||||
m := re.FindSubmatch(data)
|
||||
if m == nil {
|
||||
return 0, fmt.Errorf("smolvm: base.yaml doesn't match %s", re)
|
||||
}
|
||||
return strconv.ParseFloat(string(m[1]), 64)
|
||||
}
|
||||
var want backend.Size
|
||||
c, err := get(cpusLine)
|
||||
if err != nil {
|
||||
return backend.Size{}, err
|
||||
}
|
||||
want.CPUs = int(c)
|
||||
if want.MemoryGiB, err = get(memoryLine); err != nil {
|
||||
return backend.Size{}, err
|
||||
}
|
||||
if want.DiskGiB, err = get(diskLine); err != nil {
|
||||
return backend.Size{}, err
|
||||
}
|
||||
return want, nil
|
||||
}
|
||||
|
||||
// fitted is what base's build reports as fitted, for the CPUs and
|
||||
// memory it gets (backend.Fitted) and assets' base.yaml.
|
||||
func fitted(assets fs.FS, cpus int, mem float64) (backend.Size, error) {
|
||||
want, err := baseYAML(assets)
|
||||
return backend.Fitted(want, backend.Size{CPUs: cpus, MemoryGiB: mem}), err
|
||||
}
|
||||
@@ -1,170 +0,0 @@
|
||||
package smolvm
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/w3cj/devvm/internal/backend"
|
||||
"github.com/w3cj/devvm/internal/image"
|
||||
"github.com/w3cj/devvm/internal/platform"
|
||||
)
|
||||
|
||||
var _ backend.CacheCleaner = (*Smolvm)(nil)
|
||||
|
||||
// seedName is a pack's disk in smolvm's cache: v2-<the SHA-256 of the
|
||||
// pack's .smolmachine>-auto, which smolvm unpacks the first time a
|
||||
// machine is made from the pack and keeps for the next.
|
||||
var seedName = regexp.MustCompile(`^v2-([0-9a-f]{64})-auto$`)
|
||||
|
||||
// cacheRecent is how long a pack's disk is left alone after it changed:
|
||||
// a machine may be being made from it.
|
||||
const cacheRecent = time.Hour
|
||||
|
||||
// packCache ties the disks in smolvm's cache to devvm's packs.
|
||||
type packCache struct{ *Smolvm }
|
||||
|
||||
// packsFile lists every pack devvm made, "<key> <sha256>" per line, so a
|
||||
// pack's disk in smolvm's cache can be tied to devvm's pack after the
|
||||
// pack is deleted.
|
||||
func (s packCache) packsFile() string { return filepath.Join(s.Dirs.Smolvm(), "packs") }
|
||||
|
||||
// record adds a new pack to packsFile.
|
||||
func (s packCache) record(key string) error {
|
||||
sum, err := image.SHA256File(s.packFile(key))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
f, err := os.OpenFile(s.packsFile(), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = f.WriteString(key + " " + sum + "\n")
|
||||
if cerr := f.Close(); err == nil {
|
||||
err = cerr
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// packs are devvm's packs by SHA-256: each packsFile names, and each
|
||||
// pack in its images folder (one made before packsFile was kept is
|
||||
// hashed now).
|
||||
func (s packCache) packs() (map[string]string, error) {
|
||||
out := map[string]string{}
|
||||
f, err := os.Open(s.packsFile())
|
||||
if err == nil {
|
||||
sc := bufio.NewScanner(f)
|
||||
for sc.Scan() {
|
||||
if key, sum, ok := strings.Cut(sc.Text(), " "); ok && image.IsKey(key) {
|
||||
out[sum] = key
|
||||
}
|
||||
}
|
||||
_ = f.Close()
|
||||
} else if !errors.Is(err, fs.ErrNotExist) {
|
||||
return nil, err
|
||||
}
|
||||
known := map[string]bool{}
|
||||
for _, k := range out {
|
||||
known[k] = true
|
||||
}
|
||||
entries, err := os.ReadDir(filepath.Join(s.Dirs.Smolvm(), "images"))
|
||||
if err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return nil, err
|
||||
}
|
||||
for _, e := range entries {
|
||||
if !image.IsKey(e.Name()) || known[e.Name()] {
|
||||
continue
|
||||
}
|
||||
if sum, err := image.SHA256File(s.packFile(e.Name())); err == nil {
|
||||
out[sum] = e.Name()
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// DevvmCache lists the disks smolvm unpacked of devvm's packs (on macOS,
|
||||
// in smolvm's cache) that no machine of devvm's was made from: a disk
|
||||
// whose name is the SHA-256 of one of devvm's packs, unchanged for an
|
||||
// hour. Any other disk there may be of your own packs and is never one;
|
||||
// so are the folders of machines beside them, and smolvm's other caches.
|
||||
// On Linux smolvm's state, caches included, is devvm's own folder.
|
||||
func (s *Smolvm) DevvmCache(ctx context.Context) ([]backend.CacheEntry, error) {
|
||||
if s.OS != "darwin" {
|
||||
return nil, nil
|
||||
}
|
||||
seeds, err := packCache{s}.freeSeeds(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]backend.CacheEntry, 0, len(seeds))
|
||||
for p, key := range seeds {
|
||||
n, _ := platform.DiskUsage(p)
|
||||
out = append(out, backend.CacheEntry{What: "the disk of image " + key, Path: p, Size: n})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// DeleteCache deletes pack disks DevvmCache listed that are still free.
|
||||
func (s *Smolvm) DeleteCache(ctx context.Context, entries []backend.CacheEntry) error {
|
||||
seeds, err := packCache{s}.freeSeeds(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, e := range entries {
|
||||
if _, ok := seeds[e.Path]; !ok {
|
||||
continue
|
||||
}
|
||||
if err := os.RemoveAll(e.Path); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Remove(e.Path + ".lock"); err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// freeSeeds are the pack disks in smolvm's cache that are devvm's and no
|
||||
// machine of devvm's was made from, by path, each with its image's key.
|
||||
func (s packCache) freeSeeds(ctx context.Context) (map[string]string, error) {
|
||||
if s.Dirs.UserCache == "" {
|
||||
return nil, errors.New("smolvm: no cache folder")
|
||||
}
|
||||
dir := filepath.Join(s.Dirs.UserCache, "smolvm", "vms", packSeeds)
|
||||
entries, err := os.ReadDir(dir)
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return nil, nil
|
||||
} else if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
packs, err := s.packs()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := map[string]string{}
|
||||
for _, e := range entries {
|
||||
m := seedName.FindStringSubmatch(e.Name())
|
||||
if m == nil || !e.IsDir() {
|
||||
continue
|
||||
}
|
||||
key, ours := packs[m[1]]
|
||||
fi, err := e.Info()
|
||||
if !ours || err != nil || time.Since(fi.ModTime()) < cacheRecent {
|
||||
continue
|
||||
}
|
||||
users, err := s.imageUsers(ctx, key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(users) == 0 {
|
||||
out[filepath.Join(dir, e.Name())] = key
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
package smolvm
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/w3cj/devvm/internal/image"
|
||||
)
|
||||
|
||||
// devvm's share of smolvm's cache: the disks smolvm unpacked of devvm's
|
||||
// packs (a pack there, or one packsFile records), unchanged for an hour,
|
||||
// that no machine of devvm's was made from. Never a disk of anyone
|
||||
// else's pack, a recent one, a machine's folder or another cache.
|
||||
func TestDevvmCache(t *testing.T) {
|
||||
s := newSandbox(t)
|
||||
s.Dirs.UserCache = filepath.Join(t.TempDir(), ".cache")
|
||||
seeds := filepath.Join(s.Dirs.UserCache, "smolvm", "vms", packSeeds)
|
||||
// Packs: a (no machine), b (a VM was made from it), and c, deleted
|
||||
// but recorded.
|
||||
for _, k := range []string{"aaaaaaaaaaaa", "bbbbbbbbbbbb"} {
|
||||
s.image(t, k)
|
||||
if err := os.WriteFile(s.packFile(k), []byte(k), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
sum := func(k string) string {
|
||||
v, err := image.SHA256File(s.packFile(k))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
sa, sb, sc := sum("aaaaaaaaaaaa"), sum("bbbbbbbbbbbb"), "cc"+sum("aaaaaaaaaaaa")[2:]
|
||||
if err := os.WriteFile(packCache{s.Smolvm}.packsFile(), []byte("cccccccccccc "+sc+"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.machine(t, "devvm-web-12345612345612", "running 4 8192 100 true")
|
||||
if err := s.writeRecord("devvm-web-12345612345612", record{Image: "bbbbbbbbbbbb"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
old := time.Now().Add(-2 * time.Hour)
|
||||
seed := func(name string, recent bool) string {
|
||||
p := filepath.Join(seeds, name)
|
||||
if err := os.MkdirAll(p, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(p, "storage.raw"), []byte("x"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(p+".lock", nil, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !recent {
|
||||
if err := os.Chtimes(p, old, old); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
free, deleted := seed("v2-"+sa+"-auto", false), seed("v2-"+sc+"-auto", false)
|
||||
seed("v2-"+sb+"-auto", false) // a VM's
|
||||
seed("v2-"+"dd"+sa[2:]+"-auto", false) // someone else's pack
|
||||
seed("v2-"+sa[:62]+"ee-auto", true) // not ours
|
||||
if err := os.MkdirAll(filepath.Join(s.Dirs.UserCache, "smolvm", "vms", "3d40063296df941a"), 0o700); err != nil { // a machine's
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := s.DevvmCache(t.Context())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var ps []string
|
||||
for _, e := range got {
|
||||
ps = append(ps, e.Path)
|
||||
}
|
||||
slices.Sort(ps)
|
||||
want := []string{free, deleted}
|
||||
slices.Sort(want)
|
||||
if !slices.Equal(ps, want) {
|
||||
t.Fatalf("DevvmCache = %v, want %v", ps, want)
|
||||
}
|
||||
if err := s.DeleteCache(t.Context(), got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, p := range want {
|
||||
if _, err := os.Stat(p); !os.IsNotExist(err) {
|
||||
t.Errorf("%s stayed", p)
|
||||
}
|
||||
if _, err := os.Stat(p + ".lock"); !os.IsNotExist(err) {
|
||||
t.Errorf("%s.lock stayed", p)
|
||||
}
|
||||
}
|
||||
if entries, _ := os.ReadDir(seeds); len(entries) != 6 { // 3 disks and their locks
|
||||
t.Errorf("left %d entries, want 6", len(entries))
|
||||
}
|
||||
// On Linux smolvm's caches are in devvm's own folder: none listed.
|
||||
s.OS = "linux"
|
||||
if got, _ := s.DevvmCache(t.Context()); len(got) != 0 {
|
||||
t.Errorf("Linux: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Each new pack is recorded with its SHA-256.
|
||||
func TestPackRecorded(t *testing.T) {
|
||||
s := newSandbox(t)
|
||||
s.image(t, "aaaaaaaaaaaa")
|
||||
if err := (packCache{s.Smolvm}).record("aaaaaaaaaaaa"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
packs, err := packCache{s.Smolvm}.packs()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(packs) != 1 {
|
||||
t.Errorf("packs = %v", packs)
|
||||
}
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
package smolvm
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/user"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/w3cj/devvm/internal/backend"
|
||||
"github.com/w3cj/devvm/internal/msg"
|
||||
)
|
||||
|
||||
// minMinor is the oldest smolvm 1.x devvm runs: the version it was tested
|
||||
// with.
|
||||
const minMinor = 32
|
||||
|
||||
// Check reports whether smolvm can run VMs here: the first of Problems.
|
||||
func (s *Smolvm) Check(ctx context.Context) error {
|
||||
if ps := s.Problems(ctx); len(ps) > 0 {
|
||||
return ps[0].Msg
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Problems lists what smolvm needs that this host lacks: an arm64 Mac, or
|
||||
// Linux on arm64 or x86_64 with /dev/kvm; smolvm 1.32 or newer. A fix is
|
||||
// Homebrew's for smolvm, when it's installed.
|
||||
func (s *Smolvm) Problems(ctx context.Context) []backend.Problem {
|
||||
host := s.OS + "/" + s.Arch
|
||||
switch {
|
||||
case s.OS == "darwin" && s.Arch == "arm64":
|
||||
case s.OS == "linux" && (s.Arch == "arm64" || s.Arch == "amd64"):
|
||||
default:
|
||||
return []backend.Problem{{Key: "os", Msg: msg.SmolvmHostUnsupported(host)}}
|
||||
}
|
||||
var ps []backend.Problem
|
||||
if p, ok := s.smolvmProblem(ctx); ok {
|
||||
ps = append(ps, p)
|
||||
}
|
||||
if s.OS == "linux" {
|
||||
if p, ok := s.kvmProblem(); ok {
|
||||
ps = append(ps, p)
|
||||
}
|
||||
}
|
||||
return ps
|
||||
}
|
||||
|
||||
// smolvmProblem is a missing smolvm, one that doesn't run, or one older
|
||||
// than 1.32.
|
||||
func (s *Smolvm) smolvmProblem(ctx context.Context) (backend.Problem, bool) {
|
||||
brew := has("brew")
|
||||
problem := func(fix string, plain msg.M, fixed func(fix string) msg.M) (backend.Problem, bool) {
|
||||
if !brew {
|
||||
return backend.Problem{Key: "smolvm", Msg: plain}, true
|
||||
}
|
||||
return backend.Problem{Key: "smolvm", Fix: fix, Msg: fixed(fix)}, true
|
||||
}
|
||||
if !has("smolvm") {
|
||||
return problem("brew install smol-machines/tap/smolvm", msg.SmolvmMissing(), msg.SmolvmMissingFix)
|
||||
}
|
||||
out, err := s.Runner.Output(s.smolvm(ctx, "--version"))
|
||||
fields := strings.Fields(string(out))
|
||||
if err != nil || len(fields) == 0 {
|
||||
return problem("brew reinstall smolvm", msg.SmolvmBroken(), msg.SmolvmBrokenFix)
|
||||
}
|
||||
ver := fields[len(fields)-1]
|
||||
if !recent(ver) {
|
||||
return problem("brew upgrade smolvm", msg.SmolvmOld(ver), func(fix string) msg.M { return msg.SmolvmOldFix(fix, ver) })
|
||||
}
|
||||
return backend.Problem{}, false
|
||||
}
|
||||
|
||||
// recent reports whether a version is 1.32 or newer.
|
||||
func recent(v string) bool {
|
||||
parts := strings.Split(strings.TrimPrefix(v, "v"), ".")
|
||||
if len(parts) < 2 {
|
||||
return false
|
||||
}
|
||||
major, err1 := strconv.Atoi(parts[0])
|
||||
minor, err2 := strconv.Atoi(parts[1])
|
||||
if err1 != nil || err2 != nil {
|
||||
return false
|
||||
}
|
||||
return major > 1 || major == 1 && minor >= minMinor
|
||||
}
|
||||
|
||||
// kvmProblem is a missing /dev/kvm, or one the user can't open.
|
||||
func (s *Smolvm) kvmProblem() (backend.Problem, bool) {
|
||||
if _, err := os.Stat(s.KVM); err != nil {
|
||||
return backend.Problem{Key: "kvm", Msg: msg.NoKVM()}, true
|
||||
}
|
||||
f, err := os.OpenFile(s.KVM, os.O_RDWR, 0)
|
||||
if err == nil {
|
||||
_ = f.Close()
|
||||
return backend.Problem{}, false
|
||||
}
|
||||
name := s.Getenv("USER")
|
||||
if u, uerr := user.Current(); name == "" && uerr == nil {
|
||||
name = u.Username
|
||||
}
|
||||
fix := "sudo usermod -aG kvm " + cmp.Or(name, "$USER")
|
||||
return backend.Problem{Key: "kvm-access", Fix: fix, Msg: msg.KVMAccess(fix)}, true
|
||||
}
|
||||
|
||||
// has reports whether name is a program on PATH.
|
||||
func has(name string) bool {
|
||||
_, err := exec.LookPath(name)
|
||||
return err == nil
|
||||
}
|
||||
@@ -1,223 +0,0 @@
|
||||
package smolvm
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/w3cj/devvm/internal/backend"
|
||||
"github.com/w3cj/devvm/internal/msg"
|
||||
)
|
||||
|
||||
// Runner runs the commands the backend makes. Tests swap in a fake.
|
||||
type Runner interface {
|
||||
// Run runs a command into the run log, with step on the status line.
|
||||
Run(ctx context.Context, step msg.M, cmd *exec.Cmd) error
|
||||
// Output runs a command and returns its standard output.
|
||||
Output(cmd *exec.Cmd) ([]byte, error)
|
||||
// Attach runs a command connected to the streams already set on it.
|
||||
Attach(cmd *exec.Cmd) error
|
||||
}
|
||||
|
||||
// logRunner runs commands into the run log through logged (the UI's
|
||||
// LoggedCmd).
|
||||
type logRunner struct {
|
||||
logged func(ctx context.Context, step msg.M, cmd *exec.Cmd) error
|
||||
}
|
||||
|
||||
func (r logRunner) Run(ctx context.Context, step msg.M, cmd *exec.Cmd) error {
|
||||
return r.logged(ctx, step, cmd)
|
||||
}
|
||||
|
||||
func (logRunner) Output(cmd *exec.Cmd) ([]byte, error) { return cmd.Output() }
|
||||
|
||||
func (logRunner) Attach(cmd *exec.Cmd) error { return cmd.Run() }
|
||||
|
||||
// smolvm returns a smolvm command: its usage journal off, never the
|
||||
// machine SMOLVM_MACHINE_NAME names (devvm always names one), never the
|
||||
// SSH agent devvm has (Start names the one a machine gets), in devvm's
|
||||
// data folder. On Linux it keeps its state in devvm's own folder; on
|
||||
// macOS, where it can't, devvm's machines share the user's smolvm and are
|
||||
// told apart by their label.
|
||||
func (s *Smolvm) smolvm(ctx context.Context, args ...string) *exec.Cmd {
|
||||
if s.OS == "linux" && len(args) >= 2 {
|
||||
args = slices.Concat(args[:2], []string{"--state-dir", s.stateDir()}, args[2:])
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, "smolvm", args...) //nolint:gosec // devvm's own arguments
|
||||
cmd.Env = setEnv(os.Environ(), "SMOLVM_USAGE=0", "SMOLVM_MACHINE_NAME", "SSH_AUTH_SOCK")
|
||||
cmd.Dir = s.Dirs.Data
|
||||
if err := os.MkdirAll(s.Dirs.Data, 0o700); err != nil && cmd.Err == nil {
|
||||
cmd.Err = err // the command then fails with it
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
|
||||
// setEnv returns env with each KEY=value in kvs replacing any value KEY
|
||||
// had. A bare KEY removes it.
|
||||
func setEnv(env []string, kvs ...string) []string {
|
||||
out := slices.Clone(env)
|
||||
for _, kv := range kvs {
|
||||
key, _, hasValue := strings.Cut(kv, "=")
|
||||
out = slices.DeleteFunc(out, func(e string) bool { return strings.HasPrefix(e, key+"=") })
|
||||
if hasValue {
|
||||
out = append(out, kv)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// machine is a machine as smolvm machine ls --json has it: the fields
|
||||
// devvm reads.
|
||||
type machine struct {
|
||||
Name string `json:"name"`
|
||||
State string `json:"state"`
|
||||
CPUs int `json:"cpus"`
|
||||
MemoryMiB int `json:"memory_mib"`
|
||||
StorageGB *float64 `json:"storage_gb"`
|
||||
Network bool `json:"network"`
|
||||
Labels map[string]string `json:"labels"`
|
||||
// Its allow lists: none for smolvm's whole network.
|
||||
AllowedCIDRs []string `json:"allowed_cidrs"`
|
||||
AllowedHosts []string `json:"allowed_hosts"`
|
||||
}
|
||||
|
||||
// defaultStorage is smolvm's disk size for a machine that doesn't say.
|
||||
const defaultStorage = 20
|
||||
|
||||
// status is the machine's state as devvm's: created is stopped too.
|
||||
func (m machine) status() backend.Status {
|
||||
switch m.State {
|
||||
case "running":
|
||||
return backend.StatusRunning
|
||||
case "stopped", "created":
|
||||
return backend.StatusStopped
|
||||
}
|
||||
return backend.Status(m.State)
|
||||
}
|
||||
|
||||
func (m machine) size() backend.Size {
|
||||
disk := float64(defaultStorage)
|
||||
if m.StorageGB != nil {
|
||||
disk = *m.StorageGB
|
||||
}
|
||||
return backend.Size{CPUs: m.CPUs, MemoryGiB: float64(m.MemoryMiB) / 1024, DiskGiB: disk}
|
||||
}
|
||||
|
||||
// list returns every machine smolvm has: devvm's, and on macOS the user's
|
||||
// own.
|
||||
func (s *Smolvm) list(ctx context.Context) ([]machine, error) {
|
||||
out, err := s.Runner.Output(s.smolvm(ctx, "machine", "ls", "--json"))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("smolvm machine ls: %w", err)
|
||||
}
|
||||
var ms []machine
|
||||
if len(bytes.TrimSpace(out)) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
if err := json.Unmarshal(out, &ms); err != nil {
|
||||
return nil, fmt.Errorf("smolvm machine ls: %w", err)
|
||||
}
|
||||
return ms, nil
|
||||
}
|
||||
|
||||
// ours returns this devvm's machines: those with its label.
|
||||
func (s *Smolvm) ours(ctx context.Context) ([]machine, error) {
|
||||
ms, err := s.list(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return slices.DeleteFunc(ms, func(m machine) bool { return m.Labels[LabelKey] != s.Dirs.Data }), nil
|
||||
}
|
||||
|
||||
// errForeign is a machine by a name devvm uses that isn't its own.
|
||||
var errForeign = errors.New("not this devvm's machine")
|
||||
|
||||
// inspect returns one of devvm's machines, an error matching
|
||||
// backend.ErrNotFound when smolvm has none by that name, or one matching
|
||||
// errForeign when the machine by that name isn't this devvm's: devvm never
|
||||
// touches it.
|
||||
func (s *Smolvm) inspect(ctx context.Context, name string) (machine, error) {
|
||||
ms, err := s.list(ctx)
|
||||
if err != nil {
|
||||
return machine{}, err
|
||||
}
|
||||
for _, m := range ms {
|
||||
if m.Name != name {
|
||||
continue
|
||||
}
|
||||
if m.Labels[LabelKey] != s.Dirs.Data {
|
||||
return machine{}, fmt.Errorf("%s: %w", name, errForeign)
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
return machine{}, fmt.Errorf("%s: %w", name, backend.ErrNotFound)
|
||||
}
|
||||
|
||||
// absent checks smolvm has no machine by that name: one of devvm's is an
|
||||
// error, and so is anyone else's (smolvm_machine_foreign).
|
||||
func (s *Smolvm) absent(ctx context.Context, name string) error {
|
||||
_, err := s.inspect(ctx, name)
|
||||
switch {
|
||||
case errors.Is(err, backend.ErrNotFound):
|
||||
return nil
|
||||
case errors.Is(err, errForeign):
|
||||
return msg.SmolvmMachineForeign(name)
|
||||
case err != nil:
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("smolvm: %s exists already", name)
|
||||
}
|
||||
|
||||
// update changes a stopped machine's settings, with machine update's
|
||||
// options.
|
||||
func (s *Smolvm) update(ctx context.Context, vm string, opts ...string) error {
|
||||
if len(opts) == 0 {
|
||||
return nil
|
||||
}
|
||||
args := append([]string{"machine", "update", "--name", vm}, opts...)
|
||||
if err := s.Runner.Run(ctx, msg.Configuring(vm), s.smolvm(ctx, args...)); err != nil {
|
||||
return backend.Logged(msg.SmolvmUpdateFailed(vm))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// stop stops a machine, and its port forwarder.
|
||||
func (s *Smolvm) stop(ctx context.Context, vm string) error {
|
||||
s.Forwards.Stop(vm)
|
||||
if err := s.Runner.Run(ctx, msg.Stopping(vm), s.smolvm(ctx, "machine", "stop", "--name", vm)); err != nil {
|
||||
return backend.Logged(msg.StopFailed(vm))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// remove deletes a machine and what devvm keeps for it.
|
||||
func (s *Smolvm) remove(ctx context.Context, vm string) error {
|
||||
s.Forwards.Stop(vm)
|
||||
if err := s.Runner.Run(ctx, msg.Deleting(vm), s.smolvm(ctx, "machine", "delete", "--name", vm, "-f")); err != nil {
|
||||
return backend.Logged(msg.DeleteFailed(vm))
|
||||
}
|
||||
return s.Forwards.Forget(vm)
|
||||
}
|
||||
|
||||
// removeIfThere deletes one of devvm's machines if smolvm has it.
|
||||
func (s *Smolvm) removeIfThere(ctx context.Context, vm string) error {
|
||||
if _, err := s.inspect(ctx, vm); errors.Is(err, backend.ErrNotFound) {
|
||||
return nil
|
||||
} else if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.remove(ctx, vm)
|
||||
}
|
||||
|
||||
// asRoot is a command run as root in a running machine, its input fed to
|
||||
// sh: devvm's own scripts.
|
||||
func (s *Smolvm) asRoot(ctx context.Context, vm string, args ...string) *exec.Cmd {
|
||||
a := append(append([]string{"machine", "exec", "--name", vm}, s.proxyArgs(vm)...), "-i", "--", "sh", "-s", "--")
|
||||
return s.smolvm(ctx, append(a, args...)...)
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package smolvm
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/w3cj/devvm/assets"
|
||||
"github.com/w3cj/devvm/internal/backend"
|
||||
"github.com/w3cj/devvm/internal/paths"
|
||||
"github.com/w3cj/devvm/internal/platform"
|
||||
)
|
||||
|
||||
// TestE2EExecQuoting checks, on a real running machine, that what Exec
|
||||
// runs reaches it as given: arguments with spaces, quotes, $, newlines and
|
||||
// globs, and a folder with a space; and that it runs as the VM's user, with
|
||||
// a login's environment. tests/e2e.sh runs it on a VM it made, named by
|
||||
// DEVVM_E2E_VM, in its sandbox; otherwise it's skipped.
|
||||
func TestE2EExecQuoting(t *testing.T) {
|
||||
vm := os.Getenv("DEVVM_E2E_VM")
|
||||
if vm == "" {
|
||||
t.Skip("tests/e2e.sh runs it, on a VM of its own")
|
||||
}
|
||||
d, err := paths.FromEnv()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := New(d, assets.FS, testUI{}, platform.Host{})
|
||||
args := []string{
|
||||
"a b", " two spaces ", `"double"`, "'single'", `it's`, "$HOME", "${HOME}", "$(id -u)", "`id -u`",
|
||||
"a\nb", "tab\there", "*", "?", "[ab]", "/*", "~", "~root", `back\slash`, `\n`, "", "-n", "--",
|
||||
";", "&&", "|", ">x", "<x", "#c", "!", "%s", "é ünï",
|
||||
}
|
||||
var out, errOut bytes.Buffer
|
||||
argv := append([]string{"printf", `%s\0`}, args...)
|
||||
if err := s.Exec(t.Context(), vm, argv, backend.ExecOpts{Stdout: &out, Stderr: &errOut}); err != nil {
|
||||
t.Fatalf("Exec: %v\n%s", err, errOut.String())
|
||||
}
|
||||
got := strings.Split(strings.TrimSuffix(out.String(), "\x00"), "\x00")
|
||||
if !slices.Equal(got, args) {
|
||||
t.Errorf("the guest got %q,\nwant %q", got, args)
|
||||
}
|
||||
|
||||
dir := "/tmp/devvm e2e 'q' $x"
|
||||
if err := s.Exec(t.Context(), vm, []string{"mkdir", "-p", dir}, backend.ExecOpts{Stderr: &errOut}); err != nil {
|
||||
t.Fatalf("mkdir: %v\n%s", err, errOut.String())
|
||||
}
|
||||
out.Reset()
|
||||
if err := s.Exec(t.Context(), vm, []string{"pwd"}, backend.ExecOpts{Dir: dir, Stdout: &out, Stderr: &errOut}); err != nil {
|
||||
t.Fatalf("pwd: %v\n%s", err, errOut.String())
|
||||
}
|
||||
if got := strings.TrimSuffix(out.String(), "\n"); got != dir {
|
||||
t.Errorf("pwd in %q = %q", dir, got)
|
||||
}
|
||||
out.Reset()
|
||||
if err := s.Exec(t.Context(), vm, []string{"cat"}, backend.ExecOpts{Stdin: strings.NewReader("in\n$x\n"), Stdout: &out}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out.String() != "in\n$x\n" {
|
||||
t.Errorf("cat = %q", out.String())
|
||||
}
|
||||
// The VM's user, its home, and /etc/environment's BASH_ENV.
|
||||
out.Reset()
|
||||
if err := s.Exec(t.Context(), vm, []string{"sh", "-c", `echo "$(id -un) $HOME $USER $BASH_ENV"`}, backend.ExecOpts{Stdout: &out}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
name, _, err := s.user()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := name + " " + home(name) + " " + name + " /etc/profile.d/devvm-tools.sh\n"; out.String() != want {
|
||||
t.Errorf("as %q, want %q", out.String(), want)
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package smolvm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
|
||||
"github.com/w3cj/devvm/internal/backend/vmssh"
|
||||
)
|
||||
|
||||
// Forwarding ports (ports, ports-all) is emulated, and reviewed, so every
|
||||
// backend forwards by the same rules: smolvm forwards only the ports a
|
||||
// machine was made or updated with, at most 64, only to servers listening
|
||||
// on all of the guest's addresses, and shares a port a host program has
|
||||
// (SO_REUSEADDR). So a VM's ports get none of smolvm's forwards, and
|
||||
// devvm's forwarder instead (vmssh.Forwarder, devvm _smolvm-ports, started
|
||||
// by Start once its sshd runs): every port, or its listed ones less those
|
||||
// a host program has (Confinement.Free). It reaches the VM's sshd on its
|
||||
// forward on the host's loopback, smolvm's one forward, and ends when the
|
||||
// machine's process does (its lifeline, agent.pid). Which ports a VM
|
||||
// forwards is its record's (PortsAll, Listed), set by CreateVM and
|
||||
// SetPorts, which edit no forward of smolvm's and start a running VM's
|
||||
// forwarder again.
|
||||
|
||||
// forwarderCmd is the hidden command that runs a VM's forwarder.
|
||||
const forwarderCmd = "_smolvm-ports"
|
||||
|
||||
// ForwardMain runs a VM's forwarder (devvm _smolvm-ports) with its
|
||||
// arguments: ports.sh is script, reserved the ports devvm records for VMs
|
||||
// (but the VM's own listed ones), and its lines go to log. Besides the
|
||||
// forwarder's own flags, it takes the machine's lifeline and the host port
|
||||
// its sshd is forwarded from.
|
||||
func ForwardMain(ctx context.Context, args []string, script []byte, reserved func(vm string) (map[int]bool, error), log io.Writer) error {
|
||||
return vmssh.LifelineMain(ctx, forwarderCmd, args, script, reserved, log)
|
||||
}
|
||||
@@ -1,252 +0,0 @@
|
||||
package smolvm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/w3cj/devvm/internal/backend"
|
||||
"github.com/w3cj/devvm/internal/daemon"
|
||||
"github.com/w3cj/devvm/internal/msg"
|
||||
)
|
||||
|
||||
// A forwarder needs the machine's lifeline.
|
||||
func TestForwardMainLifeline(t *testing.T) {
|
||||
if err := ForwardMain(t.Context(), []string{"-vm", "v", "-user", "u", "-key", "/k", "-known-hosts", "/kh", "-control", "/c", "-port", "1"}, nil,
|
||||
func(string) (map[int]bool, error) { return nil, nil }, &strings.Builder{}); err == nil {
|
||||
t.Error("no lifeline: ran")
|
||||
}
|
||||
}
|
||||
|
||||
// A VM that forwards every port gets none of smolvm's, and its forwarder
|
||||
// once its sshd runs: its host key pinned, its ssh's, proxy's and
|
||||
// decider's ports reserved; stopping or deleting the VM stops it.
|
||||
func TestStartForwarder(t *testing.T) {
|
||||
s := newSandbox(t)
|
||||
vm := "devvm-a-0123456789abcd"
|
||||
s.image(t, "0123456789ab")
|
||||
spec := backend.VMSpec{Name: vm, Ports: backend.Ports{All: true}}
|
||||
if err := s.CreateVM(t.Context(), "0123456789ab", spec); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := s.calls(t); len(got) != 1 || strings.Contains(got[0], " -p ") {
|
||||
t.Errorf("create: %q", got)
|
||||
}
|
||||
var args []string
|
||||
s.fakeForwarder(t, vm, &args)
|
||||
running := false
|
||||
s.Forwards.Args = func(int) ([]string, error) {
|
||||
if !running {
|
||||
return nil, errors.New("gone")
|
||||
}
|
||||
return []string{"/devvm", forwarderCmd, "-vm", vm}, nil
|
||||
}
|
||||
var warned msg.Recorder
|
||||
s.Warn = warned.Add
|
||||
c := backend.Confinement{SSH: true, Net: backend.NetDirect, ProxyPort: 30001, Decider: "127.0.0.1:30002"}
|
||||
if err := s.Start(t.Context(), vm, c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(warned.Names()) != 0 {
|
||||
t.Errorf("warned %q", warned.Names())
|
||||
}
|
||||
r, _ := s.readRecord(vm)
|
||||
want := []string{
|
||||
"/devvm", "_smolvm-ports", "-vm", vm, "-lifeline", filepath.Join(s.stub, "smolvm-data", vm, "agent.pid"),
|
||||
"-port", "61022", "-user", "u", "-key", s.sshKey(vm), "-known-hosts", s.Forwards.KnownHosts(vm),
|
||||
"-control", s.Forwards.Control(vm), "-reserve", "61022,30001,30002",
|
||||
}
|
||||
if !r.PortsAll || !slices.Equal(args, want) {
|
||||
t.Errorf("forwarder:\n%q\nwant\n%q", args, want)
|
||||
}
|
||||
if !strings.HasPrefix(filepath.Base(s.Forwards.Control(vm)), "smolvm-") || filepath.Dir(s.Forwards.KnownHosts(vm)) != s.Dirs.VM(vm).Backend() {
|
||||
t.Errorf("its files: %s, %s", s.Forwards.Control(vm), s.Forwards.KnownHosts(vm))
|
||||
}
|
||||
if b, err := os.ReadFile(s.Forwards.KnownHosts(vm)); err != nil || string(b) != vm+" ssh-ed25519 AAAAstub\n" {
|
||||
t.Errorf("known_hosts: %q, %v", b, err)
|
||||
}
|
||||
if !slices.Contains(s.calls(t), "smolvm machine exec --name "+vm+" -- cat /etc/ssh/ssh_host_ed25519_key.pub") {
|
||||
t.Errorf("host key not read through smolvm: %q", s.calls(t))
|
||||
}
|
||||
running = true
|
||||
if !s.Forwards.Running(vm) {
|
||||
t.Error("forwarder not found")
|
||||
}
|
||||
running = false
|
||||
|
||||
// Without sshd: warned, no forwarder.
|
||||
if err := s.Stop(t.Context(), vm); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.stubs.Touch(t, "no-sshd")
|
||||
args = nil
|
||||
if err := s.Start(t.Context(), vm, c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if args != nil || !slices.Contains(warned.Names(), "ports_no_ssh vm="+vm) {
|
||||
t.Errorf("no sshd: forwarder %q, warned %q", args, warned.Names())
|
||||
}
|
||||
if err := os.Remove(filepath.Join(s.stub, "no-sshd")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A forwarder that never says it forwards: warned, the VM runs on.
|
||||
if err := s.Stop(t.Context(), vm); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
warned.Reset()
|
||||
s.Forwards.Detach = func(daemon.Cmd) (int, error) { return os.Getpid(), nil }
|
||||
if err := s.Start(t.Context(), vm, c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !slices.Equal(warned.Names(), []string{"ports_forward_failed log=" + s.Forwards.Log(vm) + " vm=" + vm}) {
|
||||
t.Errorf("warned %q", warned.Names())
|
||||
}
|
||||
|
||||
if err := s.Delete(t.Context(), vm); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Its backend folder goes with it: the forwarder's files, its record
|
||||
// and key.
|
||||
if _, err := os.Stat(s.Dirs.VM(vm).Backend()); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Errorf("its backend folder left: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// fakeForwarder makes a VM's forwarder one that says it forwards at once,
|
||||
// its arguments kept in args, with a short folder for its control socket:
|
||||
// a test's temporary one can be too long for one.
|
||||
func (s sandbox) fakeForwarder(t *testing.T, _ string, args *[]string) {
|
||||
t.Helper()
|
||||
short, err := os.MkdirTemp("/tmp", "dv")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = os.RemoveAll(short) })
|
||||
s.Forwards.Run = short
|
||||
s.Forwards.Detach = func(c daemon.Cmd) (int, error) {
|
||||
*args = append([]string{c.Path}, c.Args...)
|
||||
return os.Getpid(), daemon.WriteStatus(c.Status, os.Getpid(), "")
|
||||
}
|
||||
}
|
||||
|
||||
// A VM's listed ports are recorded, none of smolvm's, however many: its
|
||||
// forwarder forwards them alone (-only), those Confinement.Free leaves (a
|
||||
// host program's left out); with none, no forwarder runs. A running VM's
|
||||
// change starts its forwarder again with the new ports.
|
||||
func TestStartListedForwarder(t *testing.T) {
|
||||
s := newSandbox(t)
|
||||
vm := "devvm-l-0123456789abcd"
|
||||
s.image(t, "0123456789ab")
|
||||
listed := []backend.PortRange{{From: 22, To: 22}, {From: 3000, To: 3000}, {From: 8000, To: 8100}}
|
||||
if err := s.CreateVM(t.Context(), "0123456789ab", backend.VMSpec{Name: vm, Ports: backend.Ports{Ranges: listed}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var args []string
|
||||
var warned msg.Recorder
|
||||
s.fakeForwarder(t, vm, &args)
|
||||
s.Warn = warned.Add
|
||||
c := backend.Confinement{SSH: true, Net: backend.NetDirect}
|
||||
for _, tc := range []struct {
|
||||
free []backend.PortRange // nil for no Free
|
||||
only string // "" for no forwarder
|
||||
}{
|
||||
{nil, "22,3000,8000-8100"},
|
||||
{listed[2:], "8000-8100"},
|
||||
{[]backend.PortRange{}, ""},
|
||||
} {
|
||||
args = nil
|
||||
warned.Reset()
|
||||
c.Free = nil
|
||||
if tc.free != nil {
|
||||
c.Free = func(_ context.Context, rs []backend.PortRange) []backend.PortRange {
|
||||
if !slices.Equal(rs, listed) {
|
||||
t.Errorf("Free asked of %v", rs)
|
||||
}
|
||||
return tc.free
|
||||
}
|
||||
}
|
||||
if err := s.Start(t.Context(), vm, c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
i := slices.Index(args, "-only")
|
||||
if tc.only == "" && args != nil || tc.only != "" && (i < 0 || i+1 >= len(args) || args[i+1] != tc.only) || len(warned.Names()) != 0 {
|
||||
t.Errorf("only %q: forwarder %q, warned %q", tc.only, args, warned.Names())
|
||||
}
|
||||
if err := s.Stop(t.Context(), vm); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, call := range s.calls(t) {
|
||||
if strings.HasPrefix(call, "smolvm machine") && strings.Contains(call, " -p ") && !strings.HasSuffix(call, ":22") {
|
||||
t.Errorf("smolvm forwards a listed port: %q", call)
|
||||
}
|
||||
}
|
||||
// Every port again: the record alone changes.
|
||||
s.stubs.Reset(t)
|
||||
args = nil
|
||||
if err := s.SetPorts(t.Context(), vm, backend.Ports{All: true}, backend.Confinement{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r, _ := s.readRecord(vm); !r.PortsAll || r.Listed != nil || len(s.calls(t)) != 0 || args != nil {
|
||||
t.Errorf("all: %+v, %q, forwarder %q", r, s.calls(t), args)
|
||||
}
|
||||
|
||||
// Running: its forwarder starts again with the new ports at once, the
|
||||
// VM left running; none starts none.
|
||||
c.Free = nil
|
||||
if err := s.Start(t.Context(), vm, c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if slices.Contains(args, "-only") {
|
||||
t.Errorf("all: forwarder %q", args)
|
||||
}
|
||||
s.stubs.Reset(t)
|
||||
args = nil
|
||||
c = backend.Confinement{ProxyPort: 30001, Free: func(_ context.Context, rs []backend.PortRange) []backend.PortRange { return rs[1:] }}
|
||||
if err := s.SetPorts(t.Context(), vm, backend.Ports{Ranges: listed}, c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if i := slices.Index(args, "-only"); i < 0 || args[i+1] != "3000,8000-8100" || !slices.Contains(args, "61022,30001") {
|
||||
t.Errorf("running: forwarder %q", args)
|
||||
}
|
||||
for _, call := range s.calls(t) {
|
||||
if strings.Contains(call, "machine stop") || strings.Contains(call, "machine start") {
|
||||
t.Errorf("running: %q", call)
|
||||
}
|
||||
}
|
||||
args = nil
|
||||
if err := s.SetPorts(t.Context(), vm, backend.Ports{}, c); err != nil || args != nil {
|
||||
t.Errorf("running, none: forwarder %q, %v", args, err)
|
||||
}
|
||||
// A forward given a record read before another devvm's change: the
|
||||
// record's ports as they are now (none), so no forwarder.
|
||||
stale, err := s.readRecord(vm)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stale.Listed = listed
|
||||
args = nil
|
||||
if s.forward(t.Context(), vm, stale, c); args != nil {
|
||||
t.Errorf("stale record: forwarder %q", args)
|
||||
}
|
||||
// Started outside devvm since (another lifeline): no sshd of devvm's,
|
||||
// so no forwarder, warned; the record changes all the same.
|
||||
other := []byte(strconv.Itoa(os.Getpid()) + "\n1")
|
||||
if err := os.WriteFile(filepath.Join(s.stub, "smolvm-data", vm, "agent.pid"), other, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
args = nil
|
||||
warned.Reset()
|
||||
if err := s.SetPorts(t.Context(), vm, backend.Ports{Ranges: listed}, c); err != nil || args != nil ||
|
||||
!slices.Equal(warned.Names(), []string{"ports_no_ssh vm=" + vm}) {
|
||||
t.Errorf("started elsewhere: forwarder %q, warned %q, %v", args, warned.Names(), err)
|
||||
}
|
||||
if r, _ := s.readRecord(vm); !slices.Equal(r.Listed, listed) {
|
||||
t.Errorf("started elsewhere: record %+v", r)
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
package smolvm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/w3cj/devvm/internal/backend"
|
||||
)
|
||||
|
||||
var (
|
||||
_ backend.Locator = (*Smolvm)(nil)
|
||||
_ backend.Forgetter = (*Smolvm)(nil)
|
||||
_ backend.StrayFinder = (*Smolvm)(nil)
|
||||
)
|
||||
|
||||
// Location is where smolvm keeps this run's machines: on macOS the user's
|
||||
// own smolvm state, under HOME (a devvm run with another HOME sees other
|
||||
// machines); on Linux smolvm's state in devvm's data folder.
|
||||
func (s *Smolvm) Location() (string, bool) {
|
||||
if s.OS == "darwin" {
|
||||
return s.Dirs.Home, true
|
||||
}
|
||||
return s.stateDir(), true
|
||||
}
|
||||
|
||||
// Forget deletes what devvm keeps for a machine smolvm no longer has (or
|
||||
// has as someone else's): its backend folder, with its record, proxy
|
||||
// file, ssh key and port forwarder's files, its forwarder stopped first.
|
||||
// One of devvm's machines that smolvm has is refused.
|
||||
func (s *Smolvm) Forget(ctx context.Context, vm string) error {
|
||||
if _, err := s.inspect(ctx, vm); err == nil {
|
||||
return fmt.Errorf("smolvm: %s exists", vm)
|
||||
} else if !errors.Is(err, backend.ErrNotFound) && !errors.Is(err, errForeign) {
|
||||
return err
|
||||
}
|
||||
return s.Forwards.Forget(vm)
|
||||
}
|
||||
|
||||
// Strays are the project machines with devvm's label that this devvm has
|
||||
// no state for: another devvm's (its label names another data folder),
|
||||
// or this devvm's whose state is gone. Images' and the tools build's
|
||||
// machines aren't project machines.
|
||||
func (s *Smolvm) Strays(ctx context.Context) ([]backend.Stray, error) {
|
||||
ms, err := s.list(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []backend.Stray
|
||||
for _, m := range ms {
|
||||
data, labelled := m.Labels[LabelKey]
|
||||
if _, isImage := imageKey(m.Name); !labelled || isImage || m.Name == ToolsVM {
|
||||
continue
|
||||
}
|
||||
if data != s.Dirs.Data {
|
||||
out = append(out, backend.Stray{Name: m.Name, Data: data})
|
||||
} else if _, err := os.Stat(s.Dirs.VM(m.Name).State()); errors.Is(err, os.ErrNotExist) {
|
||||
out = append(out, backend.Stray{Name: m.Name, Data: data})
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package smolvm
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"time"
|
||||
|
||||
"github.com/w3cj/devvm/internal/backend/vmssh"
|
||||
"github.com/w3cj/devvm/internal/daemon"
|
||||
"github.com/w3cj/devvm/internal/paths"
|
||||
"github.com/w3cj/devvm/internal/platform"
|
||||
)
|
||||
|
||||
// newForwards is how smolvm's VMs' forwarders run: devvm _smolvm-ports,
|
||||
// self, its files in each VM's backend folder.
|
||||
func newForwards(d paths.Dirs, self string) vmssh.Forwards {
|
||||
return vmssh.Forwards{
|
||||
Dirs: d, Prefix: "smolvm", Cmd: forwarderCmd, Self: self,
|
||||
Detach: daemon.Detach, Args: platform.ProcessArgs, Tick: 500 * time.Millisecond,
|
||||
}
|
||||
}
|
||||
|
||||
// deciderPort is the port of a decider's address (127.0.0.1:PORT), 0 for
|
||||
// none.
|
||||
func deciderPort(addr string) int {
|
||||
ap, err := netip.ParseAddrPort(addr)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return int(ap.Port())
|
||||
}
|
||||
@@ -1,618 +0,0 @@
|
||||
// Package smolvm is the smolvm backend (experimental): each VM is a smolvm
|
||||
// machine, a microVM running its image as a container, with no init
|
||||
// system. Images are packs (smolvm pack create --from-vm) in devvm's data
|
||||
// folder, and a project VM is a machine made from its image's pack.
|
||||
//
|
||||
// On macOS smolvm keeps every machine in the user's own state, so devvm's
|
||||
// carry a label naming devvm's data folder, and devvm never stops, changes
|
||||
// or deletes a machine without it. On Linux smolvm's state is devvm's own
|
||||
// (--state-dir) as well.
|
||||
//
|
||||
// Network policy is emulated, reviewed (start.go); ssh for editors is
|
||||
// emulated, reviewed (ssh.go); forwarding ports, every one or the listed
|
||||
// ones, is emulated, reviewed (forward.go, vmssh.Forwarder); turning agent
|
||||
// forwarding on or off later is emulated, reviewed (agent.go).
|
||||
package smolvm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"maps"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/w3cj/devvm/internal/backend"
|
||||
"github.com/w3cj/devvm/internal/backend/vmssh"
|
||||
"github.com/w3cj/devvm/internal/image"
|
||||
"github.com/w3cj/devvm/internal/msg"
|
||||
"github.com/w3cj/devvm/internal/paths"
|
||||
"github.com/w3cj/devvm/internal/platform"
|
||||
"github.com/w3cj/devvm/internal/state"
|
||||
"github.com/w3cj/devvm/internal/ubuntu"
|
||||
)
|
||||
|
||||
// Name is the backend's name.
|
||||
const Name = "smolvm"
|
||||
|
||||
// ImagePrefix starts the name of an image's build machine:
|
||||
// devvm-img-<key>. Once built, the image is its pack.
|
||||
const ImagePrefix = "devvm-img-"
|
||||
|
||||
// LabelKey is the label every machine devvm makes carries, its value
|
||||
// devvm's data folder.
|
||||
const LabelKey = "devvm.data"
|
||||
|
||||
// Gateway is the host as a machine reaches it.
|
||||
const Gateway = "100.96.0.1"
|
||||
|
||||
// Smolvm is the backend. New sets every field; tests change them.
|
||||
type Smolvm struct {
|
||||
Dirs paths.Dirs
|
||||
Runner Runner
|
||||
// OS and Arch are the host's, as Go names them.
|
||||
OS, Arch string
|
||||
// Assets holds devvm's own files (assets.FS): base.yaml (base's CPUs,
|
||||
// memory and disk) and the scripts smolvm/ has, run as root in
|
||||
// machines.
|
||||
Assets fs.FS
|
||||
// Getenv reads the environment (SSH_AUTH_SOCK).
|
||||
Getenv func(string) string
|
||||
// User is the host's user, whose name and uid the VM's user gets.
|
||||
User func() (*user.User, error)
|
||||
// Memory returns the host's memory in bytes.
|
||||
Memory func() (uint64, error)
|
||||
// CPUs returns the host's CPU count.
|
||||
CPUs func() int
|
||||
// KVM is Linux's KVM device: /dev/kvm, unless a test build stands in
|
||||
// for it.
|
||||
KVM string
|
||||
// Terminal reports whether devvm's input is a terminal (a shell gets
|
||||
// one then).
|
||||
Terminal func() bool
|
||||
// FreePort returns a port free on the host's loopback, and PortFree
|
||||
// reports whether one is: for a VM's ssh forward.
|
||||
FreePort func(context.Context) (int, error)
|
||||
PortFree func(context.Context, int) bool
|
||||
// Info prints what the backend is doing.
|
||||
Info func(msg.M)
|
||||
// Warn prints a warning.
|
||||
Warn func(msg.M)
|
||||
// WithSteps numbers the logged commands of a phase of so many steps.
|
||||
WithSteps func(ctx context.Context, total int) context.Context
|
||||
// AddCleanup adds to the run's cleanup stack; Interrupted reports
|
||||
// whether the run was interrupted.
|
||||
AddCleanup func(f func(context.Context)) (remove func())
|
||||
Interrupted func() bool
|
||||
// Forwards runs the port forwarders of VMs that forward every port.
|
||||
Forwards vmssh.Forwards
|
||||
}
|
||||
|
||||
// UI is where the backend prints, the run log its commands run into, the
|
||||
// run's cleanup stack, and whether devvm's input is a terminal.
|
||||
type UI interface {
|
||||
Info(msg.M)
|
||||
Warn(msg.M)
|
||||
StdinIsTerminal() bool
|
||||
LoggedCmd(ctx context.Context, step msg.M, cmd *exec.Cmd) error
|
||||
WithSteps(ctx context.Context, total int) context.Context
|
||||
AddCleanup(f func(context.Context)) (remove func())
|
||||
Interrupted() bool
|
||||
}
|
||||
|
||||
var (
|
||||
_ backend.Backend = (*Smolvm)(nil)
|
||||
_ backend.Storage = (*Smolvm)(nil)
|
||||
)
|
||||
|
||||
// New returns the smolvm backend for devvm's folders and its own files
|
||||
// (assets), on u, sizing base to host.
|
||||
func New(d paths.Dirs, assets fs.FS, u UI, host platform.Host) *Smolvm {
|
||||
self, err := os.Executable()
|
||||
if err == nil {
|
||||
if r, rerr := filepath.EvalSymlinks(self); rerr == nil {
|
||||
self = r
|
||||
}
|
||||
}
|
||||
return &Smolvm{
|
||||
Dirs: d, Runner: logRunner{u.LoggedCmd}, OS: runtime.GOOS, Arch: runtime.GOARCH, Assets: assets,
|
||||
Getenv: os.Getenv, User: user.Current, Memory: host.Memory, CPUs: host.CPUs,
|
||||
KVM: "/dev/kvm",
|
||||
Terminal: u.StdinIsTerminal,
|
||||
FreePort: freePort, PortFree: platform.PortFree,
|
||||
Info: u.Info, Warn: u.Warn,
|
||||
WithSteps: u.WithSteps, AddCleanup: u.AddCleanup, Interrupted: u.Interrupted,
|
||||
Forwards: newForwards(d, self),
|
||||
}
|
||||
}
|
||||
|
||||
// Name returns smolvm.
|
||||
func (s *Smolvm) Name() string { return Name }
|
||||
|
||||
// Caps is what smolvm has natively, egress through devvm's proxy emulated
|
||||
// and reviewed (Start: an allow list of the host, and the proxy deciding
|
||||
// each connection), ssh for editors emulated and reviewed (an sshd of
|
||||
// devvm's, ssh.go), and ports forwarded, every one or the listed ones,
|
||||
// emulated and reviewed (a forwarder of devvm's over that ssh,
|
||||
// forward.go). Agent forwarding turned on or off once a VM is made is
|
||||
// emulated and reviewed (every VM made forwarding, an agent chosen at each
|
||||
// start, agent.go).
|
||||
func (s *Smolvm) Caps() backend.Caps {
|
||||
caps := backend.Caps{
|
||||
backend.FeatureEgressProxy: backend.Emulated(true), backend.FeatureSSH: backend.Emulated(true),
|
||||
backend.FeaturePorts: backend.Emulated(true), backend.FeaturePortsAll: backend.Emulated(true),
|
||||
backend.FeatureAgentToggle: backend.Emulated(true),
|
||||
}
|
||||
for _, f := range []backend.Feature{
|
||||
backend.FeatureBuildImage, backend.FeatureBuildConfinement, backend.FeatureFrom, backend.FeatureClone,
|
||||
backend.FeatureProjectMount, backend.FeatureAgentFolders, backend.FeatureToolsShare,
|
||||
backend.FeatureAgentForwarding, backend.FeatureCPUs, backend.FeatureMemory, backend.FeatureDisk,
|
||||
backend.FeatureDockerLayer, backend.FeatureNixLayer, backend.FeatureLink,
|
||||
} {
|
||||
caps[f] = backend.Native
|
||||
}
|
||||
return caps
|
||||
}
|
||||
|
||||
// UsesDecider is true: a machine with network policy reaches devvm's proxy
|
||||
// only through its decider (smolvm's mediated egress).
|
||||
func (s *Smolvm) UsesDecider() bool { return true }
|
||||
|
||||
// NameMax is 0: smolvm keeps a machine's sockets in a folder named by a
|
||||
// hash, so names have no limit devvm meets.
|
||||
func (s *Smolvm) NameMax() int { return 0 }
|
||||
|
||||
// script is one of devvm's scripts for smolvm: smolvm/<name> in Assets.
|
||||
func (s *Smolvm) script(name string) ([]byte, error) { return fs.ReadFile(s.Assets, "smolvm/"+name) }
|
||||
|
||||
// containerScript is one of smolvm's scripts for images run as
|
||||
// containers: container/<name> in Assets.
|
||||
func (s *Smolvm) containerScript(name string) ([]byte, error) {
|
||||
return fs.ReadFile(s.Assets, "container/"+name)
|
||||
}
|
||||
|
||||
// KeyFiles are devvm's scripts for smolvm that go into base, one missing
|
||||
// hashed as empty, and Ubuntu's pinned image.
|
||||
func (s *Smolvm) KeyFiles() map[string][]byte {
|
||||
files := map[string][]byte{"ubuntu-image": []byte(ubuntu.ContainerRef)}
|
||||
for _, n := range []string{"prepare.sh", "shims.sh", "sshd.sh"} {
|
||||
files["container/"+n], _ = s.containerScript(n)
|
||||
}
|
||||
return files
|
||||
}
|
||||
|
||||
// DiskDirs is devvm's smolvm folder, which holds the images' packs and, on
|
||||
// Linux, smolvm's state with the machines; on macOS smolvm keeps machines
|
||||
// under the user's home folder (backend.Storage).
|
||||
func (s *Smolvm) DiskDirs() []string {
|
||||
dirs := []string{s.Dirs.Smolvm()}
|
||||
if s.OS != "linux" && s.Dirs.Home != "" {
|
||||
dirs = append(dirs, s.Dirs.Home)
|
||||
}
|
||||
return dirs
|
||||
}
|
||||
|
||||
// Floors is the free space smolvm's steps want (backend.Storage),
|
||||
// measured with statfs on macOS in the e2e sandbox. Most of each step's
|
||||
// peak is gone when it ends: base took 1.9 GiB at its peak (0.3 kept),
|
||||
// the docker layer 2.3 (0.4 kept), and making a docker VM 2.2 at its
|
||||
// first start (8 MB kept). Shared tools builds took 0.55 GiB for node,
|
||||
// pnpm and bun, and 5.6 GiB for the other seven.
|
||||
func (s *Smolvm) Floors() backend.Floors {
|
||||
return backend.Floors{Base: 4 << 30, Image: 4 << 30, VM: 4 << 30, Tools: 4 << 30, PerTool: 512 << 20}
|
||||
}
|
||||
|
||||
// ToolFormat is uncompressed EROFS (plain.sh), as smolvm's kernel mounts
|
||||
// no other: its name changes with the script.
|
||||
func (s *Smolvm) ToolFormat() string {
|
||||
plain, _ := s.script("plain.sh") // missing, BuildTools fails
|
||||
sum := sha256.Sum256(plain)
|
||||
return "plain-" + hex.EncodeToString(sum[:])[:12]
|
||||
}
|
||||
|
||||
// record is what devvm set on one of its machines, which smolvm machine ls
|
||||
// doesn't show: kept in the VM's backend folder (paths.VM.Record).
|
||||
type record struct {
|
||||
Image string `json:"image"` // its image's key
|
||||
Project string `json:"project,omitempty"`
|
||||
AgentDirs []string `json:"agent_dirs,omitempty"`
|
||||
Tools string `json:"tools,omitempty"`
|
||||
ToolsAt string `json:"tools_at,omitempty"`
|
||||
// Forwarding is set when the machine was made forwarding an SSH
|
||||
// agent (--ssh-agent), which smolvm fixes then; AgentOff when devvm's
|
||||
// choice for it is none, so each start gives it no agent (agent.go).
|
||||
Forwarding bool `json:"forwarding,omitempty"`
|
||||
AgentOff bool `json:"agent_off,omitempty"`
|
||||
// PortsAll is set when it forwards every port, else Listed are those
|
||||
// it forwards: through its forwarder (forward.go), with none of
|
||||
// smolvm's.
|
||||
PortsAll bool `json:"ports_all,omitempty"`
|
||||
Listed []backend.PortRange `json:"listed_ports,omitempty"`
|
||||
Env map[string]string `json:"env,omitempty"`
|
||||
// Mediated is set once the machine started through devvm's decider:
|
||||
// smolvm then requires one at every start, until devvm removes that.
|
||||
Mediated bool `json:"mediated,omitempty"`
|
||||
// Confined is the lifeline (agent.pid: its pid and start time) of the
|
||||
// machine's last start through devvm's decider; "" after any other.
|
||||
Confined string `json:"confined,omitempty"`
|
||||
// Started is the lifeline of the machine's last start by Start, with
|
||||
// the agent devvm chose (agent.go); "" while a start is under way.
|
||||
Started string `json:"started,omitempty"`
|
||||
// SSHPort is the host loopback port its sshd is forwarded from, set
|
||||
// while it's started with it (Confinement.SSH); 0 otherwise.
|
||||
SSHPort int `json:"ssh_port,omitempty"`
|
||||
// SSHUp is set once this start's sshd runs (services.sh done), and
|
||||
// cleared before each start.
|
||||
SSHUp bool `json:"ssh_up,omitempty"`
|
||||
// NoSSHD is set when its last start with ssh found no sshd in its
|
||||
// image: it runs without.
|
||||
NoSSHD bool `json:"no_sshd,omitempty"`
|
||||
}
|
||||
|
||||
// proxyFile holds the proxy URL, password and all, of a machine started
|
||||
// with network policy: Start writes it (mode 600), or removes it without.
|
||||
// devvm's execs name it (machine exec --secret-file), so smolvm reads it
|
||||
// and only its path is in smolvm's arguments. Not create's --secret-file:
|
||||
// smolvm ignores that for a machine made from a pack.
|
||||
func (s *Smolvm) proxyFile(vm string) string { return s.Dirs.VM(vm).ProxyURL() }
|
||||
|
||||
// setProxyFile writes the machine's proxy URL, or removes its file for "".
|
||||
func (s *Smolvm) setProxyFile(vm, u string) error {
|
||||
if u == "" {
|
||||
if err := os.Remove(s.proxyFile(vm)); err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return state.WriteFile(s.proxyFile(vm), []byte(u))
|
||||
}
|
||||
|
||||
// proxyArgs are machine exec's options that give the command the proxy
|
||||
// variables (backend.GuestProxyVars) from the machine's proxy file, none
|
||||
// when it has none.
|
||||
func (s *Smolvm) proxyArgs(vm string) []string {
|
||||
f := s.proxyFile(vm)
|
||||
if fi, err := os.Stat(f); err != nil || fi.Size() == 0 { //nolint:gosec // devvm's own file, in the VM's folder: the hash its name ends with
|
||||
return nil
|
||||
}
|
||||
var args []string
|
||||
for _, k := range backend.GuestProxyVars() {
|
||||
args = append(args, "--secret-file", k+"="+f)
|
||||
}
|
||||
return args
|
||||
}
|
||||
|
||||
func (s *Smolvm) readRecord(vm string) (record, error) {
|
||||
var r record
|
||||
b, err := os.ReadFile(s.Dirs.VM(vm).Record())
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return r, nil
|
||||
} else if err != nil {
|
||||
return r, err
|
||||
}
|
||||
return r, json.Unmarshal(b, &r)
|
||||
}
|
||||
|
||||
func (s *Smolvm) writeRecord(vm string, r record) error {
|
||||
b, err := json.MarshalIndent(r, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return state.WriteFile(s.Dirs.VM(vm).Record(), append(b, '\n'))
|
||||
}
|
||||
|
||||
// imageKey returns the key of an image's build machine, and whether it is
|
||||
// one.
|
||||
func imageKey(name string) (string, bool) {
|
||||
key, ok := strings.CutPrefix(name, ImagePrefix)
|
||||
return key, ok && image.IsKey(key)
|
||||
}
|
||||
|
||||
// pack is an image's pack: smolvm's stub, beside its .smolmachine.
|
||||
func (s *Smolvm) pack(key string) string { return filepath.Join(s.Dirs.SmolvmImage(key), "image") }
|
||||
|
||||
func (s *Smolvm) packFile(key string) string { return s.pack(key) + ".smolmachine" }
|
||||
|
||||
// stateDir is smolvm's own state on Linux hosts.
|
||||
func (s *Smolvm) stateDir() string { return filepath.Join(s.Dirs.Smolvm(), "state") }
|
||||
|
||||
// List lists devvm's machines, without images' and the tools build's.
|
||||
func (s *Smolvm) List(ctx context.Context) ([]backend.Instance, error) {
|
||||
ms, err := s.ours(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []backend.Instance
|
||||
for _, m := range ms {
|
||||
if _, ok := imageKey(m.Name); ok || m.Name == ToolsVM {
|
||||
continue
|
||||
}
|
||||
in, err := s.instance(m)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, in)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Inspect returns one of devvm's machines.
|
||||
func (s *Smolvm) Inspect(ctx context.Context, vm string) (backend.Instance, error) {
|
||||
m, err := s.inspect(ctx, vm)
|
||||
if errors.Is(err, errForeign) {
|
||||
return backend.Instance{}, fmt.Errorf("%s: %w", vm, backend.ErrNotFound)
|
||||
} else if err != nil {
|
||||
return backend.Instance{}, err
|
||||
}
|
||||
return s.instance(m)
|
||||
}
|
||||
|
||||
func (s *Smolvm) instance(m machine) (backend.Instance, error) {
|
||||
r, err := s.readRecord(m.Name)
|
||||
if err != nil {
|
||||
return backend.Instance{}, err
|
||||
}
|
||||
return backend.Instance{
|
||||
Name: m.Name, Status: m.status(), Size: m.size(),
|
||||
AgentDirs: slices.Clone(r.AgentDirs), AgentForwarding: r.Forwarding && !r.AgentOff, AgentFixed: !r.Forwarding,
|
||||
// smolvm forwards the agent from the machine's start, not
|
||||
// through ssh sessions.
|
||||
AgentWhileRunning: true,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Stop stops one of devvm's machines; a stopped one is left as it is.
|
||||
func (s *Smolvm) Stop(ctx context.Context, vm string) error {
|
||||
m, err := s.inspect(ctx, vm)
|
||||
if err != nil {
|
||||
return notFound(vm, err)
|
||||
}
|
||||
if m.status() == backend.StatusStopped {
|
||||
return nil
|
||||
}
|
||||
return s.stop(ctx, vm)
|
||||
}
|
||||
|
||||
// Delete deletes one of devvm's machines, stopping it first.
|
||||
func (s *Smolvm) Delete(ctx context.Context, vm string) error {
|
||||
if _, err := s.inspect(ctx, vm); err != nil {
|
||||
return notFound(vm, err)
|
||||
}
|
||||
return s.remove(ctx, vm)
|
||||
}
|
||||
|
||||
// notFound makes a machine that isn't devvm's one it doesn't have.
|
||||
func notFound(vm string, err error) error {
|
||||
if errors.Is(err, errForeign) {
|
||||
return fmt.Errorf("%s: %w", vm, backend.ErrNotFound)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// user is the VM's user: the host's name and uid.
|
||||
func (s *Smolvm) user() (name, uid string, err error) {
|
||||
u, err := s.User()
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return u.Username, u.Uid, nil
|
||||
}
|
||||
|
||||
func home(name string) string { return "/home/" + name + ".guest" }
|
||||
|
||||
// loginEnv is what runs a command as the VM's user would get from logging
|
||||
// in: smolvm's exec sets HOME alone, and reads no /etc/environment, which
|
||||
// devvm's scripts write to (BASH_ENV).
|
||||
const loginEnv = `set -a; [ -r /etc/environment ] && . /etc/environment; set +a; exec "$@"`
|
||||
|
||||
// userArgs are machine exec's arguments that run argv as the VM's user, in
|
||||
// dir.
|
||||
func (s *Smolvm) userArgs(vm, dir string, input, tty bool, argv []string) ([]string, error) {
|
||||
name, _, err := s.user()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if dir == "" {
|
||||
dir = "/"
|
||||
}
|
||||
args := append([]string{"machine", "exec", "--name", vm}, s.proxyArgs(vm)...)
|
||||
if input {
|
||||
args = append(args, "-i")
|
||||
}
|
||||
if tty {
|
||||
args = append(args, "-t")
|
||||
}
|
||||
args = append(args, "-u", name, "-w", dir,
|
||||
"-e", "USER="+name, "-e", "LOGNAME="+name, "-e", "HOME="+home(name), "-e", "SHELL=/bin/bash",
|
||||
"--", "sh", "-c", loginEnv, "sh")
|
||||
return append(args, argv...), nil
|
||||
}
|
||||
|
||||
// Exec runs argv in the VM as its user, in o.Dir. smolvm passes each
|
||||
// argument as it is: no shell reads them.
|
||||
func (s *Smolvm) Exec(ctx context.Context, vm string, argv []string, o backend.ExecOpts) error {
|
||||
args, err := s.userArgs(vm, o.Dir, o.Stdin != nil, false, argv)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cmd := s.smolvm(ctx, args...)
|
||||
cmd.Stdin, cmd.Stdout, cmd.Stderr = o.Stdin, o.Stdout, o.Stderr
|
||||
return s.Runner.Attach(cmd)
|
||||
}
|
||||
|
||||
// Shell returns a login shell in dir as the VM's user, with a terminal when
|
||||
// devvm has one.
|
||||
func (s *Smolvm) Shell(ctx context.Context, vm, dir string) (backend.Command, error) {
|
||||
args, err := s.userArgs(vm, dir, true, s.Terminal(), []string{"bash", "-l"})
|
||||
if err != nil {
|
||||
return backend.Command{}, err
|
||||
}
|
||||
cmd := s.smolvm(ctx, args...)
|
||||
if cmd.Err != nil {
|
||||
return backend.Command{}, cmd.Err
|
||||
}
|
||||
return backend.Command{Path: cmd.Path, Args: cmd.Args, Env: cmd.Env, Dir: cmd.Dir}, nil
|
||||
}
|
||||
|
||||
// stopped returns a machine that must be stopped to be changed, and its
|
||||
// record.
|
||||
func (s *Smolvm) stopped(ctx context.Context, vm string) (machine, record, error) {
|
||||
m, err := s.inspect(ctx, vm)
|
||||
if err != nil {
|
||||
return machine{}, record{}, notFound(vm, err)
|
||||
}
|
||||
if m.status() != backend.StatusStopped {
|
||||
return machine{}, record{}, msg.VMNotStopped(vm)
|
||||
}
|
||||
r, err := s.readRecord(vm)
|
||||
return m, r, err
|
||||
}
|
||||
|
||||
// SetSize changes a stopped VM's size where it differs. Disks only grow.
|
||||
func (s *Smolvm) SetSize(ctx context.Context, vm string, sz backend.Size) error {
|
||||
if sz == (backend.Size{}) {
|
||||
return nil
|
||||
}
|
||||
m, _, err := s.stopped(ctx, vm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cur := m.size()
|
||||
var opts []string
|
||||
if sz.CPUs > 0 && sz.CPUs != cur.CPUs {
|
||||
opts = append(opts, "--cpus", strconv.Itoa(sz.CPUs))
|
||||
}
|
||||
if sz.MemoryGiB > 0 && sz.MemoryGiB != cur.MemoryGiB {
|
||||
opts = append(opts, "--mem", mib(sz.MemoryGiB))
|
||||
}
|
||||
if sz.DiskGiB > 0 && sz.DiskGiB < cur.DiskGiB {
|
||||
return msg.DiskShrink(gibString(cur.DiskGiB), vm, gibString(sz.DiskGiB))
|
||||
}
|
||||
if sz.DiskGiB > cur.DiskGiB {
|
||||
opts = append(opts, "--storage", gibCeil(sz.DiskGiB))
|
||||
}
|
||||
return s.update(ctx, vm, opts...)
|
||||
}
|
||||
|
||||
func gibString(g float64) string { return strconv.FormatFloat(g, 'g', -1, 64) }
|
||||
|
||||
// mib is GiB as smolvm's --mem takes it.
|
||||
func mib(g float64) string { return strconv.Itoa(int(g * 1024)) }
|
||||
|
||||
// gibCeil is a disk size as smolvm's --storage takes it: whole GiB.
|
||||
func gibCeil(g float64) string {
|
||||
n := int(g)
|
||||
if float64(n) < g {
|
||||
n++
|
||||
}
|
||||
return strconv.Itoa(n)
|
||||
}
|
||||
|
||||
// listed is the ports a VM with ports p records as listed: none for
|
||||
// every one.
|
||||
func listed(p backend.Ports) []backend.PortRange {
|
||||
if p.All {
|
||||
return nil
|
||||
}
|
||||
return slices.Clone(p.Ranges)
|
||||
}
|
||||
|
||||
// SetPorts changes which of a VM's ports its forwarder forwards (every
|
||||
// one, its listed ones, or none): its record, which a stopped VM forwards
|
||||
// from its next start, and a running one's forwarder, started again with
|
||||
// them. Only devvm's record changes: smolvm forwards none of them. One
|
||||
// started outside devvm since has no sshd of devvm's to forward through.
|
||||
func (s *Smolvm) SetPorts(ctx context.Context, vm string, p backend.Ports, c backend.Confinement) error {
|
||||
m, err := s.inspect(ctx, vm)
|
||||
if err != nil {
|
||||
return notFound(vm, err)
|
||||
}
|
||||
r, err := s.readRecord(vm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if want := listed(p); r.PortsAll != p.All || !slices.Equal(r.Listed, want) {
|
||||
r.PortsAll, r.Listed = p.All, want
|
||||
if err := s.writeRecord(vm, r); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if m.status() != backend.StatusRunning {
|
||||
return nil
|
||||
}
|
||||
if cur, err := s.lifeline(ctx, vm); err != nil || !runsOn(cur, r.Started) {
|
||||
r.SSHUp = false
|
||||
}
|
||||
s.forward(ctx, vm, r, c)
|
||||
return nil
|
||||
}
|
||||
|
||||
// volume is a -v value: host path, its path in the VM, and :ro unless
|
||||
// writable. A path with a colon is refused: smolvm splits on colons.
|
||||
func volume(host, at string, writable bool) (string, error) {
|
||||
for _, p := range []string{host, at} {
|
||||
if strings.Contains(p, ":") {
|
||||
return "", msg.SmolvmMountColon(p)
|
||||
}
|
||||
}
|
||||
v := host + ":" + at
|
||||
if !writable {
|
||||
v += ":ro"
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// SetAgentDirs replaces a stopped VM's agent folder mounts.
|
||||
func (s *Smolvm) SetAgentDirs(ctx context.Context, vm string, dirs []string) error {
|
||||
_, r, err := s.stopped(ctx, vm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if slices.Equal(r.AgentDirs, dirs) {
|
||||
return nil
|
||||
}
|
||||
var opts []string
|
||||
for _, d := range r.AgentDirs {
|
||||
opts = append(opts, "--remove-volume", d+":"+d)
|
||||
}
|
||||
for _, d := range dirs {
|
||||
v, err := volume(d, d, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
opts = append(opts, "-v", v)
|
||||
}
|
||||
if err := s.update(ctx, vm, opts...); err != nil {
|
||||
return err
|
||||
}
|
||||
r.AgentDirs = slices.Clone(dirs)
|
||||
return s.writeRecord(vm, r)
|
||||
}
|
||||
|
||||
// ProxyURL is devvm's proxy as a machine reaches it, at the gateway; ""
|
||||
// unless c.Net is NetProxy.
|
||||
func (s *Smolvm) ProxyURL(c backend.Confinement) string {
|
||||
if c.Net != backend.NetProxy {
|
||||
return ""
|
||||
}
|
||||
return backend.ProxyURL(Gateway, c.ProxyPort, c.ProxyPassword)
|
||||
}
|
||||
|
||||
// sortedEnv is env as KEY=value, sorted.
|
||||
func sortedEnv(env map[string]string) []string {
|
||||
var out []string
|
||||
for _, k := range slices.Sorted(maps.Keys(env)) {
|
||||
out = append(out, k+"="+env[k])
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -1,857 +0,0 @@
|
||||
package smolvm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/w3cj/devvm/assets"
|
||||
"github.com/w3cj/devvm/internal/backend"
|
||||
"github.com/w3cj/devvm/internal/backend/vmssh"
|
||||
"github.com/w3cj/devvm/internal/daemon"
|
||||
"github.com/w3cj/devvm/internal/msg"
|
||||
"github.com/w3cj/devvm/internal/paths"
|
||||
"github.com/w3cj/devvm/internal/stubtest"
|
||||
"github.com/w3cj/devvm/internal/ubuntu"
|
||||
)
|
||||
|
||||
// testUI prints nothing, runs commands as they are, counts no steps and
|
||||
// keeps no cleanups.
|
||||
type testUI struct{}
|
||||
|
||||
func (testUI) Info(msg.M) {}
|
||||
func (testUI) Warn(msg.M) {}
|
||||
func (testUI) LoggedCmd(_ context.Context, _ msg.M, cmd *exec.Cmd) error { return cmd.Run() }
|
||||
func (testUI) WithSteps(ctx context.Context, _ int) context.Context { return ctx }
|
||||
func (testUI) AddCleanup(func(context.Context)) func() { return func() {} }
|
||||
func (testUI) Interrupted() bool { return false }
|
||||
func (testUI) StdinIsTerminal() bool { return false }
|
||||
|
||||
// sandbox is a smolvm backend on the stub (testdata/stubs/smolvm), first
|
||||
// on PATH, with devvm's folders in a new temporary folder; its user is u,
|
||||
// uid 501, on a host with 64 GiB.
|
||||
type sandbox struct {
|
||||
*Smolvm
|
||||
stubs *stubtest.Stubs
|
||||
stub string // stubs.Dir
|
||||
}
|
||||
|
||||
func newSandbox(t *testing.T) sandbox {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
for _, d := range []string{"data", "config"} {
|
||||
if err := os.MkdirAll(filepath.Join(root, d), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
stubs := stubtest.New(t)
|
||||
t.Setenv("SMOLVM_MACHINE_NAME", "users-own")
|
||||
d := paths.Dirs{Data: filepath.Join(root, "data"), Config: filepath.Join(root, "config"), Lima: filepath.Join(root, "lima")}
|
||||
s := &Smolvm{
|
||||
Dirs: d, Runner: stubtest.ExecRunner{}, OS: "darwin", Arch: "arm64", Assets: assets.FS,
|
||||
Getenv: func(string) string { return "" },
|
||||
User: func() (*user.User, error) { return &user.User{Username: "u", Uid: "501"}, nil },
|
||||
Memory: func() (uint64, error) { return 64 << 30, nil }, CPUs: func() int { return 8 },
|
||||
KVM: "/dev/kvm", Terminal: func() bool { return false },
|
||||
FreePort: func(context.Context) (int, error) { return 61022, nil }, PortFree: func(context.Context, int) bool { return true },
|
||||
Info: func(msg.M) {}, Warn: func(msg.M) {},
|
||||
WithSteps: testUI{}.WithSteps, AddCleanup: testUI{}.AddCleanup, Interrupted: testUI{}.Interrupted,
|
||||
Forwards: func() vmssh.Forwards {
|
||||
f := newForwards(d, "/devvm")
|
||||
f.Tick = time.Millisecond
|
||||
f.Detach = func(daemon.Cmd) (int, error) { return 0, errors.New("no forwarder here") }
|
||||
f.Args = func(int) ([]string, error) { return nil, errors.New("no process") }
|
||||
return f
|
||||
}(),
|
||||
}
|
||||
return sandbox{s, stubs, stubs.Dir}
|
||||
}
|
||||
|
||||
// calls are the stub's calls, without the reads.
|
||||
func (s sandbox) calls(t *testing.T) []string {
|
||||
t.Helper()
|
||||
var out []string
|
||||
for _, l := range s.stubs.Calls(t) {
|
||||
if l != "smolvm machine ls --json" && !strings.HasPrefix(l, "smolvm machine data-dir") {
|
||||
out = append(out, l)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// machine makes a stub machine: "STATE CPUS MEM STORAGE NET", with this
|
||||
// devvm's label.
|
||||
func (s sandbox) machine(t *testing.T, name, fields string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(filepath.Join(s.stub, "smolvm"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(s.stub, "smolvm", name), []byte(fields+" "+s.Dirs.Data+"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// image makes an image's pack.
|
||||
func (s sandbox) image(t *testing.T, key string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(s.Dirs.SmolvmImage(key), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, f := range []string{s.pack(key), s.packFile(key)} {
|
||||
if err := os.WriteFile(f, nil, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// What smolvm has natively, and what waits for an emulation: refused in
|
||||
// one line naming the VM.
|
||||
func TestCaps(t *testing.T) {
|
||||
s := newSandbox(t)
|
||||
caps := s.Caps()
|
||||
for _, f := range backend.Features {
|
||||
want := !slices.Contains([]backend.Feature{
|
||||
backend.FeatureEgressProxy, backend.FeatureSSH, backend.FeaturePorts, backend.FeaturePortsAll, backend.FeatureAgentToggle,
|
||||
}, f)
|
||||
none := map[backend.Feature]string{
|
||||
backend.FeatureEgressProxy: "emulated", // reviewed
|
||||
backend.FeatureSSH: "emulated", // reviewed
|
||||
backend.FeaturePorts: "emulated", // reviewed
|
||||
backend.FeaturePortsAll: "emulated", // reviewed
|
||||
backend.FeatureAgentToggle: "emulated", // reviewed
|
||||
}[f]
|
||||
if none == "" {
|
||||
none = "none"
|
||||
}
|
||||
if caps[f].IsNative() != want || (!want && caps[f].String() != none) {
|
||||
t.Errorf("%s: %s", f, caps[f])
|
||||
}
|
||||
}
|
||||
var r backend.Review
|
||||
if err := r.Require(s, "devvm-x", backend.Confinement{Net: backend.NetProxy}.Features()...); err != nil {
|
||||
t.Errorf("network policy: %v", err)
|
||||
}
|
||||
if err := r.Require(s, "devvm-x", backend.FeatureSSH); err != nil {
|
||||
t.Errorf("ssh: %v", err)
|
||||
}
|
||||
if err := r.Require(s, "devvm-x", backend.VMSpec{Ports: backend.Ports{All: true}}.Features()...); err != nil {
|
||||
t.Errorf("every port: %v", err)
|
||||
}
|
||||
if err := r.Require(s, "devvm-x", backend.VMSpec{Ports: backend.Ports{Ranges: []backend.PortRange{{From: 22, To: 9000}}}}.Features()...); err != nil {
|
||||
t.Errorf("listed ports: %v", err)
|
||||
}
|
||||
if err := r.Require(s, "devvm-x", backend.FeatureAgentToggle); err != nil {
|
||||
t.Errorf("agent toggle: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Tool images are uncompressed, named by plain.sh; base's key has
|
||||
// prepare.sh, shims.sh, sshd.sh and Ubuntu's pinned image.
|
||||
func TestFormatAndKeyFiles(t *testing.T) {
|
||||
s := newSandbox(t)
|
||||
if f := s.ToolFormat(); !strings.HasPrefix(f, "plain-") || len(f) != len("plain-")+12 {
|
||||
t.Errorf("ToolFormat = %q", f)
|
||||
}
|
||||
kf := s.KeyFiles()
|
||||
if len(kf) != 4 || len(kf["container/prepare.sh"]) == 0 || len(kf["container/shims.sh"]) == 0 || len(kf["container/sshd.sh"]) == 0 ||
|
||||
string(kf["ubuntu-image"]) != ubuntu.ContainerRef {
|
||||
t.Errorf("KeyFiles = %v", slices.Collect(func(yield func(string) bool) {
|
||||
for k := range kf {
|
||||
if !yield(k) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
// Its disks are in devvm's smolvm folder, and on macOS also under the
|
||||
// user's home folder, where smolvm keeps machines.
|
||||
func TestDiskDirs(t *testing.T) {
|
||||
s := newSandbox(t)
|
||||
s.Dirs.Home = "/Users/u"
|
||||
if loc, ok := s.Location(); loc != "/Users/u" || !ok {
|
||||
t.Errorf("macOS: Location = %q, %v", loc, ok)
|
||||
}
|
||||
if got := s.DiskDirs(); !slices.Equal(got, []string{s.Dirs.Smolvm(), "/Users/u"}) {
|
||||
t.Errorf("macOS: DiskDirs = %q", got)
|
||||
}
|
||||
s.OS = "linux"
|
||||
if got := s.DiskDirs(); !slices.Equal(got, []string{s.Dirs.Smolvm()}) {
|
||||
t.Errorf("Linux: DiskDirs = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A VM's listed ports are recorded as they are, however many; every port
|
||||
// lists none.
|
||||
func TestListedAndVolume(t *testing.T) {
|
||||
rs := []backend.PortRange{{From: 22, To: 22}, {From: 3000, To: 4000}}
|
||||
if got := listed(backend.Ports{Ranges: rs}); !slices.Equal(got, rs) {
|
||||
t.Errorf("ranges: %v", got)
|
||||
}
|
||||
if got := listed(backend.Ports{All: true, Ranges: rs}); got != nil {
|
||||
t.Errorf("all: %v", got)
|
||||
}
|
||||
if got := listed(backend.Ports{}); len(got) != 0 {
|
||||
t.Errorf("none: %v", got)
|
||||
}
|
||||
if _, err := volume("/a:b", "/a:b", true); msg.NamesOf(err) != "smolvm_mount_colon path=/a:b" {
|
||||
t.Errorf("colon: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A VM is made from its image's pack, labelled, with everything set; what
|
||||
// smolvm doesn't show is recorded.
|
||||
func TestCreateVM(t *testing.T) {
|
||||
s := newSandbox(t)
|
||||
s.image(t, "0123456789ab")
|
||||
spec := backend.VMSpec{
|
||||
Name: "devvm-p-0123456789abc5", Project: "/p", AgentDirs: []string{"/h/.claude"}, Tools: "/t", ToolsAt: "/mnt/devvm-tools",
|
||||
AgentForwarding: true, Size: backend.Size{CPUs: 2}, Ports: backend.Ports{Ranges: []backend.PortRange{{From: 5173, To: 5173}}},
|
||||
}
|
||||
if err := s.CreateVM(t.Context(), "0123456789ab", spec); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := "smolvm machine create --name devvm-p-0123456789abc5 --label devvm.data=" + s.Dirs.Data +
|
||||
" --from " + s.packFile("0123456789ab") + " --cpus 2 --mem 8192 --storage 100 -v /var/lib/docker" +
|
||||
" -v /p:/p -v /h/.claude:/h/.claude:ro -v /t:/mnt/devvm-tools:ro --ssh-agent"
|
||||
if got := s.calls(t); !slices.Equal(got, []string{want}) {
|
||||
t.Errorf("calls:\n%q\nwant\n%q", got, want)
|
||||
}
|
||||
// Its listed ports are its forwarder's: recorded, none of smolvm's.
|
||||
if r, err := s.readRecord(spec.Name); err != nil || r.PortsAll || !slices.Equal(r.Listed, spec.Ports.Ranges) {
|
||||
t.Errorf("record %+v, %v", r, err)
|
||||
}
|
||||
in, err := s.Inspect(t.Context(), spec.Name)
|
||||
if err != nil || !in.AgentForwarding || !slices.Equal(in.AgentDirs, spec.AgentDirs) || in.Status != backend.StatusStopped ||
|
||||
in.Size != (backend.Size{CPUs: 2, MemoryGiB: 8, DiskGiB: 100}) {
|
||||
t.Errorf("Inspect = %+v, %v", in, err)
|
||||
}
|
||||
// The same name again, or someone else's machine by it.
|
||||
if err := s.CreateVM(t.Context(), "0123456789ab", spec); err == nil {
|
||||
t.Error("made twice")
|
||||
}
|
||||
s.machine(t, "devvm-q-0123456789abc6", "created 4 8192 null false")
|
||||
s.stubs.Touch(t, "smolvm-foreign-devvm-q-0123456789abc6")
|
||||
spec.Name = "devvm-q-0123456789abc6"
|
||||
if err := s.CreateVM(t.Context(), "0123456789ab", spec); msg.NamesOf(err) != "smolvm_machine_foreign vm=devvm-q-0123456789abc6" {
|
||||
t.Errorf("foreign: %v", err)
|
||||
}
|
||||
if err := s.CreateVM(t.Context(), "ba9876543210", spec); msg.NamesOf(err) != "image_missing key=ba9876543210" {
|
||||
t.Errorf("no image: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Only devvm's machines are listed, inspected, stopped or deleted: never
|
||||
// another's, whatever its name.
|
||||
func TestOnlyOurs(t *testing.T) {
|
||||
s := newSandbox(t)
|
||||
s.machine(t, "devvm-a-0123456789abcd", "running 4 8192 20 true")
|
||||
s.machine(t, "devvm-img-0123456789ab", "stopped 4 8192 100 true")
|
||||
s.machine(t, ToolsVM, "stopped 4 8192 100 true")
|
||||
s.machine(t, "devvm-b-0123456789abc2", "running 4 8192 20 true")
|
||||
s.stubs.Touch(t, "smolvm-foreign-devvm-b-0123456789abc2")
|
||||
ins, err := s.List(t.Context())
|
||||
if err != nil || len(ins) != 1 || ins[0].Name != "devvm-a-0123456789abcd" || ins[0].Status != backend.StatusRunning {
|
||||
t.Fatalf("List = %+v, %v", ins, err)
|
||||
}
|
||||
for _, f := range []func() error{
|
||||
func() error { _, err := s.Inspect(t.Context(), "devvm-b-0123456789abc2"); return err },
|
||||
func() error { return s.Stop(t.Context(), "devvm-b-0123456789abc2") },
|
||||
func() error { return s.Delete(t.Context(), "devvm-b-0123456789abc2") },
|
||||
func() error { return s.Start(t.Context(), "devvm-b-0123456789abc2", backend.Confinement{}) },
|
||||
} {
|
||||
if err := f(); !errors.Is(err, backend.ErrNotFound) {
|
||||
t.Errorf("someone else's: %v", err)
|
||||
}
|
||||
}
|
||||
if got := s.calls(t); len(got) != 0 {
|
||||
t.Errorf("calls: %q", got)
|
||||
}
|
||||
keys, err := s.Images(t.Context())
|
||||
if err != nil || !slices.Equal(keys, []string{"0123456789ab"}) {
|
||||
t.Errorf("Images = %q, %v", keys, err)
|
||||
}
|
||||
// SMOLVM_MACHINE_NAME is never passed on.
|
||||
if cmd := s.smolvm(t.Context(), "machine", "ls"); slices.ContainsFunc(cmd.Env, func(e string) bool {
|
||||
return strings.HasPrefix(e, "SMOLVM_MACHINE_NAME=")
|
||||
}) || !slices.Contains(cmd.Env, "SMOLVM_USAGE=0") {
|
||||
t.Errorf("env: %q", cmd.Env)
|
||||
}
|
||||
}
|
||||
|
||||
// Start sets the network where it differs, then runs services.sh; the
|
||||
// network policy is refused, and so is forwarding without an agent.
|
||||
func TestStart(t *testing.T) {
|
||||
s := newSandbox(t)
|
||||
vm := "devvm-a-0123456789abcd"
|
||||
s.machine(t, vm, "stopped 4 8192 20 false")
|
||||
if err := s.Start(t.Context(), vm, backend.Confinement{Net: backend.NetDirect}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []string{
|
||||
"smolvm machine update --name " + vm + " --net",
|
||||
"smolvm machine start --name " + vm,
|
||||
"smolvm machine exec --name " + vm + " -i -- sh -s --",
|
||||
}
|
||||
if got := s.calls(t); !slices.Equal(got, want) {
|
||||
t.Errorf("calls:\n%q\nwant\n%q", got, want)
|
||||
}
|
||||
s.stubs.Reset(t)
|
||||
if err := s.Start(t.Context(), vm, backend.Confinement{}); err != nil || len(s.calls(t)) != 0 {
|
||||
t.Errorf("running: %v, %q", err, s.calls(t))
|
||||
}
|
||||
if err := s.Stop(t.Context(), vm); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.stubs.Reset(t)
|
||||
if err := s.Start(t.Context(), vm, backend.Confinement{Net: backend.NetNone}); err != nil ||
|
||||
s.calls(t)[0] != "smolvm machine update --name "+vm+" --no-net" {
|
||||
t.Errorf("no network: %v, %q", err, s.calls(t))
|
||||
}
|
||||
if err := s.Start(t.Context(), vm, backend.Confinement{Net: backend.NetProxy}); err == nil || msg.IDOf(err) != "" || err.Error() != "smolvm: "+vm+": no decider to start it through" {
|
||||
t.Errorf("network policy without a decider: %v", err)
|
||||
}
|
||||
|
||||
// Forwarding: the agent it's given, or none.
|
||||
fw := "devvm-f-0123456789abc3"
|
||||
s.machine(t, fw, "stopped 4 8192 20 true")
|
||||
if err := s.writeRecord(fw, record{Forwarding: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Start(t.Context(), fw, backend.Confinement{}); msg.NamesOf(err) != "smolvm_no_agent vm="+fw {
|
||||
t.Errorf("no agent: %v", err)
|
||||
}
|
||||
if err := s.Start(t.Context(), fw, backend.Confinement{AgentSocket: "/a.sock"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if b, _ := os.ReadFile(filepath.Join(s.stub, "smolvm-agent-"+fw)); strings.TrimSpace(string(b)) != "/a.sock" {
|
||||
t.Errorf("agent: %q", b)
|
||||
}
|
||||
if got := s.Lifeline(t.Context(), fw); got != filepath.Join(s.stub, "smolvm-data", fw, "agent.pid") {
|
||||
t.Errorf("Lifeline = %q", got)
|
||||
}
|
||||
if err := s.Stop(t.Context(), fw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// None chosen for this start alone (Confinement.NoAgent): no agent at
|
||||
// all, whatever the user's or devvm's.
|
||||
s.Getenv = func(string) string { return "/user.sock" }
|
||||
if err := s.Start(t.Context(), fw, backend.Confinement{NoAgent: true, AgentSocket: "/a.sock"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := s.startAgent(t, fw); got != noAgent {
|
||||
t.Errorf("no agent: %q", got)
|
||||
}
|
||||
// A machine made without forwarding never gets the agent devvm has.
|
||||
t.Setenv("SSH_AUTH_SOCK", "/devvm-has.sock")
|
||||
if err := s.Stop(t.Context(), vm); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Start(t.Context(), vm, backend.Confinement{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := s.startAgent(t, vm); got != "unset" {
|
||||
t.Errorf("made without: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A stopped start forwards none of a VM's listed ports through smolvm,
|
||||
// and leaves its record's list as it is: a VM without ssh forwards none,
|
||||
// warned.
|
||||
func TestStartListedNoSSH(t *testing.T) {
|
||||
s := newSandbox(t)
|
||||
vm := "devvm-p-0123456789abc5"
|
||||
s.machine(t, vm, "stopped 4 8192 20 true")
|
||||
listed := []backend.PortRange{{From: 5173, To: 5173}, {From: 8000, To: 8002}}
|
||||
if err := s.writeRecord(vm, record{Listed: listed}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var warned msg.Recorder
|
||||
s.Warn = warned.Add
|
||||
free := func(_ context.Context, rs []backend.PortRange) []backend.PortRange { return rs[1:] }
|
||||
if err := s.Start(t.Context(), vm, backend.Confinement{Free: free}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := strings.Join(s.calls(t), "\n"); strings.Contains(got, " -p ") || strings.Contains(got, "--remove-port") {
|
||||
t.Errorf("smolvm's forwards changed: %q", got)
|
||||
}
|
||||
if r, err := s.readRecord(vm); err != nil || !slices.Equal(r.Listed, listed) {
|
||||
t.Errorf("record %+v, %v", r, err)
|
||||
}
|
||||
if !slices.Equal(warned.Names(), []string{"ports_no_ssh vm=" + vm}) {
|
||||
t.Errorf("warned %q", warned.Names())
|
||||
}
|
||||
}
|
||||
|
||||
// startAgent stops vm, if it runs, and returns the agent its last start
|
||||
// was given: unset for none.
|
||||
func (s sandbox) startAgent(t *testing.T, vm string) string {
|
||||
t.Helper()
|
||||
b, err := os.ReadFile(filepath.Join(s.stub, "smolvm-agent-"+vm)) //nolint:gosec // the stub's file in the test's own folder
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Stop(t.Context(), vm); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return strings.TrimSpace(string(b))
|
||||
}
|
||||
|
||||
// Turning forwarding on or off (agent-toggle, emulated): a machine made
|
||||
// ready for it (AgentToggle) forwards from the start, and each start gives
|
||||
// it the agent devvm's choice names, none when it's off; one made without
|
||||
// forwarding can't get it.
|
||||
func TestAgentToggle(t *testing.T) {
|
||||
s := newSandbox(t)
|
||||
s.image(t, "0123456789ab")
|
||||
s.Getenv = func(k string) string {
|
||||
if k == "SSH_AUTH_SOCK" {
|
||||
return "/user.sock"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
vm := "devvm-t-0123456789abc7"
|
||||
if err := s.CreateVM(t.Context(), "0123456789ab", backend.VMSpec{Name: vm, AgentToggle: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := s.calls(t); len(got) != 1 || !strings.HasSuffix(got[0], " --ssh-agent") {
|
||||
t.Errorf("create: %q", got)
|
||||
}
|
||||
in, err := s.Inspect(t.Context(), vm)
|
||||
if err != nil || in.AgentForwarding || in.AgentFixed {
|
||||
t.Errorf("made off: %+v, %v", in, err)
|
||||
}
|
||||
steps := []struct {
|
||||
on bool
|
||||
conf backend.Confinement
|
||||
want string
|
||||
}{
|
||||
{false, backend.Confinement{NoAgent: true}, noAgent},
|
||||
{true, backend.Confinement{}, "/user.sock"},
|
||||
{true, backend.Confinement{AgentSocket: "/devvm.sock"}, "/devvm.sock"},
|
||||
// Off in its record wins over a confinement that names an agent.
|
||||
{false, backend.Confinement{AgentSocket: "/devvm.sock"}, noAgent},
|
||||
{false, backend.Confinement{}, noAgent},
|
||||
}
|
||||
for i, st := range steps {
|
||||
if err := s.SetAgentForwarding(t.Context(), vm, st.on); err != nil {
|
||||
t.Fatalf("%d: %v", i, err)
|
||||
}
|
||||
if in, err := s.Inspect(t.Context(), vm); err != nil || in.AgentForwarding != st.on {
|
||||
t.Errorf("%d: Inspect = %+v, %v", i, in, err)
|
||||
}
|
||||
if err := s.Start(t.Context(), vm, st.conf); err != nil {
|
||||
t.Fatalf("%d: %v", i, err)
|
||||
}
|
||||
if got := s.startAgent(t, vm); got != st.want {
|
||||
t.Errorf("%d: agent %q, want %q", i, got, st.want)
|
||||
}
|
||||
}
|
||||
// On, with no agent of the user's: refused before anything changes.
|
||||
if err := s.SetAgentForwarding(t.Context(), vm, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.Getenv = func(string) string { return "" }
|
||||
s.stubs.Reset(t)
|
||||
if err := s.Start(t.Context(), vm, backend.Confinement{}); msg.NamesOf(err) != "smolvm_no_agent vm="+vm || len(s.calls(t)) != 0 {
|
||||
t.Errorf("no agent: %v, %q", err, s.calls(t))
|
||||
}
|
||||
// Running: changed only once it's stopped.
|
||||
if err := s.Start(t.Context(), vm, backend.Confinement{NoAgent: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.SetAgentForwarding(t.Context(), vm, false); msg.NamesOf(err) != "vm_not_stopped vm="+vm {
|
||||
t.Errorf("running: %v", err)
|
||||
}
|
||||
// Made without forwarding: off stays off, on is refused.
|
||||
fixed := "devvm-x-0123456789abc8"
|
||||
if err := s.CreateVM(t.Context(), "0123456789ab", backend.VMSpec{Name: fixed}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if in, err := s.Inspect(t.Context(), fixed); err != nil || in.AgentForwarding || !in.AgentFixed {
|
||||
t.Errorf("made without: %+v, %v", in, err)
|
||||
}
|
||||
if err := s.SetAgentForwarding(t.Context(), fixed, false); err != nil {
|
||||
t.Errorf("off: %v", err)
|
||||
}
|
||||
if err := s.SetAgentForwarding(t.Context(), fixed, true); msg.NamesOf(err) != "agent_fixed backend=smolvm vm="+fixed {
|
||||
t.Errorf("on: %v", err)
|
||||
}
|
||||
// Made forwarding (--ssh-agent): on.
|
||||
fw := "devvm-f-0123456789abc3"
|
||||
if err := s.CreateVM(t.Context(), "0123456789ab", backend.VMSpec{Name: fw, AgentForwarding: true, AgentToggle: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if in, err := s.Inspect(t.Context(), fw); err != nil || !in.AgentForwarding || in.AgentFixed || !in.AgentWhileRunning {
|
||||
t.Errorf("made on: %+v, %v", in, err)
|
||||
}
|
||||
// Started by Start: the agent devvm chose. Started some other way
|
||||
// since (another lifeline): one it may not have chosen; stopped, none.
|
||||
if err := s.Start(t.Context(), fw, backend.Confinement{NoAgent: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if u, err := s.AgentUnchosen(t.Context(), fw); u || err != nil {
|
||||
t.Errorf("started by devvm: %v, %v", u, err)
|
||||
}
|
||||
other := []byte(strconv.Itoa(os.Getpid()) + "\n1")
|
||||
if err := os.WriteFile(filepath.Join(s.stub, "smolvm-data", fw, "agent.pid"), other, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if u, err := s.AgentUnchosen(t.Context(), fw); !u || err != nil {
|
||||
t.Errorf("started elsewhere: %v, %v", u, err)
|
||||
}
|
||||
if err := s.Stop(t.Context(), fw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if u, err := s.AgentUnchosen(t.Context(), fw); u || err != nil {
|
||||
t.Errorf("stopped: %v, %v", u, err)
|
||||
}
|
||||
// Made without forwarding: no agent however it's started.
|
||||
if err := s.Start(t.Context(), fixed, backend.Confinement{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(s.stub, "smolvm-data", fixed, "agent.pid"), other, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if u, err := s.AgentUnchosen(t.Context(), fixed); u || err != nil {
|
||||
t.Errorf("made without: %v, %v", u, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Network policy: an allow list of the gateway, DNS answering only a name
|
||||
// that doesn't exist, the proxy's address in the environment, and the start
|
||||
// through devvm's decider, its token in no arguments. Confined while it
|
||||
// runs on that start; a start without network policy takes it all away.
|
||||
func TestStartConfined(t *testing.T) {
|
||||
s := newSandbox(t)
|
||||
t.Setenv("SMOLVM_INTERCEPTOR_TOKEN", strings.Repeat("cd", 32)) // the user's own: never passed on
|
||||
vm := "devvm-n-0123456789abc4"
|
||||
s.machine(t, vm, "stopped 4 8192 20 false")
|
||||
tok := strings.Repeat("ab", 32)
|
||||
c := backend.Confinement{
|
||||
Net: backend.NetProxy, ProxyPort: 3128, ProxyPassword: "pw", Env: map[string]string{"NO_PROXY": "localhost"},
|
||||
Decider: "127.0.0.1:4000", DeciderToken: tok,
|
||||
}
|
||||
for _, bad := range []backend.Confinement{
|
||||
{Net: backend.NetProxy, Decider: "10.0.0.1:4000", DeciderToken: tok},
|
||||
{Net: backend.NetProxy, Decider: "127.0.0.1:4000", DeciderToken: "ab"},
|
||||
} {
|
||||
if err := s.Start(t.Context(), vm, bad); err == nil {
|
||||
t.Errorf("%+v: started", bad)
|
||||
}
|
||||
}
|
||||
// The proxy's variables in a machine's environment go: the proxy's
|
||||
// URL is only ever in its file.
|
||||
if err := s.writeRecord(vm, record{Env: map[string]string{"HTTPS_PROXY": "http://devvm:[email protected]:1"}}); err != nil { //nolint:gosec // the test's own password
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Start(t.Context(), vm, c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f := s.proxyFile(vm)
|
||||
secrets := " --secret-file HTTP_PROXY=" + f + " --secret-file HTTPS_PROXY=" + f + " --secret-file http_proxy=" + f + " --secret-file https_proxy=" + f
|
||||
want := []string{
|
||||
"smolvm machine update --name " + vm + " --reset-allow-list --allow-cidr 100.96.0.1/32 --allow-host-pattern devvm.invalid",
|
||||
"smolvm machine update --name " + vm + " --remove-env HTTPS_PROXY -e NO_PROXY=localhost",
|
||||
"smolvm machine start --name " + vm + " --mediated-egress --egress-interceptor 127.0.0.1:4000",
|
||||
"smolvm machine exec --name " + vm + secrets + " -i -- sh -s --",
|
||||
}
|
||||
if got := s.calls(t); !slices.Equal(got, want) {
|
||||
t.Errorf("calls:\n%q\nwant\n%q", got, want)
|
||||
}
|
||||
// The proxy's URL, password and all, is in its file alone (mode 600),
|
||||
// which each exec names.
|
||||
if b, err := os.ReadFile(f); err != nil || string(b) != "http://devvm:[email protected]:3128" { //nolint:gosec // the test's own password
|
||||
t.Errorf("proxy file: %q, %v", b, err)
|
||||
}
|
||||
if fi, err := os.Stat(f); err != nil || fi.Mode().Perm() != 0o600 {
|
||||
t.Errorf("proxy file: %v, %v", fi, err)
|
||||
}
|
||||
if args, err := s.userArgs(vm, "/", false, false, []string{"true"}); err != nil || !strings.Contains(strings.Join(args, " "), secrets[1:]+" -u u ") {
|
||||
t.Errorf("exec: %q, %v", args, err)
|
||||
}
|
||||
if strings.Contains(strings.Join(s.calls(t), " "), ":pw@") {
|
||||
t.Error("the password is in smolvm's arguments")
|
||||
}
|
||||
if b, _ := os.ReadFile(filepath.Join(s.stub, "smolvm-decider-"+vm)); strings.TrimSpace(string(b)) != "127.0.0.1:4000 "+tok {
|
||||
t.Errorf("decider: %q", b)
|
||||
}
|
||||
if strings.Contains(strings.Join(s.calls(t), " "), tok) {
|
||||
t.Error("the token is in smolvm's arguments")
|
||||
}
|
||||
if ok, err := s.Confined(t.Context(), vm); !ok || err != nil {
|
||||
t.Errorf("Confined = %v, %v", ok, err)
|
||||
}
|
||||
// Its allow list widened while it runs: no longer confined, and the next
|
||||
// start sets it again.
|
||||
if out, err := exec.CommandContext(t.Context(), "smolvm", "machine", "update", "--name", vm, "--allow-cidr", "1.1.1.1/32").CombinedOutput(); err != nil {
|
||||
t.Fatalf("%v: %s", err, out)
|
||||
}
|
||||
if ok, err := s.Confined(t.Context(), vm); ok || err != nil {
|
||||
t.Errorf("widened: Confined = %v, %v", ok, err)
|
||||
}
|
||||
if err := s.Stop(t.Context(), vm); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.stubs.Reset(t)
|
||||
if err := s.Start(t.Context(), vm, c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := s.calls(t); len(got) == 0 || got[0] != want[0] {
|
||||
t.Errorf("widened, then started: %q", got)
|
||||
}
|
||||
if ok, err := s.Confined(t.Context(), vm); !ok || err != nil {
|
||||
t.Errorf("started again: Confined = %v, %v", ok, err)
|
||||
}
|
||||
// Started again as it was: nothing to change.
|
||||
if err := s.Stop(t.Context(), vm); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ok, _ := s.Confined(t.Context(), vm); ok {
|
||||
t.Error("stopped, yet confined")
|
||||
}
|
||||
s.stubs.Reset(t)
|
||||
if err := s.Start(t.Context(), vm, c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := s.calls(t); len(got) != 2 || !strings.HasPrefix(got[0], "smolvm machine start ") {
|
||||
t.Errorf("started again: %q", got)
|
||||
}
|
||||
// Started some other way since: not confined.
|
||||
pid := filepath.Join(s.stub, "smolvm-data", vm, "agent.pid")
|
||||
if err := os.WriteFile(pid, []byte(strconv.Itoa(os.Getpid())+"\n1"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ok, err := s.Confined(t.Context(), vm); ok || err != nil {
|
||||
t.Errorf("another start: Confined = %v, %v", ok, err)
|
||||
}
|
||||
// Without network policy: smolvm's own network, nothing of the decider's.
|
||||
if err := s.Stop(t.Context(), vm); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.stubs.Reset(t)
|
||||
if err := s.Start(t.Context(), vm, backend.Confinement{Net: backend.NetDirect}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want = []string{
|
||||
"smolvm machine update --name " + vm + " --net --reset-allow-list --no-egress-interceptor",
|
||||
"smolvm machine update --name " + vm + " --remove-env NO_PROXY",
|
||||
"smolvm machine start --name " + vm,
|
||||
"smolvm machine exec --name " + vm + " -i -- sh -s --",
|
||||
}
|
||||
if got := s.calls(t); !slices.Equal(got, want) {
|
||||
t.Errorf("calls:\n%q\nwant\n%q", got, want)
|
||||
}
|
||||
if _, err := os.Stat(f); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Errorf("proxy file: %v", err)
|
||||
}
|
||||
if b, _ := os.ReadFile(filepath.Join(s.stub, "smolvm-decider-"+vm)); strings.TrimSpace(string(b)) != "none unset" {
|
||||
t.Errorf("decider: %q", b)
|
||||
}
|
||||
if ok, _ := s.Confined(t.Context(), vm); ok {
|
||||
t.Error("confined without network policy")
|
||||
}
|
||||
}
|
||||
|
||||
// Base: a machine from Ubuntu's pinned container image, prepared, its
|
||||
// scripts run between the stand-ins, packed, then deleted.
|
||||
func TestBuildBase(t *testing.T) {
|
||||
s := newSandbox(t)
|
||||
built, err := s.BuildImage(t.Context(), backend.ImageSpec{
|
||||
Image: "base", Key: "0123456789ab", Net: backend.NetInternet,
|
||||
Scripts: []backend.Script{{Name: "base.sh", Data: []byte("#!/bin/bash\necho base\n")}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if built.Libc != "gnu" || built.Origin != "docker.io/library/ubuntu:26.04@"+ubuntu.ContainerDigest {
|
||||
t.Errorf("Built = %+v", built)
|
||||
}
|
||||
inst := "devvm-img-0123456789ab"
|
||||
got := s.calls(t)
|
||||
want := []string{
|
||||
"smolvm machine create --name " + inst + " --label devvm.data=" + s.Dirs.Data +
|
||||
" --cpus 4 --mem 8192 --storage 100 -v /var/lib/docker --net --image docker.io/library/ubuntu@" + ubuntu.ContainerDigest,
|
||||
"smolvm machine start --name " + inst,
|
||||
"smolvm machine exec --name " + inst + " -i -- sh -s --",
|
||||
"smolvm machine exec --name " + inst + " -i -- sh -s -- u 501",
|
||||
"smolvm machine exec --name " + inst + " -- sh -c if command -v apk >/dev/null; then echo musl; else echo gnu; fi",
|
||||
"smolvm machine exec --name " + inst + " -i -- sh -s -- on",
|
||||
"smolvm machine exec --name " + inst + " -i -u u -w / -e USER=u -e LOGNAME=u -e HOME=/home/u.guest -e SHELL=/bin/bash -- sh -c " +
|
||||
loginEnv + " sh bash -s",
|
||||
"smolvm machine exec --name " + inst + " -i -- sh -s --",
|
||||
"smolvm machine exec --name " + inst + " -i -- sh -s -- off",
|
||||
"smolvm machine stop --name " + inst,
|
||||
"smolvm pack create --from-vm " + inst + " -o " + s.Dirs.SmolvmImage("0123456789ab") + ".tmp/image",
|
||||
"smolvm machine delete --name " + inst + " -f",
|
||||
}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Errorf("calls:\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n"))
|
||||
}
|
||||
if _, err := os.Stat(s.packFile("0123456789ab")); err != nil {
|
||||
t.Errorf("no pack: %v", err)
|
||||
}
|
||||
if keys, err := s.Images(t.Context()); err != nil || !slices.Equal(keys, []string{"0123456789ab"}) {
|
||||
t.Errorf("Images = %q, %v", keys, err)
|
||||
}
|
||||
// A VM made from it keeps it.
|
||||
if err := s.CreateVM(t.Context(), "0123456789ab", backend.VMSpec{Name: "devvm-p-0123456789abc5"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.DeleteImage(t.Context(), "0123456789ab"); msg.NamesOf(err) != "image_in_use key=0123456789ab vms=devvm-p-0123456789abc5" {
|
||||
t.Errorf("in use: %v", err)
|
||||
}
|
||||
if err := s.Delete(t.Context(), "devvm-p-0123456789abc5"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.DeleteImage(t.Context(), "0123456789ab"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(s.Dirs.SmolvmImage("0123456789ab")); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Errorf("still there: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// On a host of 2 CPUs and 8 GiB, base's build machine and a VM given no
|
||||
// size get 2 CPUs and 4 GiB; a VM's own CPUs still win.
|
||||
func TestSmallHost(t *testing.T) {
|
||||
big := newSandbox(t)
|
||||
if built, err := big.BuildImage(t.Context(), backend.ImageSpec{Image: "base", Key: "0123456789ab", Net: backend.NetInternet}); err != nil || built.Fitted != (backend.Size{}) {
|
||||
t.Errorf("on a big host: fitted %+v, %v; want none", built.Fitted, err)
|
||||
}
|
||||
s := newSandbox(t)
|
||||
s.CPUs = func() int { return 2 }
|
||||
s.Memory = func() (uint64, error) { return 8 << 30, nil }
|
||||
built, err := s.BuildImage(t.Context(), backend.ImageSpec{Image: "base", Key: "0123456789ab", Net: backend.NetInternet})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := (backend.Size{CPUs: 2, MemoryGiB: 4}); built.Fitted != want {
|
||||
t.Errorf("fitted %+v, want %+v", built.Fitted, want)
|
||||
}
|
||||
if got := s.calls(t); len(got) == 0 || !strings.Contains(got[0], "machine create ") || !strings.Contains(got[0], " --cpus 2 --mem 4096 ") {
|
||||
t.Errorf("calls:\n%s\nwant base made with --cpus 2 --mem 4096", strings.Join(got, "\n"))
|
||||
}
|
||||
for vm, size := range map[string]backend.Size{"devvm-p-0123456789abc5": {}, "devvm-q-0123456789abc6": {CPUs: 1}} {
|
||||
if err := s.CreateVM(t.Context(), "0123456789ab", backend.VMSpec{Name: vm, Size: size}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
got := s.calls(t)
|
||||
got = got[max(0, len(got)-2):]
|
||||
if len(got) != 2 || !strings.Contains(got[0]+got[1], " --cpus 2 --mem 4096 ") || !strings.Contains(got[0]+got[1], " --cpus 1 --mem 4096 ") {
|
||||
t.Errorf("calls:\n%s\nwant --cpus 2 and --cpus 1, each with --mem 4096", strings.Join(got, "\n"))
|
||||
}
|
||||
}
|
||||
|
||||
// A failed script keeps the build machine, stopped; an image only Docker
|
||||
// has is refused.
|
||||
func TestBuildFails(t *testing.T) {
|
||||
s := newSandbox(t)
|
||||
s.image(t, "0123456789ab")
|
||||
s.stubs.Touch(t, "script-fails")
|
||||
_, err := s.BuildImage(t.Context(), backend.ImageSpec{
|
||||
Image: "foo", Key: "ba9876543210", Parent: "0123456789ab", Net: backend.NetInternet,
|
||||
Scripts: []backend.Script{{Name: "foo.sh", Data: []byte("#!/bin/bash\nexit 3\n")}},
|
||||
})
|
||||
if msg.NamesOf(err) != "smolvm_script_failed script=foo.sh vm=devvm-img-ba9876543210" {
|
||||
t.Errorf("failed: %v", err)
|
||||
}
|
||||
m, err := s.inspect(t.Context(), "devvm-img-ba9876543210")
|
||||
if err != nil || m.status() != backend.StatusStopped {
|
||||
t.Errorf("kept: %+v, %v", m, err)
|
||||
}
|
||||
if keys, _ := s.Images(t.Context()); !slices.Contains(keys, "ba9876543210") {
|
||||
t.Errorf("unfinished not listed: %q", keys)
|
||||
}
|
||||
_, err = s.BuildImage(t.Context(), backend.ImageSpec{
|
||||
Image: "base", Key: "aaaaaaaaaaaa", Net: backend.NetInternet, From: &backend.From{Ref: "mine:1", Digest: "sha256:" + strings.Repeat("cd", 32)},
|
||||
})
|
||||
if msg.NamesOf(err) != "smolvm_from_registry_only image=mine:1" {
|
||||
t.Errorf("Docker's: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Sizes change where they differ; disks only grow; ports and agent folders
|
||||
// replace what was set, ports in devvm's record alone.
|
||||
func TestSet(t *testing.T) {
|
||||
s := newSandbox(t)
|
||||
vm := "devvm-a-0123456789abcd"
|
||||
s.machine(t, vm, "stopped 4 8192 100 true")
|
||||
if err := s.writeRecord(vm, record{AgentDirs: []string{"/h/.claude"}, Listed: []backend.PortRange{{From: 3000, To: 3000}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.SetSize(t.Context(), vm, backend.Size{CPUs: 4, MemoryGiB: 4, DiskGiB: 120}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.SetSize(t.Context(), vm, backend.Size{DiskGiB: 50}); msg.NamesOf(err) != "disk_shrink have=120 vm="+vm+" want=50" {
|
||||
t.Errorf("shrink: %v", err)
|
||||
}
|
||||
if err := s.SetPorts(t.Context(), vm, backend.Ports{Ranges: []backend.PortRange{{From: 8000, To: 8000}}}, backend.Confinement{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.SetAgentDirs(t.Context(), vm, []string{"/h/.codex"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []string{
|
||||
"smolvm machine update --name " + vm + " --mem 4096 --storage 120",
|
||||
"smolvm machine update --name " + vm + " --remove-volume /h/.claude:/h/.claude -v /h/.codex:/h/.codex:ro",
|
||||
}
|
||||
if got := s.calls(t); !slices.Equal(got, want) {
|
||||
t.Errorf("calls:\n%q\nwant\n%q", got, want)
|
||||
}
|
||||
if r, err := s.readRecord(vm); err != nil || r.PortsAll || !slices.Equal(r.Listed, []backend.PortRange{{From: 8000, To: 8000}}) {
|
||||
t.Errorf("record %+v, %v", r, err)
|
||||
}
|
||||
s.machine(t, vm, "running 4 4096 120 true")
|
||||
if err := s.SetSize(t.Context(), vm, backend.Size{CPUs: 2}); msg.NamesOf(err) != "vm_not_stopped vm="+vm {
|
||||
t.Errorf("running: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// On Linux, smolvm's state is devvm's own.
|
||||
func TestLinuxStateDir(t *testing.T) {
|
||||
s := newSandbox(t)
|
||||
s.OS = "linux"
|
||||
cmd := s.smolvm(t.Context(), "machine", "ls", "--json")
|
||||
if want := []string{"smolvm", "machine", "ls", "--state-dir", filepath.Join(s.Dirs.Smolvm(), "state"), "--json"}; !slices.Equal(cmd.Args, want) {
|
||||
t.Errorf("args = %q", cmd.Args)
|
||||
}
|
||||
if cmd := s.smolvm(t.Context(), "--version"); len(cmd.Args) != 2 {
|
||||
t.Errorf("--version: %q", cmd.Args)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProblems(t *testing.T) {
|
||||
s := newSandbox(t)
|
||||
if ps := s.Problems(t.Context()); len(ps) != 0 {
|
||||
t.Errorf("all there: %+v", ps)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(s.stub, "smolvm-version"), []byte("1.31.0"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Check(t.Context()); !strings.HasPrefix(msg.NamesOf(err), "smolvm_old") {
|
||||
t.Errorf("old: %v", err)
|
||||
}
|
||||
s.OS, s.Arch = "darwin", "amd64"
|
||||
if err := s.Check(t.Context()); msg.NamesOf(err) != "smolvm_host_unsupported host=darwin/amd64" {
|
||||
t.Errorf("Intel Mac: %v", err)
|
||||
}
|
||||
for _, v := range []struct {
|
||||
v string
|
||||
ok bool
|
||||
}{{"1.32.2", true}, {"1.40.0", true}, {"2.0.0", true}, {"1.9.9", false}, {"x", false}} {
|
||||
if recent(v.v) != v.ok {
|
||||
t.Errorf("recent(%s)", v.v)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
package smolvm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"strconv"
|
||||
|
||||
"github.com/w3cj/devvm/internal/backend"
|
||||
"github.com/w3cj/devvm/internal/backend/vmssh"
|
||||
"github.com/w3cj/devvm/internal/msg"
|
||||
"github.com/w3cj/devvm/internal/platform"
|
||||
)
|
||||
|
||||
// ssh for editors is emulated, and reviewed: smolvm runs no sshd, so devvm
|
||||
// runs one of its own in each project VM, for which the caller asks it
|
||||
// (Confinement.SSH):
|
||||
//
|
||||
// - base has openssh-server, its host keys deleted (sshd.sh), and
|
||||
// services.sh makes the VM new ones (ed25519) at each start, before
|
||||
// sshd starts: no two VMs made from one pack share them, and devvm
|
||||
// reads them through smolvm's exec, as it does on Lima;
|
||||
// - sshd runs on devvm's own config (services.sh): the VM's user alone,
|
||||
// with the VM's own key (sshKey, vmssh.EnsureKey) alone, no passwords;
|
||||
// local forwarding, remote forwards of TCP ports only on 127.77.0.0/16
|
||||
// (links' addresses), no remote socket forwards, tunnels or X11. Root
|
||||
// in the VM can change that: what keeps the VM's connections from
|
||||
// going out through the host is the host's ssh, which asks for none of
|
||||
// those but a link's (devvm's entry pins its options);
|
||||
// - its guest port, 22, is forwarded from a host loopback port
|
||||
// (sshForward): Confinement.SSHPort, or one of the backend's, kept while
|
||||
// it stays free, never one of the VM's listed ports. It's the one
|
||||
// forward smolvm makes;
|
||||
// - SSH answers only once this start's sshd runs (record.SSHUp), so
|
||||
// nothing reads the host keys a start is about to replace. A VM whose
|
||||
// image has no sshd starts without ssh, warned.
|
||||
const sshGuestPort = 22
|
||||
|
||||
// sshKey is the key devvm's ssh logs in to one VM with, in its backend
|
||||
// folder, made at its first start with ssh.
|
||||
func (s *Smolvm) sshKey(vm string) string { return s.Dirs.VM(vm).Key() }
|
||||
|
||||
// sshForward is the host loopback port a VM's ssh is forwarded from at a
|
||||
// start that runs it: c.SSHPort when the caller chose one (devvm records
|
||||
// every VM's), else the one it had while that's free, else a new one;
|
||||
// never one of the VM's listed ports, which its forwarder takes.
|
||||
func (s *Smolvm) sshForward(ctx context.Context, vm string, c backend.Confinement, r record) (int, error) {
|
||||
listed := backend.Ports{Ranges: r.Listed}
|
||||
if c.SSHPort > 0 {
|
||||
if listed.Has(c.SSHPort) {
|
||||
return 0, msg.SmolvmSSHPortForwarded(strconv.Itoa(c.SSHPort), vm)
|
||||
}
|
||||
return c.SSHPort, nil
|
||||
}
|
||||
if r.SSHPort > 0 && !listed.Has(r.SSHPort) && s.PortFree(ctx, r.SSHPort) {
|
||||
return r.SSHPort, nil
|
||||
}
|
||||
for range 20 {
|
||||
p, err := s.FreePort(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if !listed.Has(p) {
|
||||
return p, nil
|
||||
}
|
||||
}
|
||||
return 0, errors.New("smolvm: no free port on the host's loopback")
|
||||
}
|
||||
|
||||
// sshForwardSpec is -p's value for a VM's ssh forward.
|
||||
func sshForwardSpec(port int) string { return strconv.Itoa(port) + ":" + strconv.Itoa(sshGuestPort) }
|
||||
|
||||
// freePort is a port free on the host's loopback, IPv4 and IPv6, as
|
||||
// smolvm forwards on both, and on every other address
|
||||
// (platform.PortFree).
|
||||
func freePort(ctx context.Context) (int, error) {
|
||||
for range 20 {
|
||||
l, err := platform.ListenLoopback(ctx, "127.0.0.1:0")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
port := l.Addr().(*net.TCPAddr).Port
|
||||
_ = l.Close()
|
||||
if platform.PortFree(ctx, port) {
|
||||
return port, nil
|
||||
}
|
||||
}
|
||||
return 0, errors.New("smolvm: no free port on the host's loopback")
|
||||
}
|
||||
|
||||
// servicesArgs are services.sh's arguments for a start that runs the VM's
|
||||
// sshd: the user, devvm's public key, and the names of the variables its
|
||||
// sessions get: the proxy's under network policy, then env's.
|
||||
func servicesArgs(user, pub string, env map[string]string, proxy bool) []string {
|
||||
var first []string
|
||||
if proxy {
|
||||
first = backend.GuestProxyVars()
|
||||
}
|
||||
return vmssh.ServicesArgs(user, pub, first, env)
|
||||
}
|
||||
|
||||
// SSH returns how ssh reaches a running VM whose start ran its sshd: its
|
||||
// forward on the host's loopback, the VM's user, and devvm's key alone.
|
||||
// A VM started without it gets vm_no_ssh.
|
||||
func (s *Smolvm) SSH(ctx context.Context, vm string) (backend.SSHTarget, error) {
|
||||
m, err := s.inspect(ctx, vm)
|
||||
if err != nil {
|
||||
return backend.SSHTarget{}, notFound(vm, err)
|
||||
}
|
||||
if m.status() != backend.StatusRunning {
|
||||
return backend.SSHTarget{}, msg.VMNotRunning(vm)
|
||||
}
|
||||
r, err := s.readRecord(vm)
|
||||
if err != nil {
|
||||
return backend.SSHTarget{}, err
|
||||
}
|
||||
switch {
|
||||
case r.NoSSHD:
|
||||
return backend.SSHTarget{}, msg.VMNoSshd(vm)
|
||||
case r.SSHPort == 0 || !r.SSHUp:
|
||||
return backend.SSHTarget{}, msg.VMNoSSH(vm)
|
||||
}
|
||||
name, _, err := s.user()
|
||||
if err != nil {
|
||||
return backend.SSHTarget{}, err
|
||||
}
|
||||
return backend.SSHTarget{
|
||||
Host: "127.0.0.1", Port: r.SSHPort, User: name,
|
||||
Options: []backend.SSHOption{
|
||||
{Key: "IdentityFile", Value: `"` + s.sshKey(vm) + `"`},
|
||||
{Key: "IdentitiesOnly", Value: "yes"},
|
||||
{Key: "PreferredAuthentications", Value: "publickey"},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
@@ -1,195 +0,0 @@
|
||||
package smolvm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/w3cj/devvm/internal/backend"
|
||||
"github.com/w3cj/devvm/internal/backend/vmssh"
|
||||
"github.com/w3cj/devvm/internal/msg"
|
||||
)
|
||||
|
||||
// A VM's key is beside its record, in its backend folder, one per VM.
|
||||
func TestSSHKey(t *testing.T) {
|
||||
s := newSandbox(t)
|
||||
a, b := "devvm-a-0123456789abcd", "devvm-b-0123456789abce"
|
||||
if filepath.Dir(s.sshKey(a)) != filepath.Dir(s.Dirs.VM(a).Record()) || s.sshKey(a) == s.sshKey(b) {
|
||||
t.Errorf("keys: %s, %s", s.sshKey(a), s.sshKey(b))
|
||||
}
|
||||
}
|
||||
|
||||
// A start with ssh forwards it from a host port, kept while it's free and
|
||||
// never one of its listed ports; services.sh gets the user, the VM's key and
|
||||
// the names of the variables its sessions get, never their values. SSH
|
||||
// answers once services.sh ran. A start without ssh takes the forward away.
|
||||
func TestStartSSH(t *testing.T) {
|
||||
s := newSandbox(t)
|
||||
vm := "devvm-s-0123456789abcd"
|
||||
s.machine(t, vm, "stopped 4 8192 20 true")
|
||||
if err := s.writeRecord(vm, record{Listed: []backend.PortRange{{From: 61022, To: 61022}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next := []int{61022, 61023}
|
||||
s.FreePort = func(context.Context) (int, error) { p := next[0]; next = next[1:]; return p, nil }
|
||||
if _, err := s.SSH(t.Context(), vm); msg.NamesOf(err) != "vm_not_running vm="+vm {
|
||||
t.Errorf("stopped: %v", err)
|
||||
}
|
||||
if err := s.Start(t.Context(), vm, backend.Confinement{SSH: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pub, err := vmssh.EnsureKey(s.sshKey(vm))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []string{
|
||||
"smolvm machine update --name " + vm + " -p 61023:22",
|
||||
"smolvm machine start --name " + vm,
|
||||
"smolvm machine exec --name " + vm + " -- sh -c " + sshdProbe,
|
||||
"smolvm machine exec --name " + vm + " -i -- sh -s -- ssh u " + pub,
|
||||
// Its listed port's forwarder, once its sshd runs: the host key.
|
||||
"smolvm machine exec --name " + vm + " -- cat " + vmssh.HostKeyPath,
|
||||
}
|
||||
if got := s.calls(t); !slices.Equal(got, want) {
|
||||
t.Errorf("calls:\n%q\nwant\n%q", got, want)
|
||||
}
|
||||
tgt, err := s.SSH(t.Context(), vm)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wantOpts := []backend.SSHOption{
|
||||
{Key: "IdentityFile", Value: `"` + s.sshKey(vm) + `"`},
|
||||
{Key: "IdentitiesOnly", Value: "yes"},
|
||||
{Key: "PreferredAuthentications", Value: "publickey"},
|
||||
}
|
||||
if tgt.Host != "127.0.0.1" || tgt.Port != 61023 || tgt.User != "u" || !slices.Equal(tgt.Options, wantOpts) || tgt.ConfigFile != "" {
|
||||
t.Errorf("SSH = %+v", tgt)
|
||||
}
|
||||
// Running, but its sshd not yet up (another devvm's start): no answer,
|
||||
// so nothing reads host keys about to be replaced.
|
||||
r, _ := s.readRecord(vm)
|
||||
r.SSHUp = false
|
||||
if err := s.writeRecord(vm, r); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.SSH(t.Context(), vm); msg.NamesOf(err) != "vm_no_ssh vm="+vm {
|
||||
t.Errorf("sshd not up: %v", err)
|
||||
}
|
||||
|
||||
// Again: the same port while it's free, else a new one.
|
||||
for _, tc := range []struct {
|
||||
free bool
|
||||
want string
|
||||
}{
|
||||
{true, ""},
|
||||
{false, " --remove-port 61023:22 -p 61099:22"},
|
||||
} {
|
||||
if err := s.Stop(t.Context(), vm); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.stubs.Reset(t)
|
||||
s.PortFree = func(context.Context, int) bool { return tc.free }
|
||||
next = []int{61099}
|
||||
if err := s.Start(t.Context(), vm, backend.Confinement{SSH: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := s.calls(t)
|
||||
if tc.want == "" && strings.HasPrefix(got[0], "smolvm machine update") || tc.want != "" && got[0] != "smolvm machine update --name "+vm+tc.want {
|
||||
t.Errorf("free %v: %q", tc.free, got)
|
||||
}
|
||||
}
|
||||
|
||||
// Network policy: its port, and the proxy's and Env's names for the
|
||||
// sessions; a port that's one of its listed ports is refused.
|
||||
if err := s.Stop(t.Context(), vm); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.stubs.Reset(t)
|
||||
c := backend.Confinement{
|
||||
Net: backend.NetProxy, ProxyPort: 3128, ProxyPassword: "proxy-pass!", SSH: true, SSHPort: 61022,
|
||||
Env: map[string]string{"NO_PROXY": "localhost"}, Decider: "127.0.0.1:4000", DeciderToken: strings.Repeat("ab", 32),
|
||||
}
|
||||
if err := s.Start(t.Context(), vm, c); msg.NamesOf(err) != "smolvm_ssh_port_forwarded port=61022 vm="+vm {
|
||||
t.Errorf("forwarded port: %v", err)
|
||||
}
|
||||
c.SSHPort = 40022
|
||||
if err := s.Start(t.Context(), vm, c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := s.calls(t)
|
||||
if !slices.Contains(got, "smolvm machine update --name "+vm+" --reset-allow-list --allow-cidr 100.96.0.1/32 --allow-host-pattern devvm.invalid --remove-port 61099:22 -p 40022:22") ||
|
||||
!strings.HasSuffix(got[len(got)-2], " -i -- sh -s -- ssh u "+pub+" HTTP_PROXY HTTPS_PROXY http_proxy https_proxy NO_PROXY") {
|
||||
t.Errorf("network policy: %q", got)
|
||||
}
|
||||
// The password has a "!", so no key's base64 or temp path holds it by chance.
|
||||
if strings.Contains(strings.Join(got, " "), "proxy-pass!") {
|
||||
t.Error("the password is in smolvm's arguments")
|
||||
}
|
||||
|
||||
// Without ssh: the forward goes, and so does SSH's target.
|
||||
if err := s.Stop(t.Context(), vm); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.stubs.Reset(t)
|
||||
if err := s.Start(t.Context(), vm, backend.Confinement{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := s.calls(t); got[0] != "smolvm machine update --name "+vm+" --net --reset-allow-list --no-egress-interceptor" ||
|
||||
!slices.Contains(got, "smolvm machine update --name "+vm+" --remove-port 40022:22") ||
|
||||
got[len(got)-1] != "smolvm machine exec --name "+vm+" -i -- sh -s --" {
|
||||
t.Errorf("without ssh: %q", got)
|
||||
}
|
||||
if _, err := s.SSH(t.Context(), vm); msg.NamesOf(err) != "vm_no_ssh vm="+vm {
|
||||
t.Errorf("without ssh: %v", err)
|
||||
}
|
||||
s.stubs.Touch(t, "smolvm-foreign-"+vm)
|
||||
if _, err := s.SSH(t.Context(), vm); !errors.Is(err, backend.ErrNotFound) {
|
||||
t.Errorf("someone else's: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// An image without sshd (made before devvm ran one): the VM starts and
|
||||
// runs without ssh, warned; it isn't stopped. rm deletes its key.
|
||||
func TestStartNoSSHD(t *testing.T) {
|
||||
s := newSandbox(t)
|
||||
vm := "devvm-o-0123456789abcd"
|
||||
s.machine(t, vm, "stopped 4 8192 20 true")
|
||||
s.stubs.Touch(t, "no-sshd")
|
||||
var warned msg.Recorder
|
||||
s.Warn = warned.Add
|
||||
if err := s.Start(t.Context(), vm, backend.Confinement{SSH: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m, err := s.inspect(t.Context(), vm); err != nil || m.status() != backend.StatusRunning {
|
||||
t.Errorf("not running: %+v, %v", m, err)
|
||||
}
|
||||
if !slices.Equal(warned.Names(), []string{"vm_no_sshd vm=" + vm}) {
|
||||
t.Errorf("warned %q", warned.Names())
|
||||
}
|
||||
// services.sh ran the rest, asked for no sshd.
|
||||
if got := s.calls(t); got[len(got)-1] != "smolvm machine exec --name "+vm+" -i -- sh -s --" {
|
||||
t.Errorf("calls: %q", got)
|
||||
}
|
||||
if _, err := s.SSH(t.Context(), vm); msg.NamesOf(err) != "vm_no_sshd vm="+vm {
|
||||
t.Errorf("SSH: %v", err)
|
||||
}
|
||||
if err := s.Delete(t.Context(), vm); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(s.sshKey(vm)); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Errorf("key kept: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestForwards(t *testing.T) {
|
||||
if sshForwardSpec(61022) != "61022:22" {
|
||||
t.Error(sshForwardSpec(61022))
|
||||
}
|
||||
if got := servicesArgs("u", "ssh-ed25519 AA c", map[string]string{"B": "1", "A": "2", "1x": "3"}, false); !slices.Equal(got, []string{"ssh", "u", "ssh-ed25519 AA c", "A", "B"}) {
|
||||
t.Errorf("servicesArgs = %q", got)
|
||||
}
|
||||
}
|
||||
@@ -1,401 +0,0 @@
|
||||
package smolvm
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"maps"
|
||||
"net/netip"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/w3cj/devvm/internal/backend"
|
||||
"github.com/w3cj/devvm/internal/backend/vmssh"
|
||||
"github.com/w3cj/devvm/internal/daemon"
|
||||
"github.com/w3cj/devvm/internal/msg"
|
||||
)
|
||||
|
||||
// A machine with network policy (NetProxy) reaches nothing but devvm's
|
||||
// proxy, in three parts:
|
||||
//
|
||||
// - its allow list is the gateway alone (gatewayCIDR), so smolvm refuses
|
||||
// connections anywhere else, and the gateway is every port of the host's
|
||||
// loopback;
|
||||
// - its DNS answers only dnsClosed, a name that doesn't exist (smolvm
|
||||
// answers every other query itself, NXDOMAIN, without asking anyone);
|
||||
// - it starts with mediated egress (--mediated-egress --egress-interceptor):
|
||||
// smolvm asks devvm's proxy, as its decider, about each connection the
|
||||
// allow list lets through, before it connects anywhere. The proxy takes
|
||||
// over those to itself and refuses the rest. A decider that's gone, or
|
||||
// doesn't know the token, refuses everything; and once a machine started
|
||||
// so, smolvm won't start it without a decider.
|
||||
const (
|
||||
gatewayCIDR = Gateway + "/32"
|
||||
dnsClosed = "devvm.invalid"
|
||||
)
|
||||
|
||||
// Start starts a stopped machine with the network c asks for, then what
|
||||
// base's services do at boot on Lima (services.sh): smolvm runs no init
|
||||
// system. A running machine is left as it is.
|
||||
//
|
||||
// Its network and environment are set while it's stopped, where they
|
||||
// differ: NetDirect and NetInternet are smolvm's own network, which reaches
|
||||
// the internet but not the host's loopback; NetNone is none; NetProxy is
|
||||
// devvm's proxy alone, through its decider (c.Decider), with the proxy's
|
||||
// address in HTTP_PROXY and HTTPS_PROXY (and lowercase), which devvm's
|
||||
// execs get from the machine's proxy file (proxyFile), so the password is
|
||||
// in no process's arguments. A machine made forwarding an SSH agent
|
||||
// forwards the one agentSocket chooses: none, c.AgentSocket, or the
|
||||
// user's (SSH_AUTH_SOCK). With c.SSH its ssh is forwarded (sshForward) and
|
||||
// services.sh runs its sshd; without, the forward goes. A VM that
|
||||
// forwards ports gets its forwarder once its sshd runs (forward): smolvm
|
||||
// forwards none of them.
|
||||
func (s *Smolvm) Start(ctx context.Context, vm string, c backend.Confinement) error {
|
||||
proxy := c.Net == backend.NetProxy
|
||||
if proxy {
|
||||
if err := checkDecider(vm, c); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
m, err := s.inspect(ctx, vm)
|
||||
if err != nil {
|
||||
return notFound(vm, err)
|
||||
}
|
||||
if m.status() == backend.StatusRunning {
|
||||
return nil
|
||||
}
|
||||
r, err := s.readRecord(vm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
agent := ""
|
||||
if r.Forwarding {
|
||||
if agent, err = agentSocket(vm, r, c, s.Getenv); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
var opts []string
|
||||
if proxy {
|
||||
if !m.closed() {
|
||||
opts = append(opts, "--reset-allow-list", "--allow-cidr", gatewayCIDR, "--allow-host-pattern", dnsClosed)
|
||||
}
|
||||
} else {
|
||||
// What a start through the decider left: the allow list, and the
|
||||
// decider required at every start.
|
||||
if len(m.AllowedCIDRs) > 0 || len(m.AllowedHosts) > 0 || r.Mediated {
|
||||
if err := s.update(ctx, vm, "--net", "--reset-allow-list", "--no-egress-interceptor"); err != nil {
|
||||
return err
|
||||
}
|
||||
m.Network, r.Mediated = true, false
|
||||
}
|
||||
if want := c.Net != backend.NetNone; m.Network != want {
|
||||
if want {
|
||||
opts = append(opts, "--net")
|
||||
} else {
|
||||
opts = append(opts, "--no-net")
|
||||
}
|
||||
}
|
||||
}
|
||||
env := maps.Clone(c.Env)
|
||||
for _, k := range backend.GuestProxyVars() {
|
||||
delete(env, k) // the proxy file's
|
||||
}
|
||||
// The VM's ssh: forwarded while it's asked for, its sshd run then.
|
||||
var sshd []string
|
||||
if c.SSH {
|
||||
port, err := s.sshForward(ctx, vm, c, r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pub, err := vmssh.EnsureKey(s.sshKey(vm))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
name, _, err := s.user()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if port != r.SSHPort {
|
||||
if r.SSHPort > 0 {
|
||||
opts = append(opts, "--remove-port", sshForwardSpec(r.SSHPort))
|
||||
}
|
||||
opts = append(opts, "-p", sshForwardSpec(port))
|
||||
}
|
||||
r.SSHPort, sshd = port, servicesArgs(name, pub, env, proxy)
|
||||
} else if r.SSHPort > 0 {
|
||||
opts = append(opts, "--remove-port", sshForwardSpec(r.SSHPort))
|
||||
r.SSHPort = 0
|
||||
}
|
||||
if err := s.update(ctx, vm, opts...); err != nil {
|
||||
return err
|
||||
}
|
||||
if !maps.Equal(r.Env, env) && (len(r.Env) > 0 || len(env) > 0) {
|
||||
var eopts []string
|
||||
for _, k := range slices.Sorted(maps.Keys(r.Env)) {
|
||||
if _, ok := env[k]; !ok {
|
||||
eopts = append(eopts, "--remove-env", k)
|
||||
}
|
||||
}
|
||||
for _, kv := range sortedEnv(env) {
|
||||
eopts = append(eopts, "-e", kv)
|
||||
}
|
||||
if err := s.update(ctx, vm, eopts...); err != nil {
|
||||
return err
|
||||
}
|
||||
r.Env = env
|
||||
}
|
||||
if err := s.setProxyFile(vm, s.ProxyURL(c)); err != nil {
|
||||
return err
|
||||
}
|
||||
// Recorded before the start: a start that fails leaves it unconfined,
|
||||
// and without ssh until services.sh ran its sshd.
|
||||
r.Mediated, r.Confined, r.Started = r.Mediated || proxy, "", ""
|
||||
r.SSHUp, r.NoSSHD = false, false
|
||||
if err := s.writeRecord(vm, r); err != nil {
|
||||
return err
|
||||
}
|
||||
args := []string{"machine", "start", "--name", vm}
|
||||
if proxy {
|
||||
args = append(args, "--mediated-egress", "--egress-interceptor", c.Decider)
|
||||
}
|
||||
cmd := s.smolvm(ctx, args...)
|
||||
// The token is in no process's arguments.
|
||||
if proxy {
|
||||
cmd.Env = setEnv(cmd.Env, "SMOLVM_INTERCEPTOR_TOKEN="+c.DeciderToken)
|
||||
} else {
|
||||
cmd.Env = setEnv(cmd.Env, "SMOLVM_INTERCEPTOR_TOKEN")
|
||||
}
|
||||
// The agent it forwards (agentSocket), read at this start alone; one
|
||||
// made without forwarding gets none (smolvm's commands never pass on
|
||||
// devvm's own SSH_AUTH_SOCK).
|
||||
if agent != "" {
|
||||
cmd.Env = setEnv(cmd.Env, "SSH_AUTH_SOCK="+agent)
|
||||
}
|
||||
if err := s.Runner.Run(ctx, msg.Starting(vm), cmd); err != nil {
|
||||
return backend.Logged(msg.StartFailed(vm))
|
||||
}
|
||||
if r.Started, err = s.lifeline(ctx, vm); err != nil {
|
||||
return err
|
||||
}
|
||||
if proxy {
|
||||
r.Confined = r.Started
|
||||
}
|
||||
if err := s.writeRecord(vm, r); err != nil {
|
||||
return err
|
||||
}
|
||||
noSSHD := false
|
||||
if sshd != nil {
|
||||
if noSSHD, err = s.lacksSSHD(ctx, vm); err != nil {
|
||||
return err
|
||||
}
|
||||
if noSSHD {
|
||||
s.Warn(msg.VMNoSshd(vm))
|
||||
sshd = nil
|
||||
}
|
||||
}
|
||||
if err := s.services(ctx, vm, sshd); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.SSHPort > 0 {
|
||||
r.SSHUp, r.NoSSHD = !noSSHD, noSSHD
|
||||
if err := s.writeRecord(vm, r); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
s.forward(ctx, vm, r, c)
|
||||
return nil
|
||||
}
|
||||
|
||||
// forward starts the forwarder of a VM that forwards ports, once its sshd
|
||||
// runs (forward.go), after stopping any it had, holding its lock
|
||||
// throughout: every port or its listed ones (its record's as it reads
|
||||
// them then, c.Forwarded), its host key read through smolvm, and never on
|
||||
// its own ssh's, proxy's or decider's port. One that can't start is warned
|
||||
// about: the VM runs on. A VM that forwards none is left without one.
|
||||
func (s *Smolvm) forward(ctx context.Context, vm string, r record, c backend.Confinement) {
|
||||
failed := func() { s.Warn(msg.PortsForwardFailed(s.Forwards.Log(vm), vm)) }
|
||||
unlock, err := s.Forwards.Lock(ctx, vm)
|
||||
if err != nil {
|
||||
failed()
|
||||
return
|
||||
}
|
||||
defer unlock()
|
||||
s.Forwards.Stop(vm)
|
||||
// Another devvm's SetPorts may have changed the ports since r was read.
|
||||
if cur, err := s.readRecord(vm); err == nil {
|
||||
r.PortsAll, r.Listed = cur.PortsAll, cur.Listed
|
||||
}
|
||||
only := c.Forwarded(ctx, backend.Ports{All: r.PortsAll, Ranges: r.Listed})
|
||||
if only != nil && len(only) == 0 {
|
||||
return
|
||||
}
|
||||
if !r.SSHUp {
|
||||
s.Warn(msg.PortsNoSSH(vm))
|
||||
return
|
||||
}
|
||||
out, err := vmOutput(ctx, s.Runner, func(ctx context.Context) *exec.Cmd {
|
||||
return s.smolvm(ctx, "machine", "exec", "--name", vm, "--", "cat", vmssh.HostKeyPath)
|
||||
})
|
||||
key, ok := vmssh.HostKey(out)
|
||||
name, _, uerr := s.user()
|
||||
lifeline := s.Lifeline(ctx, vm)
|
||||
if err != nil || !ok || uerr != nil || lifeline == "" {
|
||||
failed()
|
||||
return
|
||||
}
|
||||
spec := vmssh.Spec{
|
||||
User: name, Key: s.sshKey(vm), HostKey: key, Only: only,
|
||||
Reserve: []int{r.SSHPort, c.ProxyPort, deciderPort(c.Decider)},
|
||||
Args: []string{"-lifeline", lifeline, "-port", strconv.Itoa(r.SSHPort)},
|
||||
}
|
||||
if s.Forwards.Start(vm, spec) != nil {
|
||||
failed()
|
||||
}
|
||||
}
|
||||
|
||||
// What devvm reads of what the VM prints, and how long it waits for it:
|
||||
// root in the VM decides both.
|
||||
const (
|
||||
vmOutputMax = 64 << 10
|
||||
vmOutputTimeout = 30 * time.Second
|
||||
)
|
||||
|
||||
// vmOutput runs the command mk makes, whose output the VM makes, through
|
||||
// r, returning at most vmOutputMax bytes of it and waiting vmOutputTimeout
|
||||
// at most.
|
||||
func vmOutput(ctx context.Context, r Runner, mk func(context.Context) *exec.Cmd) ([]byte, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, vmOutputTimeout)
|
||||
defer cancel()
|
||||
out := &vmssh.Capped{Max: vmOutputMax}
|
||||
cmd := mk(ctx)
|
||||
cmd.Stdout, cmd.WaitDelay = out, time.Second
|
||||
err := r.Attach(cmd)
|
||||
return out.Bytes(), err
|
||||
}
|
||||
|
||||
// sshdProbe answers "sshd" when the machine's image has sshd, else "none".
|
||||
const sshdProbe = `if [ -x /usr/sbin/sshd ] || command -v sshd >/dev/null 2>&1; then echo sshd; else echo none; fi`
|
||||
|
||||
// lacksSSHD reports whether a running machine's image has no sshd (made
|
||||
// before devvm installed one), asked before services.sh runs, so no other
|
||||
// failure reads as it; one that can't say stops it.
|
||||
func (s *Smolvm) lacksSSHD(ctx context.Context, vm string) (bool, error) {
|
||||
out, err := vmOutput(ctx, s.Runner, func(ctx context.Context) *exec.Cmd {
|
||||
return s.smolvm(ctx, "machine", "exec", "--name", vm, "--", "sh", "-c", sshdProbe)
|
||||
})
|
||||
switch strings.TrimSpace(string(out)) {
|
||||
case "none":
|
||||
return true, nil
|
||||
case "sshd":
|
||||
if err == nil {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
if ctx.Err() == nil {
|
||||
_ = s.stop(ctx, vm)
|
||||
}
|
||||
return false, backend.Logged(msg.StartFailed(vm))
|
||||
}
|
||||
|
||||
// closed reports whether the machine's allow lists are network policy's:
|
||||
// the gateway alone, and DNS for dnsClosed alone. smolvm's JSON doesn't show
|
||||
// its UDP allows, deny lists or egress rules.
|
||||
func (m machine) closed() bool {
|
||||
return slices.Equal(m.AllowedCIDRs, []string{gatewayCIDR}) && slices.Equal(m.AllowedHosts, []string{"=" + dnsClosed})
|
||||
}
|
||||
|
||||
// checkDecider checks a NetProxy start has a decider: on host loopback,
|
||||
// with a token of 64 hex digits.
|
||||
func checkDecider(vm string, c backend.Confinement) error {
|
||||
at, err := netip.ParseAddrPort(c.Decider)
|
||||
tok, terr := hex.DecodeString(c.DeciderToken)
|
||||
if err != nil || !at.Addr().IsLoopback() || terr != nil || len(tok) != 32 {
|
||||
return fmt.Errorf("smolvm: %s: no decider to start it through", vm)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// services runs services.sh in a running machine, with args (servicesArgs
|
||||
// for its sshd); a failure stops it.
|
||||
func (s *Smolvm) services(ctx context.Context, vm string, args []string) error {
|
||||
script, err := s.containerScript("services.sh")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cmd := s.asRoot(ctx, vm, args...)
|
||||
cmd.Stdin = bytes.NewReader(script)
|
||||
if err := s.Runner.Run(ctx, msg.M{}, cmd); err != nil {
|
||||
if ctx.Err() == nil {
|
||||
_ = s.stop(ctx, vm)
|
||||
}
|
||||
return backend.Logged(msg.StartFailed(vm))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Confined reports whether the machine runs on the process Start started
|
||||
// through devvm's decider: its lifeline is the one recorded then, that
|
||||
// process runs, and its allow lists are still network policy's (smolvm
|
||||
// changes them on a running machine). A machine started any other way since
|
||||
// (smolvm machine start, with a decider of someone else's), or whose allow
|
||||
// list was widened, isn't.
|
||||
func (s *Smolvm) Confined(ctx context.Context, vm string) (bool, error) {
|
||||
r, err := s.readRecord(vm)
|
||||
if err != nil || r.Confined == "" {
|
||||
return false, err
|
||||
}
|
||||
m, err := s.inspect(ctx, vm)
|
||||
if err != nil {
|
||||
return false, notFound(vm, err)
|
||||
}
|
||||
if m.status() != backend.StatusRunning || !m.closed() {
|
||||
return false, nil
|
||||
}
|
||||
cur, err := s.lifeline(ctx, vm)
|
||||
return err == nil && runsOn(cur, r.Confined), err
|
||||
}
|
||||
|
||||
// StartID is what a running machine's lifeline holds: the pid and start
|
||||
// time of the process that runs it, which each start makes anew.
|
||||
func (s *Smolvm) StartID(ctx context.Context, vm string) (string, error) {
|
||||
m, err := s.inspect(ctx, vm)
|
||||
if err != nil {
|
||||
return "", notFound(vm, err)
|
||||
}
|
||||
if m.status() != backend.StatusRunning {
|
||||
return "", nil
|
||||
}
|
||||
return s.lifeline(ctx, vm)
|
||||
}
|
||||
|
||||
// runsOn reports whether a machine whose lifeline holds cur runs on the
|
||||
// process recorded as want: the same, and that process runs.
|
||||
func runsOn(cur, want string) bool {
|
||||
return want != "" && cur == want && daemon.LifeRuns(cur)
|
||||
}
|
||||
|
||||
// lifeline returns what the machine's lifeline holds (its pid and start
|
||||
// time), "" when there's none.
|
||||
func (s *Smolvm) lifeline(ctx context.Context, vm string) (string, error) {
|
||||
path := s.Lifeline(ctx, vm)
|
||||
if path == "" {
|
||||
return "", nil
|
||||
}
|
||||
return daemon.ReadLifeline(path)
|
||||
}
|
||||
|
||||
// Lifeline is the pid file of the process that runs the machine, in
|
||||
// smolvm's folder for it: its first line is the pid, its second the start
|
||||
// time. "" when smolvm can't say where that is.
|
||||
func (s *Smolvm) Lifeline(ctx context.Context, vm string) string {
|
||||
dir := s.dataDir(ctx, vm)
|
||||
if dir == "" {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(dir, "agent.pid")
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
package smolvm
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
|
||||
"github.com/w3cj/devvm/internal/backend"
|
||||
"github.com/w3cj/devvm/internal/image"
|
||||
"github.com/w3cj/devvm/internal/msg"
|
||||
)
|
||||
|
||||
// ToolsVM is the throwaway machine shared tools are built in.
|
||||
const ToolsVM = "devvm-tools-build"
|
||||
|
||||
// BuildTools makes ToolsVM from base's pack, with spec.Out its only mount,
|
||||
// starts it with the network spec.Net asks for, runs the script with its
|
||||
// arguments as the VM's user, makes each image it wrote uncompressed
|
||||
// (plain.sh, ToolFormat), and deletes it. A ToolsVM of devvm's left by an
|
||||
// earlier run is deleted first, and the machine goes however the run ends
|
||||
// (a cleanup on the ui stack).
|
||||
func (s *Smolvm) BuildTools(ctx context.Context, spec backend.ToolsSpec) error {
|
||||
if spec.Net != backend.NetInternet && spec.Net != backend.NetNone {
|
||||
return fmt.Errorf("smolvm: builds are confined, not started with network %d", spec.Net)
|
||||
}
|
||||
if spec.Format != s.ToolFormat() {
|
||||
return fmt.Errorf("smolvm: tool images are %s, not %q", s.ToolFormat(), spec.Format)
|
||||
}
|
||||
if !image.IsKey(spec.Base) {
|
||||
return fmt.Errorf("smolvm: invalid image key %q", spec.Base)
|
||||
}
|
||||
if !filepath.IsAbs(spec.Out) || !filepath.IsAbs(spec.OutAt) {
|
||||
return fmt.Errorf("smolvm: the tools build's folders must be absolute: %q at %q", spec.Out, spec.OutAt)
|
||||
}
|
||||
if _, err := os.Stat(s.packFile(spec.Base)); err != nil {
|
||||
return msg.ImageMissing(spec.Base)
|
||||
}
|
||||
if err := s.removeIfThere(ctx, ToolsVM); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.absent(ctx, ToolsVM); err != nil {
|
||||
return err
|
||||
}
|
||||
out, err := volume(spec.Out, spec.OutAt, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cpus, mem, disk, err := s.baseSize()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// A failure leaves it to the cleanup, which runs once the caller has
|
||||
// shown the run log's end.
|
||||
done := s.AddCleanup(func(ctx context.Context) { _ = s.removeIfThere(ctx, ToolsVM) })
|
||||
// Its steps: create, start, the script (the user's CAs before it),
|
||||
// plain.sh, delete.
|
||||
steps := 5
|
||||
if !spec.Trust.None() {
|
||||
steps++
|
||||
}
|
||||
ctx = s.WithSteps(ctx, steps)
|
||||
if err := s.Runner.Run(ctx, msg.CloningImage("base"), s.smolvm(ctx, "machine", "create", "--name", ToolsVM,
|
||||
"--label", LabelKey+"="+s.Dirs.Data, "--from", s.packFile(spec.Base),
|
||||
"--cpus", strconv.Itoa(cpus), "--mem", mib(mem), "--storage", gibCeil(disk), "-v", out)); err != nil {
|
||||
return backend.Logged(msg.VMCreateFailed(ToolsVM))
|
||||
}
|
||||
if err := s.writeRecord(ToolsVM, record{Image: spec.Base}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.Start(ctx, ToolsVM, backend.Confinement{Net: spec.Net}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.runScript(ctx, ToolsVM, spec.Trust.Add, true); err != nil {
|
||||
return err
|
||||
}
|
||||
plainScript, err := s.script("plain.sh")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
args, err := s.userArgs(ToolsVM, "/", true, false, append([]string{"bash", "-s", "--"}, spec.Args...))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cmd := s.smolvm(ctx, args...)
|
||||
cmd.Stdin = bytes.NewReader(spec.Script.Data)
|
||||
if err := s.Runner.Run(ctx, msg.BuildingToolsIn(ToolsVM), cmd); err != nil {
|
||||
return backend.Logged(msg.ToolsBuildFailed())
|
||||
}
|
||||
files := []string{spec.OutAt}
|
||||
for i := 2; i < len(spec.Args); i += 3 {
|
||||
files = append(files, spec.Args[i])
|
||||
}
|
||||
plain := s.asRoot(ctx, ToolsVM, files...)
|
||||
plain.Stdin = bytes.NewReader(plainScript)
|
||||
if err := s.Runner.Run(ctx, msg.RunningScript("plain.sh", ToolsVM), plain); err != nil {
|
||||
return backend.Logged(msg.ToolsBuildFailed())
|
||||
}
|
||||
if err := s.remove(ctx, ToolsVM); err != nil {
|
||||
return err
|
||||
}
|
||||
done()
|
||||
return nil
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
package smolvm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/w3cj/devvm/internal/backend"
|
||||
"github.com/w3cj/devvm/internal/platform"
|
||||
)
|
||||
|
||||
var _ backend.UsageReporter = (*Smolvm)(nil)
|
||||
|
||||
// caches are smolvm's caches on macOS, under the user's cache folder,
|
||||
// which every machine of the user's shares with devvm's: what smolvm
|
||||
// unpacked of each pack a machine was made from (a disk per pack, named
|
||||
// by the SHA-256 of its .smolmachine), of each container image, and its
|
||||
// downloads. Its machines' own folders are beside them, in vms/, and
|
||||
// aren't caches.
|
||||
func caches() []struct{ name, path string } {
|
||||
return []struct{ name, path string }{
|
||||
{"pack disks", "smolvm/vms/" + packSeeds},
|
||||
{"image disks", "smolvm/image-seeds"},
|
||||
{"image archives", "smolvm-image-archives"},
|
||||
{"registry", "smolvm-registry"},
|
||||
}
|
||||
}
|
||||
|
||||
// packSeeds is the folder of smolvm's cache in which it keeps the disk it
|
||||
// unpacked of each pack, as v2-<the pack's SHA-256>-auto.
|
||||
const packSeeds = "_pack-storage-seeds"
|
||||
|
||||
// Usage is the disk each of devvm's machines takes (its folder, as
|
||||
// smolvm machine data-dir says), and on macOS smolvm's caches. On Linux
|
||||
// smolvm's state is devvm's own, in its data folder, and has no caches
|
||||
// shown apart.
|
||||
func (s *Smolvm) Usage(ctx context.Context) (backend.Usage, error) {
|
||||
u := backend.Usage{VMs: map[string]int64{}}
|
||||
vms, err := s.List(ctx)
|
||||
if err != nil {
|
||||
return u, err
|
||||
}
|
||||
for _, in := range vms {
|
||||
if dir := s.dataDir(ctx, in.Name); dir != "" {
|
||||
if n, err := platform.DiskUsage(dir); err == nil {
|
||||
u.VMs[in.Name] = n
|
||||
}
|
||||
}
|
||||
}
|
||||
if s.OS == "darwin" {
|
||||
u.Caches = cacheUsage(s.Dirs.UserCache)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// cacheUsage is smolvm's caches on macOS, each by entry, in the user's
|
||||
// cache folder (paths.Dirs.UserCache).
|
||||
func cacheUsage(cache string) []backend.Cache {
|
||||
if cache == "" {
|
||||
return nil
|
||||
}
|
||||
var out []backend.Cache
|
||||
for _, c := range caches() {
|
||||
dir := filepath.Join(cache, c.path)
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
cache := backend.Cache{Name: c.name, Path: dir}
|
||||
for _, e := range entries {
|
||||
if e.IsDir() && e.Name()[0] != '.' {
|
||||
cache.Count++
|
||||
}
|
||||
}
|
||||
if n, err := platform.DiskUsage(dir); err == nil {
|
||||
cache.Size, cache.Sized = n, true
|
||||
}
|
||||
out = append(out, cache)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -1,3 +1,7 @@
|
||||
// Package vmssh is what devvm runs over a VM's ssh on the host: the port
|
||||
// forwarder that reaches a Lima VM over Lima's ssh (Forwarder, run
|
||||
// detached by Forwards), and the sessions that carry links between VMs
|
||||
// (Links).
|
||||
package vmssh
|
||||
|
||||
import (
|
||||
@@ -29,10 +33,9 @@ import (
|
||||
)
|
||||
|
||||
// The forwarder forwards a VM's ports to the host's loopback, by the same
|
||||
// rules on every backend: Lima's own forwards share a port a host program
|
||||
// has (SO_REUSEADDR), and smolvm's are at most 64 and reach only servers
|
||||
// on all of the guest's addresses. It runs on the host, detached (devvm
|
||||
// _lima-ports, _smolvm-ports; Forwards), one per VM:
|
||||
// rules on every backend, where Lima's own forwards would share a port a
|
||||
// host program has (SO_REUSEADDR). It runs on the host, detached (devvm
|
||||
// _lima-ports; Forwards), one per VM:
|
||||
//
|
||||
// - it reaches the VM only through the VM's sshd, as the VM's user with
|
||||
// its own key, the host key read through the backend at the start and
|
||||
@@ -46,7 +49,7 @@ import (
|
||||
// (proxy.IsLinkAddr): every port from 1024 up, or the VM's listed ports alone
|
||||
// (Only); never on a port the host has on any address (no SO_REUSEADDR:
|
||||
// platform.ListenExclusive), nor on a port devvm records for any VM
|
||||
// (ssh, proxy, decider, listed forwards) but the VM's own listed ones;
|
||||
// (ssh, proxy, desktop, listed forwards) but the VM's own listed ones;
|
||||
// - every connection starts on the host: the VM opens none to the host
|
||||
// through it, and the master asks for no forwarding into the host;
|
||||
// - it ends once the VM no longer runs as it did when it started (Alive),
|
||||
|
||||
@@ -357,17 +357,6 @@ func TestLogLimit(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// What a VM prints is kept up to the cap.
|
||||
func TestCapped(t *testing.T) {
|
||||
c := &Capped{Max: 4}
|
||||
if n, err := c.Write([]byte("abc")); n != 3 || err != nil {
|
||||
t.Fatal(n, err)
|
||||
}
|
||||
if n, _ := c.Write([]byte("defg")); n != 4 || c.String() != "abcd" {
|
||||
t.Errorf("kept %q", c.String())
|
||||
}
|
||||
}
|
||||
|
||||
// While devvm's ports can't be read, nothing new is forwarded.
|
||||
func TestForwarderReservedUnknown(t *testing.T) {
|
||||
p := freePorts(t, 1)[0]
|
||||
|
||||
@@ -35,7 +35,7 @@ type Forwards struct {
|
||||
// folders can be too long for a socket.
|
||||
Run string
|
||||
// Cmd is devvm's hidden command that runs a forwarder
|
||||
// (_smolvm-ports), and Self is devvm's binary, which runs it.
|
||||
// (_lima-ports), and Self is devvm's binary, which runs it.
|
||||
Cmd, Self string
|
||||
// Detach starts a process that outlives devvm (daemon.Detach).
|
||||
Detach daemon.Starter
|
||||
|
||||
@@ -1,183 +0,0 @@
|
||||
// Package vmssh is devvm's own ssh into VMs whose backend has none for
|
||||
// editors (smolvm's machines): each VM's key, its
|
||||
// sshd's host key as devvm reads it, what services.sh is told to run its
|
||||
// sshd with, and the port forwarder that reaches the VM over that ssh, or
|
||||
// a Lima VM over Lima's (Forwarder, run detached by Forwards).
|
||||
package vmssh
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"maps"
|
||||
"os"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/w3cj/devvm/internal/shell"
|
||||
"github.com/w3cj/devvm/internal/state"
|
||||
)
|
||||
|
||||
// Comment is the comment of devvm's keys for its VMs.
|
||||
const Comment = "devvm"
|
||||
|
||||
// EnsureKey makes a VM's key at path when it's missing (or isn't one of
|
||||
// devvm's), and returns its public half as an authorized_keys line, read
|
||||
// from the private key itself: one file, written whole, mode 600. Its
|
||||
// public half is that VM's only authorized key, so it logs in to no other.
|
||||
func EnsureKey(path string) (string, error) {
|
||||
b, err := os.ReadFile(path) //nolint:gosec // devvm's own file
|
||||
if err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return "", err
|
||||
}
|
||||
if pub, ok := Public(b); ok {
|
||||
return pub, nil
|
||||
}
|
||||
privPEM, pub, err := newKey(Comment)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return pub, state.WriteFile(path, privPEM)
|
||||
}
|
||||
|
||||
// Public returns the public half of an ed25519 key in OpenSSH's format,
|
||||
// unencrypted (as devvm writes it), as an authorized_keys line.
|
||||
func Public(privPEM []byte) (string, bool) {
|
||||
blk, _ := pem.Decode(privPEM)
|
||||
if blk == nil || blk.Type != "OPENSSH PRIVATE KEY" {
|
||||
return "", false
|
||||
}
|
||||
rest, ok := bytes.CutPrefix(blk.Bytes, []byte("openssh-key-v1\x00"))
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
var fields [4][]byte
|
||||
for i := range fields {
|
||||
if fields[i], rest, ok = field(rest); !ok {
|
||||
return "", false
|
||||
}
|
||||
if i == 2 { // the key count
|
||||
if len(rest) < 4 || binary.BigEndian.Uint32(rest) != 1 {
|
||||
return "", false
|
||||
}
|
||||
rest = rest[4:]
|
||||
}
|
||||
}
|
||||
// cipher none, kdf none, no kdf options, then the public key's blob.
|
||||
blob := fields[3]
|
||||
if string(fields[0]) != "none" || string(fields[1]) != "none" || len(fields[2]) != 0 {
|
||||
return "", false
|
||||
}
|
||||
kt, keyRest, ok := field(blob)
|
||||
if pk, _, pok := field(keyRest); !ok || !pok || string(kt) != "ssh-ed25519" || len(pk) != ed25519.PublicKeySize {
|
||||
return "", false
|
||||
}
|
||||
if inner, _, iok := field(rest); !iok || len(inner) == 0 {
|
||||
return "", false
|
||||
}
|
||||
return "ssh-ed25519 " + base64.StdEncoding.EncodeToString(blob) + " " + Comment, true
|
||||
}
|
||||
|
||||
// field reads one ssh wire format string from b.
|
||||
func field(b []byte) (f, rest []byte, ok bool) {
|
||||
if len(b) < 4 {
|
||||
return nil, nil, false
|
||||
}
|
||||
n := int64(binary.BigEndian.Uint32(b))
|
||||
if int64(len(b)-4) < n {
|
||||
return nil, nil, false
|
||||
}
|
||||
return b[4 : 4+n], b[4+n:], true
|
||||
}
|
||||
|
||||
// pubLine is an ed25519 public key line, as newKey writes it.
|
||||
var pubLine = regexp.MustCompile(`^ssh-ed25519 [A-Za-z0-9+/]+=* [A-Za-z0-9.-]+\n?$`)
|
||||
|
||||
// newKey makes an ed25519 key: the private one in OpenSSH's format,
|
||||
// unencrypted, and the public one as an authorized_keys line.
|
||||
func newKey(comment string) (privPEM []byte, pub string, err error) {
|
||||
pk, priv, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
blob := wireString(nil, []byte("ssh-ed25519"))
|
||||
blob = wireString(blob, pk)
|
||||
var check [4]byte
|
||||
if _, err := rand.Read(check[:]); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
inner := append(append([]byte{}, check[:]...), check[:]...)
|
||||
inner = wireString(inner, []byte("ssh-ed25519"))
|
||||
inner = wireString(inner, pk)
|
||||
inner = wireString(inner, priv)
|
||||
inner = wireString(inner, []byte(comment))
|
||||
for i := byte(1); len(inner)%8 != 0; i++ {
|
||||
inner = append(inner, i)
|
||||
}
|
||||
body := wireString([]byte("openssh-key-v1\x00"), []byte("none"))
|
||||
body = wireString(body, []byte("none"))
|
||||
body = wireString(body, nil)
|
||||
body = binary.BigEndian.AppendUint32(body, 1)
|
||||
body = wireString(body, blob)
|
||||
body = wireString(body, inner)
|
||||
privPEM = pem.EncodeToMemory(&pem.Block{Type: "OPENSSH PRIVATE KEY", Bytes: body})
|
||||
return privPEM, "ssh-ed25519 " + base64.StdEncoding.EncodeToString(blob) + " " + comment, nil
|
||||
}
|
||||
|
||||
// wireString appends b to buf as the ssh wire format's string: its length,
|
||||
// then its bytes.
|
||||
func wireString(buf, b []byte) []byte {
|
||||
return append(binary.BigEndian.AppendUint32(buf, uint32(len(b))), b...) //nolint:gosec // devvm's own short fields
|
||||
}
|
||||
|
||||
// hostKeyLine is an ed25519 public key line, as the VM's sshd has it.
|
||||
var hostKeyLine = regexp.MustCompile(`^ssh-ed25519 [A-Za-z0-9+/]+=*(\s|$)`)
|
||||
|
||||
// HostKey returns the key type and base64 of the VM's sshd's host key, as
|
||||
// cat of its .pub file gives them.
|
||||
func HostKey(out []byte) (string, bool) {
|
||||
line, _, _ := strings.Cut(strings.TrimSpace(string(out)), "\n")
|
||||
if !hostKeyLine.MatchString(line) {
|
||||
return "", false
|
||||
}
|
||||
f := strings.Fields(line)
|
||||
return f[0] + " " + f[1], true
|
||||
}
|
||||
|
||||
// HostKeyPath is the VM's sshd's host key's public half, which services.sh
|
||||
// makes at each start.
|
||||
const HostKeyPath = "/etc/ssh/ssh_host_ed25519_key.pub"
|
||||
|
||||
// ServicesArgs are services.sh's arguments for a start that runs the VM's
|
||||
// sshd: the user, devvm's public key, and the names of the variables its
|
||||
// sessions get from the start's environment (first, then env's), values
|
||||
// never in arguments.
|
||||
func ServicesArgs(user, pub string, first []string, env map[string]string) []string {
|
||||
names := slices.Clone(first)
|
||||
for _, k := range slices.Sorted(maps.Keys(env)) {
|
||||
if shell.EnvName(k) {
|
||||
names = append(names, k)
|
||||
}
|
||||
}
|
||||
return append([]string{"ssh", user, pub}, names...)
|
||||
}
|
||||
|
||||
// Capped keeps the first Max bytes written to it, and takes the rest
|
||||
// without keeping it: what devvm reads of what a VM prints.
|
||||
type Capped struct {
|
||||
bytes.Buffer
|
||||
Max int
|
||||
}
|
||||
|
||||
func (w *Capped) Write(p []byte) (int, error) {
|
||||
if room := w.Max - w.Len(); room > 0 {
|
||||
w.Buffer.Write(p[:min(len(p), room)])
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
package vmssh
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A VM's key is OpenSSH's ed25519 format, which ssh-keygen reads back to
|
||||
// the same public key, as devvm reads it from the private key; it's made
|
||||
// once per VM, one file, mode 600, and again when it's gone or isn't one.
|
||||
func TestKey(t *testing.T) {
|
||||
priv, pub, err := newKey(Comment)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !pubLine.MatchString(pub) || !strings.HasPrefix(string(priv), "-----BEGIN OPENSSH PRIVATE KEY-----\n") {
|
||||
t.Fatalf("key: %q\n%s", pub, priv)
|
||||
}
|
||||
if got, ok := Public(priv); !ok || got != pub {
|
||||
t.Errorf("Public = %q, %v; want %q", got, ok, pub)
|
||||
}
|
||||
for _, bad := range [][]byte{nil, []byte("garbage"), priv[:len(priv)/2], []byte("-----BEGIN OPENSSH PRIVATE KEY-----\nAAAA\n-----END OPENSSH PRIVATE KEY-----\n")} {
|
||||
if _, ok := Public(bad); ok {
|
||||
t.Errorf("Public(%q) = ok", bad)
|
||||
}
|
||||
}
|
||||
if kg, err := exec.LookPath("ssh-keygen"); err == nil {
|
||||
f := filepath.Join(t.TempDir(), "key")
|
||||
if err := os.WriteFile(f, priv, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out, err := exec.CommandContext(t.Context(), kg, "-y", "-f", f).Output() //nolint:gosec // the test's own file
|
||||
if err == nil && len(strings.Fields(string(out))) > 1 && strings.Fields(string(out))[1] != strings.Fields(pub)[1] {
|
||||
t.Errorf("ssh-keygen reads %q, want %q", out, pub)
|
||||
}
|
||||
}
|
||||
|
||||
dir := t.TempDir()
|
||||
a, b := filepath.Join(dir, "a.key"), filepath.Join(dir, "b.key")
|
||||
first, err := EnsureKey(a)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fi, err := os.Stat(a); err != nil || fi.Mode().Perm() != 0o600 {
|
||||
t.Errorf("%s: %v, %v", a, fi, err)
|
||||
}
|
||||
if again, err := EnsureKey(a); err != nil || again != first {
|
||||
t.Errorf("again: %q, %v", again, err)
|
||||
}
|
||||
if other, err := EnsureKey(b); err != nil || other == first {
|
||||
t.Errorf("another VM's: %q, %v", other, err)
|
||||
}
|
||||
if err := os.WriteFile(a, []byte("not a key"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fresh, err := EnsureKey(a); err != nil || fresh == first || !pubLine.MatchString(fresh) {
|
||||
t.Errorf("not a key: %q, %v", fresh, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A host key is read as its type and key, ed25519 alone.
|
||||
func TestHostKey(t *testing.T) {
|
||||
for out, want := range map[string]string{
|
||||
"ssh-ed25519 AAAAC3Nz root@x\n": "ssh-ed25519 AAAAC3Nz",
|
||||
"ssh-ed25519 AAAA\nssh-rsa B\n": "ssh-ed25519 AAAA",
|
||||
"ssh-rsa AAAA x\n": "",
|
||||
"ssh-ed25519 AA$A\n": "",
|
||||
"": "",
|
||||
} {
|
||||
if got, ok := HostKey([]byte(out)); got != want || ok != (want != "") {
|
||||
t.Errorf("HostKey(%q) = %q, %v", out, got, ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// services.sh gets the user, the key and the variables' names, never their
|
||||
// values: first's, then env's sorted, names that aren't left out.
|
||||
func TestServicesArgs(t *testing.T) {
|
||||
got := ServicesArgs("u", "ssh-ed25519 AA c", []string{"HTTP_PROXY"}, map[string]string{"B": "1", "A": "2", "1x": "3"})
|
||||
if !slices.Equal(got, []string{"ssh", "u", "ssh-ed25519 AA c", "HTTP_PROXY", "A", "B"}) {
|
||||
t.Errorf("ServicesArgs = %q", got)
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
)
|
||||
|
||||
// LifelineMain runs the forwarder of a VM whose sshd is forwarded to a
|
||||
// host loopback port (smolvm's, Lima's), as the hidden command name with
|
||||
// host loopback port (Lima's), as the hidden command name with
|
||||
// its arguments: ports.sh is script, reserved the ports devvm records for
|
||||
// VMs (but the VM's own listed ones), and its lines go to log. Besides the
|
||||
// forwarder's own flags, it takes the VM's lifeline (daemon.Lifeline),
|
||||
|
||||
@@ -236,7 +236,7 @@ func TestFlagErrors(t *testing.T) {
|
||||
{[]string{"network", "log", "--lines", "x"}, "flag_bad_value flag=--lines form=N value=x"},
|
||||
{[]string{"--clone=maybe"}, "flag_bad_switch flag=--clone value=maybe"},
|
||||
{[]string{"network", "log", "--blocked", "--follow"}, "flags_exclusive flag=--blocked other=--follow"},
|
||||
{[]string{"build", "--backend", "nope", "base"}, "backend_unknown backends=lima, smolvm name=nope"},
|
||||
{[]string{"build", "--backend", "nope", "base"}, "backend_unknown backends=lima name=nope"},
|
||||
{[]string{"ls", "--cpus", "4"}, "flag_unknown command=devvm ls flag=--cpus"},
|
||||
{[]string{"--ports", ""}, "flag_blank flag=ports"},
|
||||
{[]string{"gc", "--history", "--older-than", "30"}, "bad_duration value=30"},
|
||||
|
||||
@@ -29,9 +29,7 @@ func newBuildCmd(u *ui.UI) *cobra.Command {
|
||||
"An image holds no shared tools: a VM gets those when devvm makes it, or with devvm tools.",
|
||||
Example: examples(
|
||||
"devvm build docker", "build base and the docker layer on it",
|
||||
"devvm build foo+bar", "build base, foo and foo+bar",
|
||||
"devvm build base --backend smolvm", "build base on the smolvm backend",
|
||||
),
|
||||
"devvm build foo+bar", "build base, foo and foo+bar"),
|
||||
Args: exactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return imageCmd(cmd.Context(), u, f, args[0], build.Builds.Build)
|
||||
|
||||
@@ -37,9 +37,7 @@ func newDoctorCmd(u *ui.UI) *cobra.Command {
|
||||
"because devvm never installs it itself. Then list what each backend can do. " +
|
||||
"doctor fails when something is missing, but never for a warning, such as one about low free space.",
|
||||
Example: examples(
|
||||
"devvm doctor", "check the backend new VMs get",
|
||||
"devvm doctor --backend smolvm", "check the smolvm backend",
|
||||
"devvm doctor --json", "the same as JSON, for scripts",
|
||||
"devvm doctor", "check the backend new VMs get", "devvm doctor --json", "the same as JSON, for scripts",
|
||||
),
|
||||
Args: noArgs,
|
||||
ValidArgsFunction: cobra.NoFileCompletions,
|
||||
|
||||
+1
-3
@@ -73,9 +73,7 @@ func newGCCmd(u *ui.UI) *cobra.Command {
|
||||
Example: examples(
|
||||
"devvm gc", "delete stale images and unused tools, after asking",
|
||||
"devvm gc --tool-images", "also the current shared tool images no VM has",
|
||||
"devvm gc --history --older-than 30d", "also the history exports 30 days old or more",
|
||||
"devvm gc --backend smolvm", "delete every image and unused tool of the smolvm backend",
|
||||
"devvm gc --force", "delete without asking, as a script must",
|
||||
"devvm gc --history --older-than 30d", "also the history exports 30 days old or more", "devvm gc --force", "delete without asking, as a script must",
|
||||
),
|
||||
Args: func(_ *cobra.Command, args []string) error { return o.checkArgs(args) },
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
|
||||
@@ -58,14 +58,14 @@ func TestDeleteStaleKeepsImagesInUse(t *testing.T) {
|
||||
// the backend is named once among those that couldn't be asked.
|
||||
func TestWithoutSkipped(t *testing.T) {
|
||||
r := vm.LeftoverReport{
|
||||
Orphans: []vm.Orphan{{Name: "a", Backend: "lima"}, {Name: "b", Backend: "smolvm"}, {Name: "c", Backend: "smolvm"}, {Name: "d", Backend: "fake"}},
|
||||
Orphans: []vm.Orphan{{Name: "a", Backend: "lima"}, {Name: "b", Backend: "qemu"}, {Name: "c", Backend: "qemu"}, {Name: "d", Backend: "fake"}},
|
||||
Unknown: []string{"fake"},
|
||||
}
|
||||
got := withoutSkipped(r, map[string]bool{"smolvm": true, "fake": true})
|
||||
got := withoutSkipped(r, map[string]bool{"qemu": true, "fake": true})
|
||||
if len(got.Orphans) != 1 || got.Orphans[0].Name != "a" {
|
||||
t.Errorf("orphans %+v, want a alone", got.Orphans)
|
||||
}
|
||||
if !slices.Equal(got.Unknown, []string{"fake", "smolvm"}) {
|
||||
if !slices.Equal(got.Unknown, []string{"fake", "qemu"}) {
|
||||
t.Errorf("unknown %v", got.Unknown)
|
||||
}
|
||||
if got := withoutSkipped(r, nil); len(got.Orphans) != 4 || len(got.Unknown) != 1 {
|
||||
|
||||
@@ -174,7 +174,7 @@ func TestJSONShapes(t *testing.T) {
|
||||
Rows: []spaceRow{{What: "VMs", Backend: "lima", Count: 1, Size: 1, Sized: true, Kept: keptOnlyCopy, GC: 1, Rest: "devvm rm", Retain: "30d", RetainFrees: 1}},
|
||||
Total: 1, GC: 1,
|
||||
Caches: []cacheRow{{Backend: "lima", Name: "images", Path: "/c", Count: 1, Size: 1, Sized: true}},
|
||||
Unknown: []string{"smolvm"}, Strays: []strayVM{{Backend: "lima", Name: "devvm-b", Data: "/d"}},
|
||||
Unknown: []string{"qemu"}, Strays: []strayVM{{Backend: "lima", Name: "devvm-b", Data: "/d"}},
|
||||
}, []string{
|
||||
"backends[].backend: string", "backends[].count: number", "backends[].name: string", "backends[].path: string",
|
||||
"backends[].size: number", "backends[].sized: bool",
|
||||
|
||||
@@ -1,12 +1,52 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/w3cj/devvm/assets"
|
||||
"github.com/w3cj/devvm/internal/backend/lima"
|
||||
"github.com/w3cj/devvm/internal/msg"
|
||||
"github.com/w3cj/devvm/internal/netpolicy"
|
||||
"github.com/w3cj/devvm/internal/paths"
|
||||
"github.com/w3cj/devvm/internal/ui"
|
||||
)
|
||||
|
||||
// forwarderMain runs a backend's port forwarder (main) with its
|
||||
// arguments, ports.sh and the ports devvm records for VMs, which it never
|
||||
// forwards (netpolicy.UsedPorts) but its VM's own listed ones; its log
|
||||
// lines are data, written to devvm's stderr.
|
||||
type forwarderMain func(args []string, script []byte, reserved func(vm string) (map[int]bool, error)) error
|
||||
|
||||
// newForwarderCmd is a backend's hidden port forwarder command, which the
|
||||
// backend starts detached: use, short and run. Hidden: it's not for users.
|
||||
// Its flags are the forwarder's own, parsed by run.
|
||||
func newForwarderCmd(u *ui.UI, use, short string, run func(cmd *cobra.Command) forwarderMain) *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: use + " [flags]",
|
||||
Short: short,
|
||||
Hidden: true,
|
||||
DisableFlagParsing: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
fail := func(err error) { u.Die(msg.ForwarderFailed(err.Error()).Because(err)) }
|
||||
d, err := paths.FromEnv()
|
||||
if err != nil {
|
||||
fail(err)
|
||||
}
|
||||
script, err := fs.ReadFile(assets.FS, "guest/ports.sh")
|
||||
if err != nil {
|
||||
fail(err)
|
||||
}
|
||||
reserved := func(vm string) (map[int]bool, error) { return netpolicy.UsedPorts(d, vm) }
|
||||
if err := run(cmd)(args, script, reserved); err != nil {
|
||||
fail(err)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// newLimaPortsCmd is devvm _lima-ports: the port forwarder of a Lima VM
|
||||
// that forwards ports (lima.ForwardMain).
|
||||
func newLimaPortsCmd(u *ui.UI) *cobra.Command {
|
||||
|
||||
@@ -57,7 +57,7 @@ func NewRoot(u *ui.UI) *cobra.Command {
|
||||
addUpFlags(root, uf)
|
||||
addVersion(root)
|
||||
root.AddCommand(newBuildCmd(u), newRebuildCmd(u), newImagesCmd(u), newGCCmd(u), newSpaceCmd(u), newLayerCmd(u), newSetupCmd(u), newMsgCmd(u),
|
||||
newRestartCmd(u), newStopCmd(u), newToolsCmd(u), newAdoptCmd(u), newHistoryCmd(u), newRmCmd(u), newLsCmd(u), newNetworkCmd(u), newHostCmd(u), newCodeCmd(u), newDesktopCmd(u), newSSHAgentCmd(u), newGitProtectCmd(u), newPortsCmd(u), newSizeCmd(u), newDoctorCmd(u), newLimactlCmd(u), newQEMUCmd(u), newProxyCmd(u), newLimaPortsCmd(u), newSmolvmPortsCmd(u), newRefreshToolsCmd(u), newSecretCmd(u),
|
||||
newRestartCmd(u), newStopCmd(u), newToolsCmd(u), newAdoptCmd(u), newHistoryCmd(u), newRmCmd(u), newLsCmd(u), newNetworkCmd(u), newHostCmd(u), newCodeCmd(u), newDesktopCmd(u), newSSHAgentCmd(u), newGitProtectCmd(u), newPortsCmd(u), newSizeCmd(u), newDoctorCmd(u), newLimactlCmd(u), newQEMUCmd(u), newProxyCmd(u), newLimaPortsCmd(u), newRefreshToolsCmd(u), newSecretCmd(u),
|
||||
newLinkCmd(u), newGroupCmd(u), newLinksCmd(u), newRetentionCmd(u), newVersionCmd(u), newCompletionCmd(u))
|
||||
addCompletions(root, u)
|
||||
checkCommands(root)
|
||||
|
||||
@@ -153,9 +153,8 @@ func sandbox(env *testscript.Env, bin, stubs string) error {
|
||||
// VMs' proxies follow a stub hostagent that's gone before they
|
||||
// look: stop them with the sandbox.
|
||||
_ = exec.CommandContext(context.Background(), "pkill", "-f", "_proxy -listen .* -lifeline "+root+"/").Run() //nolint:gosec,forbidigo // the test's own folder; a cleanup, after the scripts' contexts end
|
||||
// And Lima's and smolvm's VMs' port forwarders.
|
||||
_ = exec.CommandContext(context.Background(), "pkill", "-f", "_lima-ports -vm .* -lifeline "+root+"/").Run() //nolint:gosec,forbidigo // the test's own folder; a cleanup, after the scripts' contexts end
|
||||
_ = exec.CommandContext(context.Background(), "pkill", "-f", "_smolvm-ports -vm .* -lifeline "+root+"/").Run() //nolint:gosec,forbidigo // the test's own folder; a cleanup, after the scripts' contexts end
|
||||
// And VMs' port forwarders.
|
||||
_ = exec.CommandContext(context.Background(), "pkill", "-f", "_lima-ports -vm .* -lifeline "+root+"/").Run() //nolint:gosec,forbidigo // the test's own folder; a cleanup, after the scripts' contexts end
|
||||
// And client VMs' link sessions, named only by their VM: by their
|
||||
// pid files, then the stub ssh's masters they leave.
|
||||
stopLinkSessions(root)
|
||||
@@ -227,9 +226,6 @@ func sandbox(env *testscript.Env, bin, stubs string) error {
|
||||
for name, v := range fakeHost() {
|
||||
env.Setenv(name, v)
|
||||
}
|
||||
// The stub smolvm's machines run on this process, which outlives each
|
||||
// command, as smolvm's own does.
|
||||
env.Setenv("SMOLVM_STUB_PID", strconv.Itoa(os.Getpid()))
|
||||
// The shared tools' versions: the stub mise, which resolves the
|
||||
// fixture lock.
|
||||
env.Setenv("DEVVM_HOST_MISE", filepath.Join(stubs, "mise"))
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
|
||||
"github.com/w3cj/devvm/assets"
|
||||
"github.com/w3cj/devvm/internal/backend"
|
||||
"github.com/w3cj/devvm/internal/backend/registry"
|
||||
"github.com/w3cj/devvm/internal/build"
|
||||
"github.com/w3cj/devvm/internal/msg"
|
||||
"github.com/w3cj/devvm/internal/paths"
|
||||
@@ -36,9 +35,7 @@ func newSetupCmd(u *ui.UI) *cobra.Command {
|
||||
"In a terminal devvm asks for each, starting from the current choice, and --backend, --features and --agents choose without asking. " +
|
||||
"A new choice of features rebuilds base and the images on it when they're next used.",
|
||||
Example: examples(
|
||||
"devvm setup", "answer every question",
|
||||
"devvm setup --backend smolvm", "make smolvm the default backend, without asking",
|
||||
"devvm setup --features omb,fzf", "give base oh-my-bash and fzf, without asking",
|
||||
"devvm setup", "answer every question", "devvm setup --features omb,fzf", "give base oh-my-bash and fzf, without asking",
|
||||
"devvm setup --features none", "give base no features",
|
||||
"devvm setup --agents claude,codex", "give new VMs Claude Code and Codex, without asking",
|
||||
),
|
||||
@@ -232,7 +229,7 @@ func (s setup) saveFeatures(dirs paths.Dirs, def settings.Defaults, features *st
|
||||
|
||||
// pickBackend asks which backend new VMs get by default, starting from
|
||||
// current, the one in effect (backend.Default when it's one devvm doesn't
|
||||
// have), the experimental ones marked.
|
||||
// have).
|
||||
func (s setup) pickBackend(reg *backend.Registry, current string) string {
|
||||
if _, ok := reg.Lookup(current); !ok {
|
||||
current = backend.Default
|
||||
@@ -241,9 +238,6 @@ func (s setup) pickBackend(reg *backend.Registry, current string) string {
|
||||
choices := make([]ui.Choice, len(names))
|
||||
for i, n := range names {
|
||||
choices[i] = ui.Choice{Name: n, On: n == current}
|
||||
if registry.Experimental(n) {
|
||||
choices[i].Desc = msg.BackendExperimental().String()
|
||||
}
|
||||
}
|
||||
return names[s.pickOne(msg.BackendHelp(), choices)]
|
||||
}
|
||||
|
||||
@@ -160,7 +160,7 @@ func savedBackend(t *testing.T, d paths.Dirs) string {
|
||||
}
|
||||
|
||||
// In a terminal, setup with neither flag asks for the backend (starting
|
||||
// from the current one, smolvm marked experimental), then the features;
|
||||
// from the current one), then the features;
|
||||
// --backend, --features or no terminal ask no backend.
|
||||
func TestSetupAsksForTheBackend(t *testing.T) {
|
||||
none := ""
|
||||
@@ -175,15 +175,15 @@ func TestSetupAsksForTheBackend(t *testing.T) {
|
||||
start string // the choice the picker starts on
|
||||
chosen bool // base's features chosen
|
||||
}{
|
||||
{name: "a terminal, nothing set", terminal: true, ask: true, start: "lima", want: "smolvm", chosen: true},
|
||||
{name: "a terminal, smolvm set", terminal: true, current: "smolvm", ask: true, start: "smolvm", want: "smolvm", chosen: true},
|
||||
{name: "a terminal, an unknown one set", terminal: true, current: "qemu", ask: true, start: "lima", want: "smolvm", chosen: true},
|
||||
{name: "a terminal, nothing set", terminal: true, ask: true, start: "lima", want: "lima", chosen: true},
|
||||
{name: "a terminal, lima set", terminal: true, current: "lima", ask: true, start: "lima", want: "lima", chosen: true},
|
||||
{name: "a terminal, an unknown one set", terminal: true, current: "qemu", ask: true, start: "lima", want: "lima", chosen: true},
|
||||
{name: "no terminal", want: "", chosen: true},
|
||||
{name: "--backend", terminal: true, flag: "lima", want: "lima"},
|
||||
{name: "--features", terminal: true, features: &none, current: "lima", want: "lima", chosen: true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s, d, shown, sized := setupSandbox(t, tc.terminal, "smolvm")
|
||||
s, d, shown, sized := setupSandbox(t, tc.terminal, "lima")
|
||||
if tc.current != "" {
|
||||
save(t, d, settings.Values{Backend: &tc.current})
|
||||
}
|
||||
@@ -213,7 +213,6 @@ func TestSetupAsksForTheBackend(t *testing.T) {
|
||||
} else if a != nil {
|
||||
want := []ui.Choice{
|
||||
{Name: "lima", On: tc.start == "lima"},
|
||||
{Name: "smolvm", Desc: "backend_experimental", On: tc.start == "smolvm"},
|
||||
}
|
||||
if a.help != "backend_help" || !slices.Equal(a.choices, want) {
|
||||
t.Errorf("shown %q %+v, want backend_help %+v", a.help, a.choices, want)
|
||||
@@ -232,7 +231,7 @@ func TestSetupAsksForTheBackend(t *testing.T) {
|
||||
// What config.toml sets, devvm setup doesn't ask for, saying so, and its
|
||||
// flags can't choose (set_in_config); it still asks for the rest.
|
||||
func TestSetupConfigSets(t *testing.T) {
|
||||
s, d, shown, sized := setupSandbox(t, true, "smolvm")
|
||||
s, d, shown, sized := setupSandbox(t, true, "lima")
|
||||
u, said, _ := testUI()
|
||||
s.ui = u
|
||||
config := "backend = \"lima\"\nnetwork = \"on\"\nfeatures = []\nagents = [\"codex\"]\n[size]\ncpus = 2\n"
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/w3cj/devvm/assets"
|
||||
"github.com/w3cj/devvm/internal/backend/smolvm"
|
||||
"github.com/w3cj/devvm/internal/msg"
|
||||
"github.com/w3cj/devvm/internal/netpolicy"
|
||||
"github.com/w3cj/devvm/internal/paths"
|
||||
"github.com/w3cj/devvm/internal/ui"
|
||||
)
|
||||
|
||||
// forwarderMain runs a backend's port forwarder (main) with its
|
||||
// arguments, ports.sh and the ports devvm records for VMs, which it never
|
||||
// forwards (netpolicy.UsedPorts) but its VM's own listed ones; its log
|
||||
// lines are data, written to devvm's stderr.
|
||||
type forwarderMain func(args []string, script []byte, reserved func(vm string) (map[int]bool, error)) error
|
||||
|
||||
// newForwarderCmd is a backend's hidden port forwarder command, which the
|
||||
// backend starts detached: use, short and run. Hidden: it's not for users.
|
||||
// Its flags are the forwarder's own, parsed by run.
|
||||
func newForwarderCmd(u *ui.UI, use, short string, run func(cmd *cobra.Command) forwarderMain) *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: use + " [flags]",
|
||||
Short: short,
|
||||
Hidden: true,
|
||||
DisableFlagParsing: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
fail := func(err error) { u.Die(msg.ForwarderFailed(err.Error()).Because(err)) }
|
||||
d, err := paths.FromEnv()
|
||||
if err != nil {
|
||||
fail(err)
|
||||
}
|
||||
script, err := fs.ReadFile(assets.FS, "container/ports.sh")
|
||||
if err != nil {
|
||||
fail(err)
|
||||
}
|
||||
reserved := func(vm string) (map[int]bool, error) { return netpolicy.UsedPorts(d, vm) }
|
||||
if err := run(cmd)(args, script, reserved); err != nil {
|
||||
fail(err)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// newSmolvmPortsCmd is devvm _smolvm-ports: the port forwarder of a smolvm
|
||||
// VM that forwards ports (smolvm.ForwardMain).
|
||||
func newSmolvmPortsCmd(u *ui.UI) *cobra.Command {
|
||||
return newForwarderCmd(u, "_smolvm-ports", "Forward a smolvm VM's ports", func(cmd *cobra.Command) forwarderMain {
|
||||
return func(args []string, script []byte, reserved func(string) (map[int]bool, error)) error {
|
||||
return smolvm.ForwardMain(cmd.Context(), args, script, reserved, u.Stderr())
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -56,9 +56,7 @@ func newSpaceCmd(u *ui.UI) *cobra.Command {
|
||||
"what devvm gc frees of it now and what frees the rest, then the backends' own caches apart. " +
|
||||
"It changes nothing and starts no VM.",
|
||||
Example: examples(
|
||||
"devvm space", "show what devvm keeps and what frees it",
|
||||
"devvm space --backend smolvm", "only the smolvm backend's",
|
||||
"devvm space --json", "the same as JSON, for scripts",
|
||||
"devvm space", "show what devvm keeps and what frees it", "devvm space --json", "the same as JSON, for scripts",
|
||||
),
|
||||
Args: noArgs,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
@@ -565,17 +563,17 @@ func (e spaceEnv) retainOf(keys ...string) string {
|
||||
|
||||
// otherState is the disk devvm's other state takes: the VMs' folders (their
|
||||
// logs and the orphans' are counted apart, by the caller), images'
|
||||
// records, run files, CA, the backends' own files, the tools lock and the
|
||||
// --from digests in the cache.
|
||||
// records, run files, CA, the tools lock and the --from digests in the
|
||||
// cache.
|
||||
func otherState(d paths.Dirs) int64 {
|
||||
var n int64
|
||||
for _, p := range []string{
|
||||
d.VMs(), d.Images(), d.FromDigests(), d.Run(), d.CA(), d.Smolvm(),
|
||||
d.VMs(), d.Images(), d.FromDigests(), d.Run(), d.CA(),
|
||||
d.ToolLock(), d.ToolLockConfig(), d.ToolLockChecked(),
|
||||
} {
|
||||
n += du(p)
|
||||
}
|
||||
return n - du(filepath.Join(d.Smolvm(), "images"))
|
||||
return n
|
||||
}
|
||||
|
||||
// counted is how many and how much.
|
||||
|
||||
@@ -19,7 +19,7 @@ import (
|
||||
func TestToolsOn(t *testing.T) {
|
||||
ts := []tools.Listed{
|
||||
{File: "node-1-0123456789ab.erofs", Backend: "lima", Targeted: true},
|
||||
{File: "go-1.20.0-0123456789ab.erofs", Backend: "smolvm", Targeted: true},
|
||||
{File: "go-1.20.0-0123456789ab.erofs", Backend: "fake", Targeted: true},
|
||||
{File: "go-1.9.0-0123456789ab.erofs"},
|
||||
}
|
||||
files := func(ls []tools.Listed) string {
|
||||
@@ -30,10 +30,10 @@ func TestToolsOn(t *testing.T) {
|
||||
return strings.Join(out, " ")
|
||||
}
|
||||
for name, want := range map[string]string{
|
||||
"": "node-1-0123456789ab.erofs go-1.20.0-0123456789ab.erofs go-1.9.0-0123456789ab.erofs",
|
||||
"lima": "node-1-0123456789ab.erofs",
|
||||
"smolvm": "go-1.20.0-0123456789ab.erofs",
|
||||
"fake": "",
|
||||
"": "node-1-0123456789ab.erofs go-1.20.0-0123456789ab.erofs go-1.9.0-0123456789ab.erofs",
|
||||
"lima": "node-1-0123456789ab.erofs",
|
||||
"fake": "go-1.20.0-0123456789ab.erofs",
|
||||
"qemu": "",
|
||||
} {
|
||||
if got := files(toolsOn(name, ts)); got != want {
|
||||
t.Errorf("toolsOn(%q) = %q, want %q", name, got, want)
|
||||
@@ -158,7 +158,7 @@ func TestWriteSpace(t *testing.T) {
|
||||
r := spaceReport{
|
||||
Rows: []spaceRow{
|
||||
{What: "images", Backend: "lima", Count: 2, Size: 2048, Sized: true, Kept: keptRemade, GC: 1024, Rest: "gc --backend lima"},
|
||||
{What: "VMs", Backend: "smolvm", Count: 1, Kept: keptOnlyCopy, Rest: "devvm rm"},
|
||||
{What: "VMs", Backend: "fake", Count: 1, Kept: keptOnlyCopy, Rest: "devvm rm"},
|
||||
{What: "history", Count: 1, Size: 1024, Sized: true, Kept: keptOnlyCopy, Rest: "gc --history", Retain: "30d", RetainFrees: 1024},
|
||||
},
|
||||
Total: 2048,
|
||||
@@ -168,7 +168,7 @@ func TestWriteSpace(t *testing.T) {
|
||||
got, colored := tables(t, func(tab *ui.Table) error { return writeSpace(tab, r) })
|
||||
want := "WHAT BACKEND COUNT SIZE KEPT GC FREED BY RETAIN\n" +
|
||||
"images lima 2 2.0K remade 1.0K gc --backend lima -\n" +
|
||||
"VMs smolvm 1 - only copy - devvm rm -\n" +
|
||||
"VMs fake 1 - only copy - devvm rm -\n" +
|
||||
"history - 1 1.0K only copy - gc --history 30d (1.0K)\n" +
|
||||
"total - - 2.0K - 1.0K - -\n" +
|
||||
"\n" +
|
||||
|
||||
@@ -54,13 +54,13 @@ func wantCodes(t *testing.T, colored string, painted ...string) {
|
||||
func TestWriteListColored(t *testing.T) {
|
||||
ls := []vm.Listed{
|
||||
{Name: "devvm-a", Status: string(backend.StatusRunning), Image: "base", Git: "on", Net: "on", Backend: "lima", Folder: "/a"},
|
||||
{Name: "devvm-bb", Status: string(backend.StatusStopped), Image: "docker", Tools: []string{"node", "claude"}, Git: "off", Net: "unenforced", Backend: "smolvm", Folder: "/b", Links: 2},
|
||||
{Name: "devvm-bb", Status: string(backend.StatusStopped), Image: "docker", Tools: []string{"node", "claude"}, Git: "off", Net: "unenforced", Backend: "fake", Folder: "/b", Links: 2},
|
||||
{Name: "devvm-c", Status: "Broken", Git: vm.ModeClone, Backend: "lima", Folder: "/c"},
|
||||
}
|
||||
plain, colored := tables(t, func(tab *ui.Table) error { return writeList(tab, ls) })
|
||||
want := "NAME STATUS IMAGE TOOLS GIT NET LINKS BACKEND FOLDER\n" +
|
||||
"devvm-a Running base - on on - lima /a\n" +
|
||||
"devvm-bb Stopped docker node,claude off unenforced 2 smolvm /b\n" +
|
||||
"devvm-bb Stopped docker node,claude off unenforced 2 fake /b\n" +
|
||||
"devvm-c Broken - - clone - - lima /c\n"
|
||||
if plain != want {
|
||||
t.Errorf("got\n%s\nwant\n%s", plain, want)
|
||||
|
||||
Loaded 100 of 162 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user