fix(network): a confined VM's programs ask 127.0.0.1 directly, so names fail at once

With transparent mode off or stopped, a confined VM's only name server,
127.0.0.1 (Lima's DNS setting), has nothing listening. glibc asked it
through systemd-resolved's stub, which could keep retrying it over UDP
and TCP without answering, so a lookup such as getent's waited out its
timeout instead of failing at once (seen on a Linux host: e2e network's
checks of DNS with transparent mode stopped and off).

Each launch's setup now replaces /etc/resolv.conf, the stub's link, with
devvm's own file on a confined VM: nameserver 127.0.0.1 alone, the stub's
search line, timeout:1 attempts:2. glibc gets a refusal at once with
nothing listening, and dnsmasq's answer through transparent mode's
nftables rule when it runs, as musl on Alpine does. An open VM gets the
stub's link back. Only systemd guests that have the stub's file and whose
/etc/resolv.conf is its link or devvm's own are touched.

Root cause, as far as it could be pinned down: with resolved's stub in
the path, a lookup depended on resolved's retry loop over a server that
refuses everything (24 attempts, flipping UDP and TCP feature levels),
and on the linux host that loop sometimes never answered the stub
within getent's 3 s. It didn't reproduce on demand (a base run on the
linux host passed both checks, and bursts of 200 parallel lookups and
stops mid-lookup all failed in under 2 s), so the fix takes resolved out
of glibc's path rather than tuning it.

Going back to open restarts systemd-resolved: it reads a /etc/resolv.conf
that isn't its own link as global servers and search domains, so it had
taken 127.0.0.1 and "~." from devvm's file, and kept them once the link
was back, which left an open VM unable to resolve names (caught by e2e
network's open checks on the linux host and ubuntu).

Review folded in: no change of a foreign or dangling link when the stub's
file is missing; two attempts; Docker's user-defined networks in the docs.
Second review: devvm's file alone is enough to go back on an open VM (a
warning when the stub's file is missing); a failed write says so in one
line and the launch goes on; troubleshooting's "An open VM resolves no
names after a downgrade"; tests for resolved's own resolv.conf link, an
open VM without the stub, a non-systemd guest with devvm's file and a
failed write.

workerd under wrangler dev, checked by hand on fedora with transparent
mode off: its fetch fails at once (Temporary failure in name resolution),
so the "about 40 seconds for each lookup" sentence is gone from lima.md,
safety/network.md and troubleshooting.md, and testing.md's manual check
covers it.

testdata/coverage/darwin.txt: internal/sshagent's baseline rose with
mise run coverage (unrelated to this change).

- backend.Confinement.Resolver: the one owner of a confined guest's name
  server; Lima's start sets .dns from it, sync.go sends it to the setup
  as DEVVM_RESOLVER; sync.go's setupInputs as mise run fmt writes it.
- assets/guest/sync.sh: resolver_conf; its unit test runs the function
  (internal/vm/resolver_test.go). sync.sh runs at each launch and goes in
  no image, so no image key changes.
- CLI tests: DEVVM_RESOLVER on confined (transparent on and off) and open
  VMs. e2e network: the stopped-transparent check also checks the file.
- Docs: network.md's The VM's resolver, lima.md, design.md, tests.md;
  CHANGELOG Fixed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
w3cjandClaude Opus 5.5 committed 2026-11-15 22:04:32 -07:00
1 parent aeea3135b2
commit 63bb1ff9a8
17 files changed
+308 -25

No files matched your search

+1
View File
@@ -146,6 +146,7 @@ These changes are on `main` and go out in the next release.
- **A `NO_PROXY` entry with port 0 matches nothing:** the proxy read an entry such as `git.test:0` as `git.test` on every port, so it sent those hosts directly rather than through your company proxy, and it read `git.test:080` or `git.test:+80` as port 80, which Go's clients don't. An entry whose port no request has, or whose port isn't in plain decimal, now matches no host, as one past 65535 already didn't ([through a company proxy](https://next.devvm.dev/docs/internals/network/#through-a-company-proxy)).
- **No false lost pin on Linux hosts:** when git on this machine replaced `.git/config` just as devvm pinned it again, the pin could fail, and devvm warned that the file lost its pin and couldn't be pinned again, then that it was pinned again, at the VM's next check. A VM's start could fail the same way. devvm now pins the file the rename left, and warns only that it was pinned again ([how a Linux host locks .git](https://next.devvm.dev/docs/internals/git-protection/#on-linux-hosts)).
- **A stopped forwarder or link session takes its ssh with it:** devvm stopping a VM's port forwarder or link session, or a `kill` of either, could leave its ssh connection to the VM running on this machine, with its control socket in devvm's run folder. Each signal devvm sends now reaches what the process started too, either one stops its ssh before it exits, and `devvm gc --orphans` also deletes a forwarder's socket that nothing listens on ([how devvm starts them](https://next.devvm.dev/docs/internals/processes/#how-devvm-starts-them)).
- **A name fails at once with transparent mode off:** in a VM confined to its proxy, with transparent mode off or stopped, a lookup through the system's resolver, such as `getent`'s or curl's, could wait out its timeout rather than fail at once, seen on a Linux host, because systemd-resolved's stub kept retrying a name server where nothing listened. The VM's programs now ask that name server, its own `127.0.0.1`, directly, from each VM's next launch, so workerd under `wrangler dev`, which waited about 40 seconds for each lookup on a Linux host, fails at once too, and a VM on the open tier keeps systemd-resolved's stub ([the VM's resolver](https://next.devvm.dev/docs/internals/network/#the-vms-resolver)).
- **A Nix package is downloaded once:** when two requests for a package that wasn't in the shared Nix cache yet came close together, the second could download it again after the first had kept it, and the cache counted it twice against its cap. It now looks in the cache again before it downloads ([the shared Nix cache](https://next.devvm.dev/docs/internals/network/#the-shared-nix-cache)).
- **A refused launch leaves a running VM running:** when `config.toml`'s proxy named a user and no `proxy` secret was saved, `devvm` in the folder of a running VM refused, as it should, but also stopped the VM, and `devvm restart` stopped it before it refused. The same happened when your CAs folder couldn't be used, or the VM's CA or secret files couldn't be readied. On a launch or a `devvm network` change, devvm now checks the company proxy, your CAs, the VM's CA and its secret files before it stops the VM's proxy, and says it left the VM and its proxy running as they were. `devvm restart` checks the company proxy and your CAs before it stops the VM. A `devvm network` change between `internet`, `allowlist` and `none` on a running VM is refused before the VM's tier changes, so its tier never says one thing while its proxy enforces another. A VM whose proxy doesn't enforce the tier the VM has now, or whose proxy is stopped for new settings and then can't start again, is still stopped, because a VM never runs on without its proxy. A `devvm network` change now stops it in that case too, where it left the VM running without its proxy ([the proxy](https://next.devvm.dev/docs/internals/network/#the-proxy)).
- **A VM's logs are held to their caps:** root in a VM could write to its serial console, `/dev/hvc0`, without end, and Lima's console log for the VM grew until this machine's disk was full, and so could Lima's own logs for the VM until its next start. While a VM runs, its proxy now keeps the disk space each of those logs takes under 10 MiB, on a file system with holes such as APFS or ext4, moving its end to the same name with `.1` added, of up to 10 MiB more, with any password in it replaced. It also replaces the VM's proxy password as the logs grow, so a reboot inside the VM, which on Linux hosts writes it to the console's log again, can't leave it there. A VM that's running when you upgrade gets this once a devvm command starts its proxy again. The port forwarder's and the link session's logs now stay under 1 MiB while they run, not only from their next start, a link's warnings take turns with the session's other lines, the build proxy's log stays under 10 MiB as a VM's proxy's does, a run writes at most 128 MiB to its run log, and the run logs take at most 256 MiB together, though devvm never deletes the newest or one that a running devvm still writes ([Lima's hostagent](https://next.devvm.dev/docs/internals/processes/#limas-hostagent)).
+43 -1
View File
@@ -17,7 +17,9 @@
# DEVVM_LOCAL_PROXY (ADDRESS:PORT on the VM's loopback, where devvm-local-proxy
# listens; empty without a proxy), DEVVM_TRANSPARENT_ADDR and
# DEVVM_TRANSPARENT_HOST (transparent mode's stand-in address, empty for off, and the
# proxy's reserved target; transparent.sh), and DEVVM_PASTE_DIR (the folder devvm
# proxy's reserved target; transparent.sh), DEVVM_RESOLVER (on a confined VM, the
# one name server its programs ask, past systemd-resolved; empty for the system's
# own), and DEVVM_PASTE_DIR (the folder devvm
# paste writes to, config.toml's paste-dir: made here, the user's own, mode 700)
# transparent.sh devvm-transparent: transparent mode, for tools that ignore the proxy settings
# tools the VM's shared tool images, "FILE TOOL VERSION" lines; tools.sh mounts them
@@ -534,6 +536,46 @@ else
if $systemd; then sudo rm -f "$dropin"; else conf_block "$dropin"; fi
[[ ! -f ~/.ssh/config ]] || proxy_block ~/.ssh/config
fi
# A confined VM's resolver (DEVVM_RESOLVER, 127.0.0.1): glibc asks that one name server itself, as
# musl does on Alpine, not systemd-resolved's stub, so a lookup fails at once when nothing answers
# there (transparent mode off). The stub, with 127.0.0.1 as its only server, can keep retrying it
# over UDP and TCP without answering, so a lookup waited out its timeout. /etc/resolv.conf, the
# stub's link, becomes devvm's file, with the stub's search line and a second's timeout, tried
# twice (dnsmasq answers in the VM); on an open VM, devvm's file goes back to the stub's link, and
# systemd-resolved restarts, which forgets what it read from devvm's file. The file is written only
# on systemd guests that have the stub's file, whose /etc/resolv.conf is its link or devvm's file;
# going back needs devvm's file alone.
# resolver_conf FILE STUB: FILE (/etc/resolv.conf) as DEVVM_RESOLVER has it, STUB the stub's file.
resolver_conf() {
local f=$1 stub=$2 was first want tmp
local mark='# devvm: a confined VM asks its one name server directly (DEVVM_RESOLVER)'
was=$(readlink "$f" 2>/dev/null || true)
first=$(head -n 1 "$f" 2>/dev/null || true)
if [[ -z ${DEVVM_RESOLVER:-} ]] || ! $systemd; then
# devvm's file alone is enough to go back: it's only ever written in place of the stub's link.
[[ -z $was && $first == "$mark" ]] || return 0
sudo ln -sfn "$stub" "$f"
# systemd-resolved took devvm's file as its own servers and search domain ("." routes every
# name to 127.0.0.1), and keeps them once the file is its link again, until it restarts.
! $systemd || sudo systemctl try-restart systemd-resolved || true
[[ -e $stub ]] || echo "devvm: $f leads to $stub again, which systemd-resolved hasn't made, so names may not resolve in this VM" >&2
return 0
fi
[[ -e $stub ]] || return 0
[[ (-n $was && "$(readlink -f "$f")" == "$(readlink -f "$stub")") || (-z $was && $first == "$mark") ]] || return 0
want=$(printf '%s\nnameserver %s\n' "$mark" "$DEVVM_RESOLVER"
grep '^search ' "$stub" 2>/dev/null || true
echo 'options timeout:1 attempts:2')
[[ -n $was || "$(cat "$f")" != "$want" ]] || return 0
tmp=$(mktemp)
printf '%s\n' "$want" >"$tmp"
if ! { sudo install -m 644 "$tmp" "$f.devvm" && sudo mv -f "$f.devvm" "$f"; }; then
sudo rm -f "$f.devvm"
echo "devvm: couldn't write $f, so with transparent mode off a lookup in this VM may wait out its timeout" >&2
fi
rm -f "$tmp"
}
resolver_conf /etc/resolv.conf /run/systemd/resolve/stub-resolv.conf
# Transparent mode (transparent.sh, devvm-transparent) on a confined VM: every name resolves to the
# stand-in address, whose ports 80, 443 and those the rules name go to the proxy, which reads the host
# from the connection. The proxy URL, which holds the password, goes on stdin, never in arguments.
+1 -1
View File
@@ -366,6 +366,6 @@ What the end-to-end tests leave out, as it would change something of yours or ne
- **A VM's clock after this machine sleeps:** e2e can't sleep a Mac, and hosted CI can't either. With an open VM and an allowlist 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 the allowlist VM 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.
- **workerd under `wrangler dev`, without proxy settings:** e2e stands in for it with curl and a static Go client, because npm's download of workerd would make the run depend on it. In a node VM on the allowlist tier with `devvm network allow api.open-meteo.com`, make a Worker whose `fetch` handler returns `fetch("https://api.open-meteo.com/v1/forecast?latitude=0&longitude=0&current=temperature_2m")`, then run `npx wrangler dev` and `curl localhost:8787` in the VM. It answers with the forecast, and `devvm network log` has `api.open-meteo.com:443` `without proxy settings`. With the host taken out of the rules, the Worker's `fetch` fails with the proxy's `403` or a certificate error, as workerd may not trust the VM's CA, and the log has the block.
- **workerd under `wrangler dev`, without proxy settings:** e2e stands in for it with curl and a static Go client, because npm's download of workerd would make the run depend on it. In a node VM on the allowlist tier with `devvm network allow api.open-meteo.com`, make a Worker whose `fetch` handler returns `fetch("https://api.open-meteo.com/v1/forecast?latitude=0&longitude=0&current=temperature_2m")`, then run `npx wrangler dev` and `curl localhost:8787` in the VM. It answers with the forecast, and `devvm network log` has `api.open-meteo.com:443` `without proxy settings`. With the host taken out of the rules, the Worker's `fetch` fails with the proxy's `403` or a certificate error, as workerd may not trust the VM's CA, and the log has the block. With `devvm network transparent off` and a launch, the `fetch` fails at once, and `wrangler dev`'s output has `Temporary failure in name resolution`. Run it from a folder in the VM's home, such as a copy in `~/wk`, because workerd's SQLite fails with `SQLITE_IOERR_SHMMAP` in the project folder on a Linux host's 9p mount.
- **`--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`.
+1 -1
View File
@@ -183,7 +183,7 @@ The sections so far:
- `clone`: `--clone` with a throwaway repo, and host git and devvm run with a home of the section's own, so neither reads your `~/.ssh/config` or your git settings, and the Include line isn't offered. The VM has its own clone with every branch, even though the repo's `url.*.insteadOf` sends its URL elsewhere, only the shared tools are mounted, and its shell opens in the clone. The repo gets a `devvm` remote named after the VM, and nothing of `.git` is locked or watched. Without a terminal, `devvm rm --force` refuses while the clone has commits that weren't fetched and keeps the VM. Once `git fetch devvm` through devvm's ssh config has brought the VM's commit, `devvm rm` refuses for uncommitted changes in the clone, and then for those in a worktree in the clone, shown under its path, and `devvm rm --no-clone-check` deletes the VM after a warning, the worktree's change with it, and removes the remote, while the fetched work stays as a local branch. A git worktree's VM gets a clone of only its branch and that branch's upstream. On a VM that mounts its folder, `devvm clone on` without a terminal is refused, and `devvm clone` shows off. `devvm clone on --force` then makes it again with its own clone of every branch, only the shared tools mounted and `.git` unlocked, and it keeps its home and its ID. `devvm clone off --force` without a terminal refuses while the clone has commits that weren't fetched and keeps the clone, and once they're fetched, it mounts the folder again with `.git` protected, keeps the VM's home and ID, removes the remote and leaves the work as a local branch. Last, `devvm --clone --repos all` in a folder of repos gives one VM a clone of each repo at its path, with every branch, the folder's own file, and nothing mounted but the shared tools. `devvm clone fetch` brings both repos' work back and lists the branch with both repos, `devvm clone add` copies a third repo into the VM at its path, with a remote, `devvm rm` without a terminal refuses for the work in one repo that wasn't fetched, naming that repo, and `devvm rm --no-clone-check` deletes the VM and removes each repo's remote. A repo with a detached `HEAD`, an annotated tag, origin's branches and an older VM's remote gets a clone detached at the same commit, with the tag still annotated and origin's branches, and none of the VM remote's. The same repo's staged, unstaged and intent-to-add changes and a tracked file turned into a folder give the same `git status` in the VM, which has neither the untracked `.env` nor the folder, and devvm names the folder. Its clone has origin's URL, another remote's https URL without the user and token it has here, a branch as far ahead of its upstream as here, and the repo's `user.name` and `user.email`, which a commit there takes with no identity given, none of its credential settings, and its pre-commit hook, which runs there. `devvm clone fetch` brings back a commit only the VM's detached `HEAD` has, as `saved/devvm/HEAD`, and `devvm rm` names another, but not the uncommitted changes copied in, which the VM left as they came. A repo whose rebase, started with `--autostash`, stopped on a conflict, after a reset, with a stash of a plain entry and a `--all` one, gets a clone in the same rebase, which `git rebase --continue` finishes there, bringing the autostash back; its stash is the repo's but for the `--all` entry, which devvm names, the commit only the reset's `ORIG_HEAD` reached isn't there, and `devvm rm` names a stash entry the VM made, not the one copied in. A `blob:none` clone of a small public repo, on the internet tier, gets a promisor clone whose git fetches a blob it lacks from the repo's origin. Work in the VM that names another blob neither side has doesn't come back, and `devvm clone fetch` says so with `clone_fetch_partial`, then brings it back once git in the VM has read the blob. Both checks are skipped when github.com can't be reached. A repo with a submodule that has one of its own, both initialised, gets clones of them in the VM, where `git submodule status --recursive` is as here; a VM commit in the submodule comes back into its repo here with `devvm clone fetch`, and `devvm rm` without a terminal names a commit in the nested one that wasn't fetched, and keeps the VM. A repo that uses Git LFS, made without `git-lfs` on this machine, has its LFS file's content in the VM, whose `git status` is clean, with git-lfs's filter in the clone's own config and not in the VM's system or global config; a file the VM's `git-lfs` adds comes back with `devvm clone fetch`, its object in the repo here, and an object in the VM that isn't what its pointer names stays out, named with `clone_lfs_kept`.
- `gc`: a VM from a folder named `img-keep`, which is named like an image, and a fixture layer edited after its build: `devvm gc` deletes the stale image and its record and an old tool image no VM lists (once there's a tools lock), and keeps base and the VM.
- `tools`: first, the shared tools resolve to upstream's newest versions, with devvm's pinned mise (downloaded once), each download with its checksum. This section is the only one that uses the newest versions, and no other step checks for them (`DEVVM_NO_TOOL_CHECK`). At the section's end, e2e puts the pinned lock back. 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. Last, a .NET project's VM on the allowlist tier, chosen by its solution file: the shared SDK at the locked version from the share, a console project that restores a package from NuGet, builds and runs, `dotnet tool install -g` into `~/.dotnet/tools` with the tool run from a non-login shell, every toolchain's environment and `PATH` folders in a login shell and a non-login one, a workload installed into `~/.dotnet`, nothing of it blocked, and a `global.json`'s own SDK installed into the VM.
- `network`: a VM with Claude Code, Codex, opencode and pi and `--network allowlist`, a fake token in devvm's environment and a fake `~/.claude.json` and Codex login in a home of its own, which `devvm agent import` copies into the sandbox's agent store, only yours to read. 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; with transparent mode stopped, direct connections fail, even as root, to an address and to other ports, TCP to a public server's port 53 included, and with it running a public DNS server and Lima's DNS addresses answer only with the stand-in address, TTL 0, or nothing; 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; with transparent mode stopped, DNS fails at once and Lima's DNS addresses answer nothing. Transparent mode runs: its service, the stand-in address on `lo` and dnsmasq and socat on that address alone; names with a dot resolve to it, a name without a dot to nothing, IPv6 has none at once, and `/etc/hosts`' names keep theirs; curl without proxy settings and a static Go client with its own resolver reach github.com with its own certificate, logged `without proxy settings`; a blocked host gets the `403` over the VM's CA; port 5432 of a name is refused at once and `devvm-why` names it, while an IPv6 connection on loopback that works isn't listed as refused; a port a rule names, on a TLS server on this machine, is redirected while the rule is there and refused at once after `devvm network rm`; servers of the VM's own bind `0.0.0.0:443` and `:80`; the service comes back when it's killed or its table flushed; `devvm network transparent off` takes it out at the next launch and `on` puts it back. In a VM of the docker layer, containers without proxy settings reach github.com on the default bridge and on a network of their own, a blocked host is logged, no other port of the stand-in address answers them, a container's published 5432 isn't reached through the stand-in address from the VM or another container while its published 443 keeps the VM's connections off it, and an `--internal` network reaches nothing. The host's loopback services are out of reach, directly or through the proxy. Behind the run's company proxy on this machine's loopback, named in the shell's `HTTPS_PROXY`, the VM's proxy sends an allowed host there by name and refuses a blocked one before it gets there. Then `config.toml`'s `[proxy]` names the same company proxy with its user alone, and the shell sets no proxy: the launch is refused until `devvm secret set proxy --stdin` saves the password, and once it's saved, the VM's proxy config names the secret and holds no password, and the company proxy, which refuses any request without that password, carries GitHub. After each launch the password is in no process's arguments, no log and nowhere in the guest, and after the `config.toml` launch not in the VM's proxy config either, and the launch after, with neither setting, goes directly. The section's leak scan, run once its secrets are used and again at its end, looks for each company proxy's password as it is, as a URL's `user:password`, as Basic's base64 and as the whole `Proxy-Authorization` value, in devvm's logs, the VMs' proxies' logs and Lima's, and before it starts, the section deletes any of its secrets that a killed run left behind. The proxy refuses requests without the VM's password; the token is nowhere in the VM, which has its own CA and the next one, 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; a second allowlist VM has CAs of its own, each VM trusts only its own and has no key, each proxy serves and presents only its own VM's CAs, and `devvm rm` deletes one VM's CAs and leaves the other's; the home folder's and the store's login files are unchanged. `devvm agent save` saves the VM's changed `~/.claude.json` with the store's MCP header in place of its placeholder, and once the VM changes that server's URL it leaves the file out, so the store keeps the server as it was. `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), read from a file so it's in no process's arguments, and `devvm secret` lists it saved, while asking `devvm secret` for a `get` subcommand is refused without printing it; `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 Line truncated
- `network`: a VM with Claude Code, Codex, opencode and pi and `--network allowlist`, a fake token in devvm's environment and a fake `~/.claude.json` and Codex login in a home of its own, which `devvm agent import` copies into the sandbox's agent store, only yours to read. 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; with transparent mode stopped, direct connections fail, even as root, to an address and to other ports, TCP to a public server's port 53 included, and with it running a public DNS server and Lima's DNS addresses answer only with the stand-in address, TTL 0, or nothing; 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; with transparent mode stopped, DNS fails at once, `/etc/resolv.conf` names `127.0.0.1` alone, and Lima's DNS addresses answer nothing. Transparent mode runs: its service, the stand-in address on `lo` and dnsmasq and socat on that address alone; names with a dot resolve to it, a name without a dot to nothing, IPv6 has none at once, and `/etc/hosts`' names keep theirs; curl without proxy settings and a static Go client with its own resolver reach github.com with its own certificate, logged `without proxy settings`; a blocked host gets the `403` over the VM's CA; port 5432 of a name is refused at once and `devvm-why` names it, while an IPv6 connection on loopback that works isn't listed as refused; a port a rule names, on a TLS server on this machine, is redirected while the rule is there and refused at once after `devvm network rm`; servers of the VM's own bind `0.0.0.0:443` and `:80`; the service comes back when it's killed or its table flushed; `devvm network transparent off` takes it out at the next launch and `on` puts it back. In a VM of the docker layer, containers without proxy settings reach github.com on the default bridge and on a network of their own, a blocked host is logged, no other port of the stand-in address answers them, a container's published 5432 isn't reached through the stand-in address from the VM or another container while its published 443 keeps the VM's connections off it, and an `--internal` network reaches nothing. The host's loopback services are out of reach, directly or through the proxy. Behind the run's company proxy on this machine's loopback, named in the shell's `HTTPS_PROXY`, the VM's proxy sends an allowed host there by name and refuses a blocked one before it gets there. Then `config.toml`'s `[proxy]` names the same company proxy with its user alone, and the shell sets no proxy: the launch is refused until `devvm secret set proxy --stdin` saves the password, and once it's saved, the VM's proxy config names the secret and holds no password, and the company proxy, which refuses any request without that password, carries GitHub. After each launch the password is in no process's arguments, no log and nowhere in the guest, and after the `config.toml` launch not in the VM's proxy config either, and the launch after, with neither setting, goes directly. The section's leak scan, run once its secrets are used and again at its end, looks for each company proxy's password as it is, as a URL's `user:password`, as Basic's base64 and as the whole `Proxy-Authorization` value, in devvm's logs, the VMs' proxies' logs and Lima's, and before it starts, the section deletes any of its secrets that a killed run left behind. The proxy refuses requests without the VM's password; the token is nowhere in the VM, which has its own CA and the next one, 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; a second allowlist VM has CAs of its own, each VM trusts only its own and has no key, each proxy serves and presents only its own VM's CAs, and `devvm rm` deletes one VM's CAs and leaves the other's; the home folder's and the store's login files are unchanged. `devvm agent save` saves the VM's changed `~/.claude.json` with the store's MCP header in place of its placeholder, and once the VM changes that server's URL it leaves the file out, so the store keeps the server as it was. `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), read from a file so it's in no process's arguments, and `devvm secret` lists it saved, while asking `devvm secret` for a `get` subcommand is refused without printing it; `secret use github` binds it to the running proxy at once, and on the next launch the VM has its own placeholdLine truncated
- `desktop`: a VM of base has none of the desktop's programs, and devvm desktop refuses it, naming the layer. `--layers desktop` makes a VM of the desktop image, and devvm desktop serves its desktop on this machine's `127.0.0.1` alone, keeping its port and its password from one run to the next. A viewer with a wrong password is refused, and one with the password gets the VM's desktop. The VM's server listens on its user's own socket and on no TCP port, with the clipboard off, and the password is in no file of the VM's, in no run log and in no host process's arguments while devvm desktop starts. With network policy, the VM still reaches only its proxy and not the desktop's port on this machine, the desktop's browsers use the VM's local proxy without a password, a blocked host still gets a `403`, and the local proxy isn't forwarded to this machine. When root in the VM runs a server of its own without a password, a viewer with a wrong password is still refused and one with the password gets in, and the refused viewer never reaches the VM, nor does the viewer's clipboard, only its key event. Ctrl+C ends devvm desktop and closes its port, and `devvm desktop --clipboard` starts the server again on the same port with the clipboard on, which a viewer with the password gets.
- `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`) on the allowlist tier: 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 open` and `devvm restart`, no drop-in and no proxy for the daemon.
- `from`: run with a `docker` that isn't running, so nothing comes from Docker. Its container images go by their pinned digests, as `node:24@sha256:…`, so devvm looks them up nowhere, except the company proxy's `alpine:3.21`, which keeps its tag so that devvm's registry lookup is checked too. 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 pinned digest, its node, python and claude at the locked versions, GNU `tar` as its commands find it, its tool images built in a clone of devvm's own Ubuntu base when the run builds them, 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, then, after `devvm network allowlist` and `devvm restart`, transparent mode's checks as the network section has them, and with its service stopped, Lima's DNS and a public server answering nothing; a VM from `alpine:3` with node and dotnet, which its `package.json` and `global.json` call for, on the docker, nix and desktop layers runs node and pnpm from musl tool images, and dotnet's musl SDK with ICU, which makes and runs a console project, built in its own base and keyed and recorded by its digest, the docker layer's Docker on OpenRC, the desktop layer's programs from Alpine's packages, 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 allowlist` and `devvm restart` transparent mode's checks on OpenRC and musl, as for Debian 12, and a download only its daemon makes from a host that isn't allowed refused with the proxy's `403`, and with GNU `tar` as its commands find it, `devvm history import` puts an export into it, while an export with a path outside the agents' history imports nothing there, and on a Linux host, given Lima's `mmap` with no mode chosen, `devvm mount-cache none` gives it `none` at its next start, through the restart that a remount Alpine refuses gets, which devvm's portable check of the folder confirms; base builds from `ubuntu:26.04`; and the build VM and its temporary folders are gone.
+1 -1
View File
@@ -109,7 +109,7 @@ These settings guard against the host's ssh asking for a forward that devvm's en
- On a running VM, `devvm ports` changes the forwarder's ports at once. 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 VM's boot ID is the same throughout, so it never restarted.
- `devvm stop` stops the forwarder, `limactl stop` outside devvm ends it (on macOS), and `rm` stops it and deletes its files.
- On macOS, a confined VM 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.
- On a confined tier, with transparent mode stopped, DNS fails at once, and Lima's network's DNS address and the host's address on it give no answer for a name, with transparent mode running too.
- On a confined tier, with transparent mode stopped, DNS fails at once, because the guest's programs ask `127.0.0.1` alone, and Lima's network's DNS address and the host's address on it give no answer for a name, with transparent mode running too.
## devcontainer.json
+1 -1
View File
@@ -61,7 +61,7 @@ On macOS, devvm starts the VM's Lima process, its hostagent, under a macOS sandb
- The profile lets the process connect to the VM's ssh port and its proxy on the host's loopback, to the unix sockets in the VM's Lima folder (ssh's control socket and the VM's network), and to the socket of the ssh agent the VM forwards, which is its proxy's relay of your agent or devvm's own ([the SSH agents](processes.md#the-ssh-agents)). It connects nowhere else, so other sockets on the host, such as Docker's, stay out of the hostagent's reach. The profile limits only the network, so a compromised hostagent can still write your files, and through them run code as you.
- The profile lets the process listen only on the VM's ssh port, over TCP, and on unix sockets in the VM's Lima folder, so it can't open a port of the VM's on the host even if Lima ignored its rules ([ports](#ports)).
- Names resolve in the proxy, so Lima's own DNS server for the VM is off, and the guest's DNS points at `127.0.0.1`, which only [transparent mode](network.md#tools-that-skip-the-proxy) answers, inside the VM, with no upstream. Without it, nothing listens there, and a lookup through the system's resolver, as `getent` and curl make one, fails at once on macOS and on a Linux host alike. On a Linux host, where the VM lists only `127.0.0.1` as its DNS server, a few tools that resolve names their own way, such as workerd under `wrangler dev`, wait about 40 seconds for each lookup before they fail. The guest reaches the proxy at `192.168.5.2`, which is the host as Lima's network sees it.
- Names resolve in the proxy, so Lima's own DNS server for the VM is off, and the guest's DNS points at `127.0.0.1`, which only [transparent mode](network.md#tools-that-skip-the-proxy) answers, inside the VM, with no upstream. Without it, nothing listens there, and a lookup through the system's resolver, as `getent` and curl make one, which asks `127.0.0.1` itself ([the VM's resolver](network.md#the-vms-resolver)), fails at once on macOS and on a Linux host alike. The guest reaches the proxy at `192.168.5.2`, which is the host as Lima's network sees it.
On Linux, Lima starts every VM's QEMU through a wrapper that devvm writes (`~/.local/share/devvm/run/qemu/`) and that runs devvm. It runs QEMU in a namespace that makes `.git`'s hooks and config read-only, for a VM whose [.git protection](git-protection.md#on-linux-hosts) is on. For a confined VM, 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 through a process for each connection, at most 256 at once ([the QEMU wrapper](processes.md#the-qemu-wrapper-and-its-keeper)). 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 `127.0.0.1` in the guest, which only transparent mode answers, and without it lookups fail at once.
+7 -1
View File
@@ -212,7 +212,7 @@ Each placeholder ends in a random value of the VM's own, its salt, which isn't i
On a confined VM, transparent mode sends a tool that ignores the proxy settings to the VM's proxy by the names it looks up ([what it covers](../safety/network.md#tools-that-ignore-the-proxy)). Nothing new runs or listens on the host, and the backends don't change: the VM reaches its proxy over the path its proxy settings use, and the proxy judges each connection as it judges `CONNECT host:port`. Every piece in the VM is a program that devvm configures, dnsmasq, nftables and socat, which base installs, and one script, `devvm-transparent`, which each launch sends. A tool that looks up `api.example.com` and connects to it goes this way:
1. Its lookup reaches dnsmasq in the VM. glibc asks systemd-resolved, which asks `127.0.0.1:53`, where Lima's DNS setting for a confined VM points, and musl on Alpine asks `127.0.0.1:53` itself. An nftables rule sends `127.0.0.1:53` to dnsmasq, which listens on the stand-in address, `198.18.0.1`, alone. That rule takes every connection to `127.0.0.1:53` in the VM, so a DNS server of the user's own there, or a forward of port 53 to it, gets nothing.
1. Its lookup reaches dnsmasq in the VM. glibc and musl both ask `127.0.0.1:53` themselves, which is where Lima's DNS setting for a confined VM points ([the VM's resolver](#the-vms-resolver)). An nftables rule sends `127.0.0.1:53` to dnsmasq, which listens on the stand-in address, `198.18.0.1`, alone. That rule takes every connection to `127.0.0.1:53` in the VM, so a DNS server of the user's own there, or a forward of port 53 to it, gets nothing.
2. dnsmasq answers the A query with `198.18.0.1`, with a time to live of 0, and every other type, AAAA and HTTPS included, with an empty answer, never `REFUSED`, which musl waits 5 seconds on. It has no upstream server, so no query leaves the VM, and it reads `/etc/hosts` first, so `localhost`, the VM's hostname, `host.lima.internal` and the [links](ports.md#links-between-vms)' names keep their own addresses. Names under `devvm.internal` that aren't a link's don't exist, and neither does a name without a dot, nor a name under the search domains that the VM's resolver appends to one, which Lima takes from this machine's network and dnsmasq reads from `/etc/resolv.conf` as it starts. So a single-label name that isn't in `/etc/hosts` doesn't resolve, rather than turning into a name of this machine's network. dnsmasq can't tell a name the resolver made that way from one a tool names whole, so every name under those domains gets no answer, such as `git.corp.example.com` under `corp.example.com`.
3. The tool connects to `198.18.0.1:443`. The address is on the VM's loopback interface, so the connection stays in the VM, and an nftables rule sends it to a socat listener on `198.18.0.1:61443`. Nothing binds port 443 or 80 itself, so your own servers keep them.
4. socat opens an ordinary `CONNECT transparent.devvm.proxy:443` to the VM's proxy, with the VM's password, which it reads from a file, never from its arguments. Each port has a listener of its own, so the port reaches the proxy in the target, and nothing the VM sends can change it.
@@ -229,6 +229,12 @@ A blocked TLS host gets a TLS handshake with a certificate for its SNI name from
**What doesn't change.** The host's confinement is the boundary: root in the VM can change or stop all of this, and then names stop resolving, or a query to Lima's DNS goes nowhere, as for a VM without transparent mode. The [self-check](#the-self-check)'s direct connection is to an address on port 443, so transparent mode never answers it. The VM's names never reach the host's resolver for a blocked host, because the proxy asks the policy before it resolves anything. [Design notes](design.md#transparent-mode) has the threat check.
### The VM's resolver
On a confined VM, Lima's DNS setting gives the guest one name server, its own `127.0.0.1`, and each launch's setup makes the system's resolver ask it directly. systemd-resolved's stub, `127.0.0.53`, would ask `127.0.0.1` in turn, and when nothing listens there, because transparent mode is off or stopped, the stub can keep retrying it over UDP and TCP without answering, so a lookup through glibc waits out its own timeout instead of failing. So the setup replaces `/etc/resolv.conf`, which on Ubuntu is a link to the stub's file, with a file of its own that names `127.0.0.1` alone, with the stub's search line and a timeout of one second, tried twice, which is plenty because dnsmasq answers in the VM itself. glibc then gets a refusal at once when nothing listens, and dnsmasq's answer through the nftables rule when transparent mode runs, as musl on Alpine does.
systemd-resolved still runs, so `resolvectl` and the programs that ask it over D-Bus still go through it. Docker reads `/etc/resolv.conf` and finds only a loopback server there, so on its default bridge it gives containers its fallback servers, and on a network of their own, such as Compose's, its embedded DNS server asks `127.0.0.1` from the VM's side. The nftables table sends both to dnsmasq. The setup writes its file only on a guest with systemd that has the stub's file and whose `/etc/resolv.conf` is the stub's link or the setup's own file, so a file or link of your own stays, and it copies the search line again at each launch. When it can't write the file, it says so in one line and the launch goes on. systemd-resolved reads a file that isn't its own link as servers and search domains of its own, so while the VM is confined it takes `127.0.0.1` from the setup's file, and a search line of `.` sends every name there. It keeps them after the file is a link again, until it restarts. So on an open VM, the setup puts the stub's link back and restarts systemd-resolved, which then asks Lima's DNS. Going back needs only the setup's own file, which it writes nowhere else, and when the stub's file is missing afterwards, the setup says that names may not resolve.
## The shared Nix cache
VMs with the [nix layer](images.md#the-nix-layer) share their downloads from Nix's binary cache, so each package comes from cache.nixos.org once per machine instead of once per VM. Each VM keeps its own Nix store and daemon, and only the host writes the cache, so no VM can change what another VM gets. The [design note](design.md#the-shared-nix-cache) says why it's a cache that the host fills rather than a shared store.
+1 -1
View File
@@ -597,7 +597,7 @@ $ devvm network transparent off
==> devvm turns transparent mode off for devvm-web-0c3c7077e29f06 at its next launch, and it applies while the VM is on a confined tier.
```
With transparent mode off, names don't resolve in a confined VM at all, so a tool that skips the proxy fails with a DNS error. Most tools, such as curl, get that error at once, on macOS and on a Linux host alike. On a Linux host, a few, such as workerd under `wrangler dev`, can wait about 40 seconds for each lookup before they fail. On the open tier there's no transparent mode, and the VM resolves names with Lima's DNS. A VM made from an image built before devvm had transparent mode lacks the programs it runs, so each launch says so, and `devvm update` makes the VM again from a newer image.
With transparent mode off, names don't resolve in a confined VM at all, so a tool that skips the proxy fails with a DNS error. Tools such as curl and workerd under `wrangler dev` get that error at once, on macOS and on a Linux host alike. On the open tier there's no transparent mode, and the VM resolves names with Lima's DNS. A VM made from an image built before devvm had transparent mode lacks the programs it runs, so each launch says so, and `devvm update` makes the VM again from a newer image.
`devvm network transparent --json` prints the same as JSON, with `on` and `from`, which is `vm`, `config` or `default`, and `devvm network --json` has it too, as `transparent`:
+10 -1
View File
@@ -175,10 +175,19 @@ On a confined tier, devvm's [transparent mode](../safety/network.md#tools-that-i
- **A connection refused on another port,** such as `ECONNREFUSED` or `Connection refused` for `db.example.com:5432`. `devvm-why` lists the port under the connections the VM refused lately. Give the tool the proxy's address in `$HTTPS_PROXY` or its own setting, or, for HTTPS or HTTP on that port, allow the host with that port, such as `devvm network allow db.example.com:8443`, which redirects the port within 10 seconds.
- **A protocol that names no host,** such as a database's or SSH, which the proxy refuses and logs as a refused block of `transparent.devvm.proxy`. SSH in the VM goes through the proxy already, and a database client needs a proxy setting of its own.
- **A DNS error,** such as `no such host`, `Temporary failure in name resolution`, `ENOTFOUND` or `EAI_AGAIN`, which means transparent mode is off for the VM (`devvm network transparent`), or the VM comes from an image that predates it, which each launch says, and `devvm update` makes it again from a newer image. Most tools get the error at once. On a Linux host, a few, such as workerd under `wrangler dev`, wait about 40 seconds for each lookup first, so a tool that seems to hang at its start may be waiting for one.
- **A DNS error,** such as `no such host`, `Temporary failure in name resolution`, `ENOTFOUND` or `EAI_AGAIN`, which means transparent mode is off for the VM (`devvm network transparent`), or the VM comes from an image that predates it, which each launch says, and `devvm update` makes it again from a newer image. The tool gets the error at once.
Some tools read the proxy variables only when a setting of their own turns them on, or never. Turn on the tool's own proxy setting, so that it uses the environment, or give it the address in `$HTTPS_PROXY`. Hugo's `resources.GetRemote`, for example, uses the proxy only when `security.http.proxyFromEnvironment` is `true` in the site's config ([inside the VM](../safety/network.md#inside-the-vm)).
## An open VM resolves no names after a downgrade
A confined VM's programs ask the VM's own name server directly, through an `/etc/resolv.conf` that devvm writes, and devvm puts systemd-resolved's back when the VM runs open ([the VM's resolver](../internals/network.md#the-vms-resolver)). An older devvm doesn't know that file, so after a downgrade, a VM that was confined and now runs open can keep it and resolve no names. When the VM's `/etc/resolv.conf` starts with `# devvm:`, launch it with a current devvm, or put systemd-resolved's file back yourself:
```sh
head -1 /etc/resolv.conf # in the VM: "# devvm: ..." means devvm's file
sudo ln -sfn /run/systemd/resolve/stub-resolv.conf /etc/resolv.conf && sudo systemctl restart systemd-resolved
```
## A server's port is taken in a confined VM
In a confined VM, transparent mode's programs listen on the stand-in address `198.18.0.1`, on port 53 and on ports 61080 and 61443 and 61100 to 61131, so a server of yours that binds one of those ports on every address, such as `0.0.0.0:61443`, fails with `EADDRINUSE`. Ports 80 and 443 stay free for your own servers. A DNS server of yours on `127.0.0.1:53` binds, but gets no lookups, from the VM or through a forward of port 53, because transparent mode sends them to its own names. Move the server to another port, or turn transparent mode off for the VM with `devvm network transparent off`, which applies at its next launch ([tools that ignore the proxy](../safety/network.md#tools-that-ignore-the-proxy)).
+16
View File
@@ -601,6 +601,22 @@ func (c Confinement) GuestProxy() bool {
return c.Net == NetProxy || c.Net == NetDirect && c.ProxyPort != 0
}
// confinedResolver is a NetProxy guest's one name server: its own
// loopback, where only transparent mode answers (assets/guest/transparent.sh
// sends 127.0.0.1:53 to its dnsmasq), so nothing else does.
const confinedResolver = "127.0.0.1"
// Resolver is the one name server the guest's DNS settings name, which
// its programs ask directly (assets/guest/sync.sh), or "" when the
// backend's own network gives its DNS: NetProxy's names resolve in the
// proxy.
func (c Confinement) Resolver() string {
if c.Net == NetProxy {
return confinedResolver
}
return ""
}
// Status is a VM's state as its backend reports it.
type Status string
+20
View File
@@ -7,6 +7,26 @@ import (
"github.com/devvmhq/devvm/internal/msg"
)
// Only a confined VM's guest has its own loopback as its one name server;
// an open VM, with or without devvm's proxy, and a build keep their
// network's own.
func TestResolver(t *testing.T) {
for _, tc := range []struct {
c Confinement
want string
}{
{Confinement{Net: NetProxy, ProxyPort: 3128}, "127.0.0.1"},
{Confinement{Net: NetDirect}, ""},
{Confinement{Net: NetDirect, ProxyPort: 3128}, ""},
{Confinement{Net: NetInternet}, ""},
{Confinement{Net: NetNone}, ""},
} {
if got := tc.c.Resolver(); got != tc.want {
t.Errorf("%+v: Resolver() = %q, want %q", tc.c.Net, got, tc.want)
}
}
}
// A start refuses only a disk smaller than the VM's: zero is the VM's
// own, and the rest changes.
func TestValidate(t *testing.T) {
+8 -6
View File
@@ -327,7 +327,6 @@ func (l *machines) startSets(cfg *config, c backend.Confinement, sshPort int) (o
if sshPort != 0 && cfg.SSH.LocalPort != sshPort {
sets = append(sets, ".ssh.localPort="+strconv.Itoa(sshPort))
}
proxy := c.Net == backend.NetProxy
if env := l.guestEnv(c); !maps.Equal(env, cfg.Env) && (len(env) > 0 || len(cfg.Env) > 0) {
if len(env) == 0 {
sets = append(sets, "del(.env)")
@@ -353,9 +352,12 @@ func (l *machines) startSets(cfg *config, c backend.Confinement, sshPort int) (o
}
// Names resolve in the proxy. On Linux restrict=on drops Lima's DNS
// too, so lookups would time out; on macOS Lima's host resolver binds
// loopback ports, which the sandbox denies (seatbelt.go). A resolver
// nothing listens on fails at once.
noDNS := proxy
// loopback ports, which the sandbox denies (seatbelt.go). The guest's
// one name server is its own loopback (Confinement.Resolver), which
// its programs ask directly (guest/sync.sh), so with nothing listening
// there a lookup fails at once.
dns := c.Resolver()
noDNS := dns != ""
resolver := cfg.HostResolver.Enabled == nil || *cfg.HostResolver.Enabled
switch {
case noDNS && resolver:
@@ -364,8 +366,8 @@ func (l *machines) startSets(cfg *config, c backend.Confinement, sshPort int) (o
sets = append(sets, "del(.hostResolver)")
}
switch {
case noDNS && !slices.Equal(cfg.DNS, []string{"127.0.0.1"}):
sets = append(sets, `.dns=["127.0.0.1"]`)
case noDNS && !slices.Equal(cfg.DNS, []string{dns}):
sets = append(sets, ".dns="+yqJSON([]string{dns}))
case !noDNS && len(cfg.DNS) > 0:
sets = append(sets, "del(.dns)")
}
+173
View File
@@ -0,0 +1,173 @@
package vm
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
// The setup's /etc/resolv.conf, as sync.sh's resolver_conf writes it: a
// confined VM's programs ask its one name server directly, past
// systemd-resolved's stub, and keep the stub's search line; an open VM's
// file goes back to the stub's link. A file that is neither the stub's
// link nor devvm's own is left as it is, and so is a guest without
// systemd, but for devvm's own file.
func TestResolverConf(t *testing.T) {
if _, err := exec.LookPath("bash"); err != nil {
t.Skip("no bash")
}
dir := t.TempDir()
stub := filepath.Join(dir, "run", "systemd", "resolve", "stub-resolv.conf")
conf := filepath.Join(dir, "etc", "resolv.conf")
for _, d := range []string{filepath.Dir(stub), filepath.Dir(conf)} {
if err := os.MkdirAll(d, 0o755); err != nil { //nolint:gosec // the test's own folders
t.Fatal(err)
}
}
if err := os.WriteFile(stub, []byte("nameserver 127.0.0.53\noptions edns0 trust-ad\nsearch corp.example\n"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.Symlink("../run/systemd/resolve/stub-resolv.conf", conf); err != nil {
t.Fatal(err)
}
fn := "resolver_conf() {\n" + between(t, "guest/sync.sh", "resolver_conf() {", "}") + "\n}\n"
calls := filepath.Join(dir, "systemctl")
run := func(systemd, resolver string) string {
t.Helper()
script := "set -euo pipefail\nsudo() { \"$@\"; }\ncalls=$5\nsystemctl() { echo \"$*\" >>\"$calls\"; }\nsystemd=$1 DEVVM_RESOLVER=$2\n" +
fn + "resolver_conf \"$3\" \"$4\"\n"
cmd := exec.CommandContext(t.Context(), "bash", "-c", script, "bash", systemd, resolver, conf, stub, calls) //nolint:gosec // sync.sh's own function, on the test's files
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("resolver_conf: %v\n%s", err, out)
}
return string(out)
}
own := "# devvm: a confined VM asks its one name server directly (DEVVM_RESOLVER)\n" +
"nameserver 127.0.0.1\nsearch corp.example\noptions timeout:1 attempts:2\n"
check := func(step, want string, link bool) {
t.Helper()
fi, err := os.Lstat(conf)
if err != nil {
t.Fatal(err)
}
if got := fi.Mode()&os.ModeSymlink != 0; got != link {
t.Errorf("%s: a link is %v, want %v", step, got, link)
}
b, err := os.ReadFile(conf) //nolint:gosec // the test's own file
if err != nil {
t.Fatal(err)
}
if string(b) != want {
t.Errorf("%s: resolv.conf is %q, want %q", step, b, want)
}
}
stubText := "nameserver 127.0.0.53\noptions edns0 trust-ad\nsearch corp.example\n"
run("false", "127.0.0.1")
check("without systemd", stubText, true)
run("true", "127.0.0.1")
check("confined", own, false)
run("true", "127.0.0.1")
check("confined again", own, false)
run("true", "")
check("open", stubText, true)
// systemd-resolved restarts once, as the file goes back to its link,
// so it forgets the servers and search domain it read from devvm's.
run("true", "")
if b, _ := os.ReadFile(calls); string(b) != "try-restart systemd-resolved\n" { //nolint:gosec // the test's own file
t.Errorf("systemctl was run with %q, want one try-restart of systemd-resolved", b)
}
// A file of the user's own stays, on either tier.
if err := os.Remove(conf); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(conf, []byte("nameserver 10.0.0.53\n"), 0o600); err != nil {
t.Fatal(err)
}
run("true", "127.0.0.1")
check("the user's own, confined", "nameserver 10.0.0.53\n", false)
run("true", "")
check("the user's own, open", "nameserver 10.0.0.53\n", false)
// A link to systemd-resolved's other file, which lists its servers
// rather than the stub, stays as it is.
full := filepath.Join(filepath.Dir(stub), "resolv.conf")
if err := os.WriteFile(full, []byte("nameserver 127.0.0.1\n"), 0o600); err != nil {
t.Fatal(err)
}
relink(t, conf, full)
run("true", "127.0.0.1")
if to, _ := os.Readlink(conf); to != full {
t.Errorf("a link to resolved's own resolv.conf leads to %q, want %q", to, full)
}
// Without the stub's file (no systemd-resolved), a link elsewhere
// stays, even one that leads nowhere.
if err := os.Remove(stub); err != nil {
t.Fatal(err)
}
relink(t, conf, "/run/resolvconf/resolv.conf")
run("true", "127.0.0.1")
if to, err := os.Readlink(conf); err != nil || to != "/run/resolvconf/resolv.conf" {
t.Errorf("without the stub: resolv.conf leads to %q (%v), want the link it had", to, err)
}
// devvm's file alone is enough to go back, on an open VM without the
// stub's file, which says names may not resolve, and on a guest
// without systemd, which restarts nothing.
for _, tc := range []struct{ systemd, resolver string }{{"true", ""}, {"false", "127.0.0.1"}} {
if err := os.Remove(conf); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(conf, []byte(own), 0o600); err != nil {
t.Fatal(err)
}
if err := os.Remove(calls); err != nil && !os.IsNotExist(err) {
t.Fatal(err)
}
out := run(tc.systemd, tc.resolver)
if to, _ := os.Readlink(conf); to != stub {
t.Errorf("systemd=%s: devvm's file without the stub leads to %q, want %q", tc.systemd, to, stub)
}
if !strings.Contains(out, "systemd-resolved hasn't made") {
t.Errorf("systemd=%s: no warning that names may not resolve: %q", tc.systemd, out)
}
b, _ := os.ReadFile(calls) //nolint:gosec // the test's own file
if want := map[string]string{"true": "try-restart systemd-resolved\n", "false": ""}[tc.systemd]; string(b) != want {
t.Errorf("systemd=%s: systemctl was run with %q, want %q", tc.systemd, b, want)
}
}
// A write that fails leaves the link, takes its temporary file away,
// and says so, and the setup goes on.
if err := os.WriteFile(stub, []byte(stubText), 0o600); err != nil {
t.Fatal(err)
}
relink(t, conf, stub)
if err := os.Chmod(filepath.Dir(conf), 0o500); err != nil { //nolint:gosec // the test's own folder, made read-only
t.Fatal(err)
}
defer os.Chmod(filepath.Dir(conf), 0o700) //nolint:errcheck,gosec // TempDir's cleanup needs it writable again
out := run("true", "127.0.0.1")
if to, _ := os.Readlink(conf); to != stub || !strings.Contains(out, "couldn't write") {
t.Errorf("a failed write: resolv.conf leads to %q, said %q", to, out)
}
if _, err := os.Lstat(conf + ".devvm"); !os.IsNotExist(err) {
t.Errorf("a failed write left %s.devvm (%v)", conf, err)
}
}
// relink makes link a link to target, in place of whatever it was.
func relink(t *testing.T, link, target string) {
t.Helper()
if err := os.Remove(link); err != nil && !os.IsNotExist(err) {
t.Fatal(err)
}
if err := os.Symlink(target, link); err != nil {
t.Fatal(err)
}
}
+12 -5
View File
@@ -59,7 +59,10 @@ func (e syncer) sync(ctx context.Context, b backend.Backend, st *state.VM, slug
if err != nil {
return err
}
in := setupInputs{slug: slug, files: files, proxyURL: b.ProxyURL(conf), links: links, moved: moved.From, transparent: netpolicy.TransparentAddr(conf, tp)}
in := setupInputs{
slug: slug, files: files, proxyURL: b.ProxyURL(conf), links: links, moved: moved.From,
transparent: netpolicy.TransparentAddr(conf, tp), resolver: conf.Resolver(),
}
s, err := e.stage(ctx, st, in)
if err != nil {
return err
@@ -149,11 +152,12 @@ func reported(files []string, report []byte) []string {
// when the backend gives the guest none), its links, the path its folder moved
// from, "" when it didn't (its moved section), and the stand-in address its
// names lead to its proxy by, "" when its transparent mode is off
// (netpolicy.TransparentAddr).
// (netpolicy.TransparentAddr), and the one name server its programs ask
// directly, "" for its system's own (backend.Confinement.Resolver).
type setupInputs struct {
slug, proxyURL, moved, transparent string
files []string
links []GuestLink
slug, proxyURL, moved, transparent, resolver string
files []string
links []GuestLink
}
// GuestLink is one target a client VM reaches through its links: the
@@ -317,6 +321,9 @@ func (e syncer) stage(ctx context.Context, st *state.VM, in setupInputs) (*stage
// none for off, and the proxy's reserved target.
{"DEVVM_TRANSPARENT_ADDR", in.transparent},
{"DEVVM_TRANSPARENT_HOST", proxy.TransparentHost},
// The one name server the guest's programs ask, past
// systemd-resolved, on a confined VM; none for the system's own.
{"DEVVM_RESOLVER", in.resolver},
{"DEVVM_PASTE_DIR", pasteDir},
}
// The devcontainer.json's variables first: devvm's own win.
+6 -2
View File
@@ -26,6 +26,7 @@ stdout '"from": "default"'
exec tar -xOf $STUB_DIR/sync.tar vm
stdout '^DEVVM_TRANSPARENT_ADDR=''198\.18\.0\.1''$'
stdout '^DEVVM_TRANSPARENT_HOST=''transparent\.devvm\.proxy''$'
stdout '^DEVVM_RESOLVER=''127\.0\.0\.1''$'
exec devvm network --json
stdout '"transparent": \{\n *"on": true,\n *"from": "default"\n *\}'
vm_state $WEB_dir/vm.json
@@ -33,7 +34,8 @@ vm_state $WEB_dir/vm.json
! exec devvm network transparent --json off
stderr '^devvm: json_shows_only command=devvm network transparent$'
# config.toml turns it off for every VM, from the next launch.
# config.toml turns it off for every VM, from the next launch; the VM's
# programs still ask its one name server directly, so names fail at once.
cp $WORK/off.toml $CFG/config.toml
exec devvm network transparent
stdout '\Aoff # \S*/config/devvm/config\.toml\n\z'
@@ -42,6 +44,7 @@ stdout '"from": "config"'
exec devvm
exec tar -xOf $STUB_DIR/sync.tar vm
stdout '^DEVVM_TRANSPARENT_ADDR=''''$'
stdout '^DEVVM_RESOLVER=''127\.0\.0\.1''$'
# The VM's own setting comes first, from its next launch; the same again
# changes nothing.
@@ -65,13 +68,14 @@ exec devvm network transparent --json
stdout '"on": false'
stdout '"from": "vm"'
# An open VM: none, whatever its setting.
# An open VM: none, whatever its setting, and the system's own resolver.
rm $STUB_DIR/hostagent
rm $CFG/config.toml
project open
exec devvm --network open --no-git-protect
exec tar -xOf $STUB_DIR/sync.tar vm
stdout '^DEVVM_TRANSPARENT_ADDR=''''$'
stdout '^DEVVM_RESOLVER=''''$'
# A value that isn't true or false, for a VM without its own: the command
# fails, naming the line.
+2 -2
View File
@@ -64,8 +64,8 @@ stdout '^\.claude/skills\n\S+/config/devvm/agents/claude/\.claude/skills\n\.clau
exec tar -xOf $STUB_DIR/sync.tar vm
stdout '\A\QDEVVM_HOSTNAME=''plain''\E\n\QDEVVM_TZ=''Europe/Paris''\E\n\QDEVVM_LANG=''en_US.UTF-8''\E\n\QDEVVM_GIT_NAME=''Test User''\E\n\QDEVVM_GIT_EMAIL=''[email protected]''\E\n'
# An open VM's proxy too, as its environment has it, where its local proxy listens, and devvm
# paste's folder; no transparent mode, which is for confined VMs.
stdout '^DEVVM_PROXY=''http://devvm:[0-9a-f]{64}@192\.168\.5\.2:[0-9]+''\n\QDEVVM_NO_PROXY=''localhost,127.0.0.1,::1''\E\n\QDEVVM_LOCAL_PROXY=''127.0.77.1:3128''\E\n\QDEVVM_TRANSPARENT_ADDR=''''\E\n\QDEVVM_TRANSPARENT_HOST=''transparent.devvm.proxy''\E\n\QDEVVM_PASTE_DIR=''/tmp/devvm-paste''\E\n\z'
# paste's folder; no transparent mode, which is for confined VMs, and the system's own resolver.
stdout '^DEVVM_PROXY=''http://devvm:[0-9a-f]{64}@192\.168\.5\.2:[0-9]+''\n\QDEVVM_NO_PROXY=''localhost,127.0.0.1,::1''\E\n\QDEVVM_LOCAL_PROXY=''127.0.77.1:3128''\E\n\QDEVVM_TRANSPARENT_ADDR=''''\E\n\QDEVVM_TRANSPARENT_HOST=''transparent.devvm.proxy''\E\n\QDEVVM_RESOLVER=''''\E\n\QDEVVM_PASTE_DIR=''/tmp/devvm-paste''\E\n\z'
exec tar -tf $STUB_DIR/sync.tar
stdout '^transparent\.sh$'
# Without links, the hosts file for /etc/hosts is empty.
+5 -2
View File
@@ -543,9 +543,12 @@ func netBlocks(n *netRun) {
// once, and Lima's network's DNS (192.168.5.3) and the host's address on
// it, asked directly, answer nothing: a refusal or no answer passes, an
// address for example.com fails.
s.Check("with transparent mode stopped, DNS fails at once, not after a timeout, and Lima's network's DNS addresses, asked directly, answer nothing", func() error {
// The VM's programs ask 127.0.0.1 themselves, past systemd-resolved's
// stub, which could keep retrying it without answering.
s.Check("with transparent mode stopped, DNS fails at once, not after a timeout, asking 127.0.0.1 alone, and Lima's network's DNS addresses, asked directly, answer nothing", func() error {
return withoutTransparent(s, vm, func() error {
if err := inVM(s, vm, "timeout 3 getent hosts example.com; [ $? -eq 2 ]"); err != nil {
if err := inVM(s, vm, `[ ! -L /etc/resolv.conf ] && [ "$(awk '$1 == "nameserver"' /etc/resolv.conf)" = "nameserver 127.0.0.1" ] &&
{ timeout 3 getent hosts example.com; [ $? -eq 2 ]; }`); err != nil {
return err
}
return inVM(s, vm, limaDNSAsked)