diff --git a/docs/content/docs/internals/lima.md b/docs/content/docs/internals/lima.md index 91a45244..cc8d3aa3 100644 --- a/docs/content/docs/internals/lima.md +++ b/docs/content/docs/internals/lima.md @@ -61,7 +61,7 @@ On macOS, devvm starts the VM's Lima process, its hostagent, under a macOS sandb On Linux, Lima starts QEMU through a wrapper that devvm writes (`~/.local/share/devvm/run/qemu/`) and that runs devvm. The wrapper adds QEMU's `restrict=on` to Lima's network, so no traffic goes in or out but Lima's own forwards. It also adds one address, `192.168.5.4:3128`, which QEMU connects to the VM's proxy. If Lima's QEMU arguments aren't the shape devvm expects, with one `-netdev user,id=net0,…` and no other network, the wrapper refuses to start QEMU (`qemu_refused`), so QEMU never runs unrestricted. DNS points at an address that nothing listens on, so lookups fail at once. -A process can't leave its sandbox, so devvm records the hostagent it started (`~/.local/share/devvm/run/.started`) and checks that the VM still runs on it ([the self-check](network.md#the-self-check)). A VM started another way, such as with `limactl start`, runs unconfined, and `devvm ls` shows it as `unenforced`. The VM's proxy follows the hostagent's pid file (`ha.pid` in the VM's Lima folder) and exits with it. +A process can't leave its sandbox, so devvm records the hostagent it started (`~/.local/share/devvm/run/.started`) and checks that the VM still runs on it ([the self-check](network.md#the-self-check)). A VM started another way, such as with `limactl start`, runs unconfined, and `devvm ls` shows it as `unenforced`. The VM's proxy follows the hostagent's pid file (`ha.pid` in the VM's Lima folder) and exits with it. devvm writes the record only once `limactl start` returns, while the hostagent runs on its own from early in the start, so an interrupt during the start stops the VM ([how long a proxy runs](network.md#how-long-a-proxy-runs)). Interrupted before the hostagent answers, the VM is one Lima reports as `Broken`, which `limactl stop` refuses, so devvm stops a broken VM with `limactl stop --force`. Builds are also confined, because they run code devvm didn't write. On macOS a build's Lima process runs under a profile that reaches either the internet but not the host's loopback, where other VMs' proxies and dev servers listen, or nothing at all. Behind a company proxy, a build with the internet also reaches one port of the host's loopback, its own proxy's ([a company proxy](design.md#a-company-proxy)). On Linux only a build with no network is confined. QEMU can't keep the internet while dropping the host's loopback, so other builds reach services on the host's `localhost`. Builds forward no ports. diff --git a/docs/content/docs/internals/network.md b/docs/content/docs/internals/network.md index 77a42e6c..4fc9b847 100644 --- a/docs/content/docs/internals/network.md +++ b/docs/content/docs/internals/network.md @@ -91,7 +91,7 @@ The proxy exits when the VM's Lima hostagent does, which it learns from the host A VM that starts again gets a new proxy on the same port. A running VM also gets a new proxy when its allowlist files 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. 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. -devvm counts a proxy as started only once the proxy says it's listening on the VM's port and is still running, because a program that took the port first would otherwise get the VM's traffic. If the proxy doesn't start, devvm stops and names the proxy's log (`proxy_start_failed`). When a stopped VM's port was taken by another program, devvm chooses a new free port. A running VM's backend holds the port it started with, so when a running VM's proxy is gone and another program took its port, devvm can't start the proxy again (`proxy_port_taken`). devvm then stops the VM (`net_proxy_down_stopped`), and it does the same when the proxy fails to start for any other reason, because a VM with network policy never runs on without its proxy. The next `devvm` starts both. +devvm counts a proxy as started only once the proxy says it's listening on the VM's port and is still running, because a program that took the port first would otherwise get the VM's traffic. If the proxy doesn't start, devvm stops and names the proxy's log (`proxy_start_failed`). When a stopped VM's port was taken by another program, devvm chooses a new free port. A running VM's backend holds the port it started with, so when a running VM's proxy is gone and another program took its port, devvm can't start the proxy again (`proxy_port_taken`). devvm then stops the VM (`net_proxy_down_stopped`), and it does the same when the proxy fails to start for any other reason, because a VM with network policy never runs on without its proxy. The next `devvm` starts both. An interrupt during the start of a VM with network policy stops the VM and its proxy too (`interrupted_start`, a cleanup that `Env.start` registers around the backend's `Start`), because a backend can leave the VM running while its start still waits for it: Lima's hostagent keeps running the VM after `limactl start` ends, and devvm records the confined start only once `limactl start` returns. Without the stop, the VM would run with no record of its confined start, so `devvm ls` would show it as `unenforced` and its next launch would offer to restart it. ## Policy files diff --git a/docs/content/docs/using/troubleshooting.md b/docs/content/docs/using/troubleshooting.md index 434bff0e..d541397f 100644 --- a/docs/content/docs/using/troubleshooting.md +++ b/docs/content/docs/using/troubleshooting.md @@ -98,6 +98,8 @@ devvm finds its folders from `HOME`, so it stops when `HOME` is empty or isn't a On the VM's next launch, devvm offers in a terminal to restart it confined, and if you decline, it warns and goes on. Without a terminal, devvm stops the VM instead, and the next `devvm` starts it confined ([the self-check](../internals/network.md#the-self-check)). +If you press Ctrl+C while devvm starts a VM with network policy, devvm stops the VM and its proxy before it exits, so the VM never runs on without the proxy, and the next `devvm` starts both again confined. + ## A request is blocked With network policy, a VM reaches only the hosts on its allowlist. To see what the proxy blocked, run `devvm network log --blocked` on this machine, or `devvm-why` in the VM. `devvm network log --blocked` also shows the `devvm network allow` command that allows each host, and the rule applies at once, to the next connection ([logs](../safety/network.md#logs)). diff --git a/internal/backend/lima/lima.go b/internal/backend/lima/lima.go index 229ecd24..ba4ce62c 100644 --- a/internal/backend/lima/lima.go +++ b/internal/backend/lima/lima.go @@ -317,23 +317,32 @@ func (l *Lima) CreateVM(ctx context.Context, image string, spec backend.VMSpec) return l.SetSize(ctx, vm, spec.Size) } -// Stop stops a VM; a stopped one is left as it is. +// Stop stops a VM; a stopped one is left as it is. One Lima reports as +// broken, such as a VM whose start was cut short before its hostagent +// answers, is stopped with --force, as limactl stop refuses it. func (l *Lima) Stop(ctx context.Context, vm string) error { in, err := l.inspect(ctx, vm) if err != nil { return err } - if backend.Status(in.Status) == backend.StatusStopped { - l.Forwards.Stop(vm) - return nil + status := backend.Status(in.Status) + if status != backend.StatusStopped { + var opts []string + if status == statusBroken { + opts = []string{"--force"} + } + err = l.stop(ctx, vm, opts...) } - err = l.stop(ctx, vm) l.Forwards.Stop(vm) return err } -func (l *Lima) stop(ctx context.Context, vm string) error { - if err := l.Runner.Run(ctx, msg.Stopping(vm), l.limactl(ctx, "stop", vm)); err != nil { +// statusBroken is how Lima reports a VM whose hostagent doesn't answer. +const statusBroken backend.Status = "Broken" + +func (l *Lima) stop(ctx context.Context, vm string, opts ...string) error { + args := slices.Concat([]string{"stop"}, opts, []string{vm}) + if err := l.Runner.Run(ctx, msg.Stopping(vm), l.limactl(ctx, args...)); err != nil { return backend.Logged(msg.StopFailed(vm)) } return nil diff --git a/internal/backend/lima/lima_test.go b/internal/backend/lima/lima_test.go index 1c6ac802..acae94bc 100644 --- a/internal/backend/lima/lima_test.go +++ b/internal/backend/lima/lima_test.go @@ -643,6 +643,27 @@ func TestExecAndShell(t *testing.T) { } } +// Against the limactl stub: a VM Lima reports as broken (its start cut +// short before its hostagent answers) is stopped with --force, which +// limactl stop alone refuses. +func TestStubStopBroken(t *testing.T) { + l, _, stubs := stubLima(t) + vm := "devvm-p-0123456789abcd" + stubs.Write(t, "instances", vm+" Broken\n") + if err := l.Stop(t.Context(), vm); err != nil { + t.Fatal(err) + } + var got []string + for _, c := range stubs.Calls(t) { + if c != "limactl list --json" { + got = append(got, c) + } + } + if want := []string{"limactl stop --force " + vm}; !slices.Equal(got, want) { + t.Errorf("calls %q, want %q", got, want) + } +} + // Against the limactl stub: VMs stop, start and go. func TestStubLifecycle(t *testing.T) { l, _, stubs := stubLima(t) diff --git a/internal/msg/messages_gen.go b/internal/msg/messages_gen.go index 823cd30d..564b70bb 100644 --- a/internal/msg/messages_gen.go +++ b/internal/msg/messages_gen.go @@ -1659,6 +1659,11 @@ func InterruptedImage(vm string) M { return M{id: "interrupted_image", vals: []val{{"vm", vm}}} } +// InterruptedStart is [interrupted_start]: "interrupted: stopping {{.vm}}, which hadn't finished starting with its network policy" +func InterruptedStart(vm string) M { + return M{id: "interrupted_start", vals: []val{{"vm", vm}}} +} + // InterruptedVM is [interrupted_vm]: "interrupted: deleting {{.vm}}, which wasn't ready yet" func InterruptedVM(vm string) M { return M{id: "interrupted_vm", vals: []val{{"vm", vm}}} @@ -3647,6 +3652,7 @@ var specs = map[string]spec{ "images_total": {fields: []string{"size"}}, "images_unused": {fields: []string{"size"}}, "interrupted_image": {fields: []string{"vm"}}, + "interrupted_start": {fields: []string{"vm"}}, "interrupted_vm": {fields: []string{"vm"}}, "json_shows_only": {fields: []string{"command"}}, "kept": {fields: []string{"vm"}}, diff --git a/internal/vm/env.go b/internal/vm/env.go index bf7bfd9c..f7d871d7 100644 --- a/internal/vm/env.go +++ b/internal/vm/env.go @@ -511,6 +511,9 @@ func (e *Env) start(ctx context.Context, b backend.Backend, st *state.VM, conf b // sshd. f := e.forwarding(b, st) conf.Free, conf.HostKey = f.Free, f.HostKey + if conf.Net == backend.NetProxy { + defer e.AddCleanup(undoStart(e, b, vm))() + } if err := b.Start(ctx, vm, conf); err != nil { if conf.Net == backend.NetProxy { e.Proxy.Stop(vm) @@ -527,6 +530,24 @@ func (e *Env) start(ctx context.Context, b backend.Backend, st *state.VM, conf b return conf, sshagent.RecordStart(st, mode, start) } +// undoStart is a start's cleanup for a VM with network policy: an +// interrupt can leave it running with its backend's start still waiting +// for it, so without the record of its confined start (Confined), and +// it stops the VM and its proxy. The next launch starts both again, +// confined. +func undoStart(e *Env, b backend.Backend, vm string) func(context.Context) { + return func(ctx context.Context) { + if !e.Interrupted() { + return + } + e.Info(msg.InterruptedStart(vm)) + if err := b.Stop(ctx, vm); err != nil && !errors.Is(err, backend.ErrNotFound) { + e.Warn(msg.StopFailed(vm)) + } + e.Proxy.Stop(vm) + } +} + // runningAgent is the SSH agent choice a running VM runs with: its // current start's (sshagent.Running). func runningAgent(ctx context.Context, b backend.Backend, st *state.VM) (string, error) { diff --git a/internal/vm/envstart_test.go b/internal/vm/envstart_test.go new file mode 100644 index 00000000..7f6e50b1 --- /dev/null +++ b/internal/vm/envstart_test.go @@ -0,0 +1,79 @@ +package vm + +import ( + "context" + "errors" + "path/filepath" + "slices" + "testing" + + "github.com/w3cj/devvm/internal/backend" + "github.com/w3cj/devvm/internal/msg" +) + +// A start of a VM with network policy registers a cleanup that, when the +// run is interrupted while its backend still waits for the VM, stops the +// VM and its proxy and says so. Not interrupted, it does nothing; a VM +// without network policy gets none. +func TestStartInterrupted(t *testing.T) { + for _, tc := range []struct { + name string + net, interrupted bool + cleanups int + stopped bool + }{ + {"interrupted", true, true, 1, true}, + {"not interrupted", true, false, 1, false}, + {"no network policy", false, true, 0, false}, + } { + t.Run(tc.name, func(t *testing.T) { + e, f, _ := upEnv(t, allNative()) + f.LifelineFile = filepath.Join(e.Dirs.Lima, "vm", "ha.pid") + f.ExecFunc = noDirect + st := existingVM(t, e, Options{Image: "base", NetworkPolicy: tc.net, NoNetworkPolicy: !tc.net}) + vm := st.Name() + if err := f.Stop(t.Context(), vm); err != nil { + t.Fatal(err) + } + var cleanups []func(context.Context) + e.AddCleanup = func(c func(context.Context)) func() { + cleanups = append(cleanups, c) + return func() {} + } + e.Interrupted = func() bool { return tc.interrupted } + var said []string + e.Info = func(m msg.M) { said = append(said, m.Names()) } + // The backend's start, cut short. + f.Errs = map[string]error{"Start": context.Canceled} + conf := backend.Confinement{Net: backend.NetDirect} + if tc.net { + conf.Net = backend.NetProxy + } + if _, err := e.start(t.Context(), f, st, conf); !errors.Is(err, context.Canceled) { + t.Fatalf("start: %v", err) + } + if len(cleanups) != tc.cleanups { + t.Fatalf("cleanups = %d, want %d", len(cleanups), tc.cleanups) + } + // As ui.Main runs them: while the start still waits. + before := len(f.Calls()) + for _, c := range slices.Backward(cleanups) { + c(t.Context()) + } + stopped := slices.Contains(f.Methods()[before:], "Stop") + if stopped != tc.stopped { + t.Errorf("stopped = %v, want %v", stopped, tc.stopped) + } + if _, runs := e.Proxy.PID(vm); runs { + t.Error("its proxy still runs") + } + wantSaid := []string(nil) + if tc.stopped { + wantSaid = []string{"interrupted_start vm=" + vm} + } + if !slices.Equal(said, wantSaid) { + t.Errorf("said %q, want %q", said, wantSaid) + } + }) + } +} diff --git a/locales/en.toml b/locales/en.toml index 804d8efb..b822ba1a 100644 --- a/locales/en.toml +++ b/locales/en.toml @@ -1604,6 +1604,9 @@ other = "creating {{.vm}} from {{.image}}" [interrupted_vm] other = "interrupted: deleting {{.vm}}, which wasn't ready yet" +[interrupted_start] +other = "interrupted: stopping {{.vm}}, which hadn't finished starting with its network policy" + [ssh_remote_hint] other = "The origin remote uses SSH, but {{.vm}} has no SSH agent, so git over SSH won't work in it. Run devvm ssh-agent on to forward yours." diff --git a/testdata/coverage/darwin.txt b/testdata/coverage/darwin.txt index b9c7e061..dd1b15be 100644 --- a/testdata/coverage/darwin.txt +++ b/testdata/coverage/darwin.txt @@ -4,12 +4,12 @@ cmd/devvm 100.0 internal/backend 95.4 internal/backend/backendtest 46.3 internal/backend/docker 80.8 -internal/backend/lima 87.6 +internal/backend/lima 87.7 internal/backend/registry 90.5 internal/backend/smolvm 73.9 internal/backend/vmssh 87.5 internal/build 87.3 -internal/cli 88.0 +internal/cli 88.1 internal/cli/docgen 85.1 internal/desktop 77.2 internal/devcontainer 96.8 @@ -17,7 +17,7 @@ internal/from 87.1 internal/gitprotect 91.4 internal/hostgit 100.0 internal/image 96.1 -internal/msg 66.1 +internal/msg 66.3 internal/msg/gen 92.5 internal/netpolicy 86.9 internal/paths 97.1 diff --git a/testdata/script/net_interrupted.txtar b/testdata/script/net_interrupted.txtar new file mode 100644 index 00000000..fdbcd24a --- /dev/null +++ b/testdata/script/net_interrupted.txtar @@ -0,0 +1,38 @@ +# A start with network policy that's interrupted while its backend waits +# for the VM (Lima's start, its hostagent running the VM) stops the VM and +# its proxy: it never runs on without the record of its confined start. +# What tools add saved stays, and devvm ls shows the policy on. + +project net +exec devvm --network-policy --no-git-protect base +vm_name NET net +exec devvm stop +exec sh -c ': > "$STUB_LOG" && echo "$NET" > "$STUB_DIR/start-hangs-running"' +! exec devvm tools add claude &u& +wait_file $STUB_DIR/hanging +kill -INT u +wait u +stdout '^==> interrupted_start vm=devvm-net-[0-9a-f]{14}$' +rm $STUB_DIR/start-hangs-running +stub_calls +stdout '^limactl start --tty=false devvm-net-[0-9a-f]{14}\n(.*\n)*limactl stop devvm-net-[0-9a-f]{14}$' +exec sh -c 'grep "^$NET " "$STUB_DIR/instances"' +stdout ' Stopped$' +exec sh -c 'pgrep -f "[_]proxy .* -vm $NET " || echo none' +stdout '^none$' +catg $VMS/devvm-net-* +stdout '^net=on$' +stdout '^image=claude$' +stdout '^tools=claude-\S+$' +exec devvm ls --json +stdout '"net": "on"' +! stdout unenforced + +# The next launch starts it confined, unasked. (Its hostagent here: the +# test's runner, which runs on.) +exec sh -c 'echo $PPID > "$STUB_DIR/hostagent"' +exec devvm +! stderr net_unenforced +exec devvm ls --json +stdout '"status": "Running"' +stdout '"net": "on"' diff --git a/testdata/stubs/limactl b/testdata/stubs/limactl index eb9f963d..985d43bc 100755 --- a/testdata/stubs/limactl +++ b/testdata/stubs/limactl @@ -17,7 +17,9 @@ # and shell its agent to $STUB_DIR/shell-agent; and # with $STUB_DIR/start-fails it fails, leaving the VM running (a degraded # start), and with $STUB_DIR/start-hangs it hangs (touching -# $STUB_DIR/hanging first). clone fails with $STUB_DIR/clone-fails, +# $STUB_DIR/hanging first); with $STUB_DIR/start-hangs-running, for a +# VM whose name contains its text, it hangs once the VM runs and has its +# ha.pid, as Lima's start waits for a VM's ssh while its hostagent runs it. clone fails with $STUB_DIR/clone-fails, # leaving its instance (a partial clone), and delete with # $STUB_DIR/delete-fails, after deleting it. shell fails with $STUB_DIR/shell-fails (or when its # arguments contain $STUB_DIR/shell-fails-on's text) and hangs with @@ -134,6 +136,10 @@ case ${1:-} in ha=$PPID [[ ! -f $STUB_DIR/hostagent ]] || ha=$(cat "$STUB_DIR/hostagent") echo "$ha" > "$LIMA_HOME/${names[0]}/ha.pid" + if [[ -e $STUB_DIR/start-hangs-running && ${names[0]} == *"$(cat "$STUB_DIR/start-hangs-running")"* ]]; then + : > "$STUB_DIR/hanging" + exec sleep 30 + fi echo "${SSH_AUTH_SOCK-unset}" > "$STUB_DIR/start-agent-${names[0]}" cfg="$LIMA_HOME/${names[0]}/ssh.config" [[ -f $cfg ]] || printf 'Host lima-%s\n IdentityFile "%s/_config/user"\n StrictHostKeyChecking no\n UserKnownHostsFile /dev/null\n NoHostAuthenticationForLocalhost yes\n PreferredAuthentications publickey\n BatchMode yes\n IdentitiesOnly yes\n User stub\n ControlMaster auto\n ControlPath "%s/ssh.sock"\n ControlPersist yes\n PermitLocalCommand yes\n LocalCommand touch /x/ran\n Hostname 127.0.0.1\n Port 60022\n' \ diff --git a/tests/e2e.sh b/tests/e2e.sh index 67e3abad..0338513b 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -2209,6 +2209,19 @@ else skip "... and the VM works: ssh, devvm's forwarder (on loopback alone), the proxy, the self-check" "Seatbelt is macOS's" skip "the next start puts Lima's ignore rules back" "Seatbelt is macOS's" fi +# Ctrl+C while Lima's start waits for the VM, its hostagent running it: devvm stops the VM and its +# proxy, so it never runs without the record of its confined start, and ls shows its policy on. +(cd "$n" && HOME=$nh "$D" stop /dev/null 2>&1) +(cd "$n" && exec env HOME="$nh" CLAUDE_CODE_OAUTH_TOKEN=sk-ant-oat01-e2efake DEVVM_MESSAGES=names "$D" "$work/int.log" 2>&1) & +ip=$! +for _ in $(seq 300); do [[ -S $DEVVM_LIMA_HOME/$vm/ha.sock ]] && break; sleep 0.2; done +kill -INT "$ip" 2>/dev/null +wait "$ip"; rc=$? +check "Ctrl+C during its start stops it and its proxy, and ls shows its policy on" bash -c " + [[ $rc -eq 130 ]] && grep -qx '==> interrupted_start vm=$vm' '$work/int.log' && [[ \$(status_of '$vm') == Stopped ]] && + ! pgrep -f -- '[_]proxy -listen .* -vm $vm ' >/dev/null && + '$D' ls | grep -Eq '^$vm +Stopped +[a-z+]*claude[a-z+]* +off +on +- +lima '" +(cd "$n" && printf 'exit\n' | HOME=$nh CLAUDE_CODE_OAUTH_TOKEN=sk-ant-oat01-e2efake "$D" >"$work/last.log" 2>&1) check "ls shows its policy on, and unenforced once started outside devvm" bash -c " '$D' ls | grep -Eq '^$vm +Running +[a-z+]*claude[a-z+]* +off +on +- +lima ' && limactl stop $vm >/dev/null 2>&1 && limactl start --tty=false $vm >/dev/null 2>&1 &&