fix(logs): a VM's logs are held to their caps while it runs

internal/vmlog owns every log a VM can drive but the proxy's own:
Limit (moved from vmssh's logLimit, with Allow for the link session's
warnings), Capped and Trim for ports.log and links.log while they run,
and KeepVM, which the VM's proxy (proxy.IO.KeepLogs, Config.VMLogs from
backend.Run.Logs) and a Lima build run on the serial consoles' and the
hostagent's logs: redacted as they grow (redact.FileFrom), so a reboot
in place can't leave the proxy password there, and rotated past 10 MiB,
counting what a log holds past the hole its writer left
(platform.DataStart).

The proxy's http.Server logs through its own limited log, and its
copied log counts what reached it as stderr; the build proxy's log is
held as a VM's proxy's is. git-pins.jsonl has a cap. Run logs take at
most 256 MiB together, never the newest or a live run's.

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 4a4aabe9a8
commit 9c74dac11e
61 files changed
+1868 -213

No files matched your search

+2 -1
View File
@@ -19,6 +19,7 @@ Each package's concerns and identifiers: [The packages](docs/content/docs/contri
| `internal/upgrade/` | devvm upgrade; `upgradetest/` (tests only) |
| `internal/from/` | `--from`'s references and digests |
| `internal/redact/` | passwords out of logs; `Secret`, the type of every secret's value |
| `internal/vmlog/` | every log a VM can drive (but the proxy's own): its rate, its cap while it runs, and the backend's logs, serial consoles' included |
| `internal/safefile/` | every read of a file a VM can write or swap |
| `internal/devcontainer/`, `internal/jsonc/` | a project's devcontainer.json; JSON with comments |
| `internal/tools/` | the shared tools: the lock, host mise, the daily check, tool image builds, the share |
@@ -122,7 +123,7 @@ Each package's concerns and identifiers: [The packages](docs/content/docs/contri
- **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 `_proxy -config` in the sandbox): the stub hostagent is gone before they look, so they'd wait 15 minutes. It also stops the sandbox's port forwarders, link sessions and stub ssh masters.
- **`limactl shell` reads stdin:** give it none unless the input is meant for it.
- **Boot problems:** read `<devvm's Lima home>/<vm>/serialv.log` before restarting; every start overwrites it.
- **Boot problems:** read `<devvm's Lima home>/<vm>/serialv.log` (and its `.1`, past 10 MiB) before restarting; every start overwrites it.
## Gotchas learned
+1
View File
@@ -143,3 +143,4 @@ These changes are on `main` and go out in the next release.
- **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 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)).
+2 -1
View File
@@ -65,7 +65,8 @@ Each package owns these concerns, and a package's `doc.go`, where it has one, ma
| `internal/fetch` | every HTTP client, with the standard library alone: `NewClient`, with a timeout and `HTTPSOnly` or `SameScheme`, `Retry` and `Transient`, `ReadCapped`, `Get`, `Resolve`, which finds where a HEAD's redirects end, and `Download`, which checks the SHA-256 and caps the size |
| `internal/upgrade` | devvm upgrade: how this devvm was installed (`Detect`), the releases (`Source`, with the newest, `Check` for a notice, and `Fetch`, which checks minisign's `ED` signature by the built-in key, then the SHA-256), the unpack, the link's switch and its rollback, and Homebrew. `upgradetest/`, for tests only, has a TLS release server and a minisign signer |
| `internal/from` | `--from`: references, registry digests with an anonymous token, Docker's IDs and the recorded digests |
| `internal/redact` | passwords out of logs, with the standard library alone: `String` for the run log's lines, which takes out proxy keys and URL passwords, and `File` for another program's log, in place and keeping its length; and `Secret`, the type of the values that let whoever holds them act as you or as a VM ([Secrets in the code](#secrets-in-the-code)) |
| `internal/redact` | passwords out of logs, with the standard library alone: `String` for the run log's lines, which takes out proxy keys and URL passwords, `In` for another program's log as it grows, in place and keeping its length, reading a line not yet ended again from its start when it's within `MatchMax` of what an earlier look read, else from `MatchMax` back, starring what runs on to an `@` there (`Look.Cut` does the same after a rotation's cut), and `Unended` for a copy's cut end; and `Secret`, the type of the values that let whoever holds them act as you or as a VM ([Secrets in the code](#secrets-in-the-code)) |
| `internal/vmlog` | every log a VM can drive but the proxy's own: `Limit`, the rate and length of what a VM makes devvm's background processes write, which the port forwarder and the link session write through and whose `Allow` the link session's warnings take their turns from; `Capped`, a background process's log held to its cap as it appends, with `Trim` at its next start; and `KeepVM`, which the VM's proxy (through `proxy.IO.KeepLogs`) and a build run on the logs the backend writes as the VM runs (`backend.Run.Logs`), the serial consoles' among them, each in a goroutine of its own, redacting what each gained every second (`redact.In`), so a reboot in place can't leave the proxy's password there, and skipping a log that hasn't grown. `Redact` is Lima's redaction at the end of a start. Each rotation copies the log's end to its `.1` file, redacting only what the last look didn't reach and masking a secret cut at its end, and empties it with `f.Truncate`, counting a log by what it holds past the hole its writer left, as Lima's programs write at their own offset. Every log is opened through `safefile` (`Opts.Write`), never through a link or waiting on a FIFO. The proxy, which imports only the standard library and a few of devvm's leaves, rotates its own logs itself (`proxy.rotating`) |
| `internal/safefile` | every read of a file a VM can write or swap, with the standard library alone, so the proxy uses it too ([the checks on owners](#the-checks-on-owners)) |
| `internal/devcontainer` | a project's `devcontainer.json`, with no side effects: finding it, mapping it to a new VM's plan, its refusals, and what devvm update's second reading replaces (`Reread`) |
| `internal/jsonc` | JSON with comments (`jsonc.Strip`), with the standard library alone |
+1 -1
View File
@@ -18,7 +18,7 @@ Every change to devvm's logic comes with a test, and Go tests are table tests ne
## Goroutine leaks
A goroutine that outlives its test is one that would outlive its command in devvm, such as a tunnel the proxy carries after it has closed, or a goroutine that passes signals on after its child has ended. `internal/leaktest` finds them in every package that starts goroutines: `internal/proxy`, `vmssh`, `daemon`, `desktop`, `ui`, `vm`, `backend/lima`, `platform`, `cli`, `gitprotect` and `memnet`. It imports only the standard library, so the proxy's and the daemon's tests use it too.
A goroutine that outlives its test is one that would outlive its command in devvm, such as a tunnel the proxy carries after it has closed, or a goroutine that passes signals on after its child has ended. `internal/leaktest` finds them in every package that starts goroutines: `internal/proxy`, `vmssh`, `daemon`, `desktop`, `ui`, `vm`, `backend/lima`, `platform`, `cli`, `gitprotect`, `vmlog` and `memnet`. It imports only the standard library, so the proxy's and the daemon's tests use it too.
- **`leaktest.Main(m)`**, in a package's `TestMain`, runs the tests and, once they've passed, reads every goroutine's stack. It gives the goroutines that are still ending, such as a closed listener's accept loop, five seconds, then fails the test binary with the stacks of any still running. It leaves out the standard library's own goroutines that outlive every test and that no test can end, which `allowed` lists with why: `signal.Notify`'s loop and an HTTP client's idle connections. It then reads Go's `goroutineleak` profile, which names each goroutine blocked for good on a channel, a lock or a wait group that nothing still running can reach, and fails on any it names. A `TestMain` that makes the test binary a helper process runs the helper first and calls `leaktest.Main` last.
- **`leaktest.Check(t)`**, called first in a test, fails that test when a goroutine started while it ran is still running once it has ended, its context cancelled and its cleanups run, after the same five seconds. It counts the goroutines the test started, and theirs, followed through those still running, so a test running in parallel doesn't count. Nor does a goroutine that a server shared between tests starts for the test, such as one that `TestMain` or a `sync.Once` started, because it leads back to that server's goroutine, which ran before the test, and `Main` finds those at the end. Its failure names the test, where `Main`'s names only the binary, so a test of something that starts and stops goroutines, such as a link session, the port forwarder or the desktop's relay, calls it.
+2 -2
View File
@@ -42,7 +42,7 @@ These settings guard against the host's ssh asking for a forward that devvm's en
- **Which ports.** Which ports each VM forwards, all, none or a list, is in its state (`ports.forward`), and the backend never hears of them: neither `Start`'s `Want` nor any other call of the backend's has them. `vmssh.Forwards.Start`, the one owner of the forwarder, reads them from the VM's state each time it starts one, after a start of the VM and when `devvm ports` changes a running VM's ports, without editing Lima's config. A stopped VM's change is its state's alone, because its next start reads it. When the VM lists ports, the forwarder forwards those less the ports a program on the host has, which the owner leaves out with a `ports_taken` warning. When none is left, no forwarder runs.
- **A forwarder per VM, on the host.** The forwarder is `vmssh.Forwarder`, which isn't a backend's. Its owner, `vmssh.Forwards`, runs it detached as `devvm _ports`, one per VM, for project VMs alone, because only a project VM's start goes through it, and builds' starts don't. The owner starts it once the backend's `Start` returns, and again on a running VM when its ports change, 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 run 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. The owner 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. Lima's `SSH` gives the port with the user and the key, the first `IdentityFile` of Lima's ssh config, and devvm refuses that target unless the config names `127.0.0.1` (`vmssh.FromTarget`, the check links and the ssh config use too). 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 has fewer than 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.
- **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 the log is rotated before it passes 1 MiB, its end kept in `ports.log.1`. 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 (`vmssh.MaxForwards`). It records why it couldn't take each port in `ports.forwarded`, by the bind's error: in use (`EADDRINUSE`), past its limit, or refused (`EACCES` or `EPERM`, such as below 1024 on Linux), and `devvm ports` warns each with its own message (`ports_taken`, `ports_limit`, `ports_refused`). Any other error, such as `EMFILE`, `ENOBUFS` or `EADDRNOTAVAIL`, says nothing about the port, so it's logged, not recorded, and the port is tried again at the next report, the log's limit capping the repeats. A port past the limit is tried again at the next report once the forwarder forwards fewer. A record from before the reasons, whose third line holds every port it couldn't take, is read as giving no reason, so it warns of none rather than call a refused port in use. It reads the reserved ports (below) again with each report, and while it can't read them, it takes no new port and keeps those it has. A port it has that has since become reserved, such as one another VM's start has chosen, is given up at that report, though the VM still listens on it, and also within 10 s on the host's own clock (`Forwarder.Recheck`), whether or not the VM reports, so a VM that holds its session open and stays silent can't keep it. A reserved port the VM listens on waits and is tried again at each report until it's no longer reserved. A port that a host program has, or that the host refused, 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, which a bind on `::1` reports as `EADDRNOTAVAIL`, `EAFNOSUPPORT` or `EPROTONOSUPPORT`. `EACCES` or `EPERM` on `::1` alone, with `127.0.0.1` bound, also gives IPv4 alone, with a line in the log, because that's a host denying IPv6 rather than a port it refuses. Any other error on `::1` closes the port's `127.0.0.1` listener and counts as that bind's error would on `127.0.0.1`, recorded or tried again at the next report as the bullet above says, so a passing error such as `EMFILE` never leaves a forward on IPv4 alone until its port is opened again. 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. Each relay's ssh runs with a context of its own, which closing its forward cancels, so the ssh is killed with the forward even when the VM never ends its channel. `pipeSSH`, which carries every relay of the forwarder's, the link sessions' and a login's callback, also cancels that context once the client on the host has closed its side and the VM has sent nothing for 30 seconds (`relayGrace`), and once the client can take nothing more and the ssh hasn't exited within 30 seconds. Each write of the VM's bytes to the client starts the grace again once it's done, and the grace doesn't run while that write waits for the client, so a client that closes for writing alone and waits still gets an answer the VM keeps sending, however slowly it reads. The VM must send something at least every 30 seconds, its first byte included, so a client that half-closes and waits longer than that for a first byte, such as `nc -N` in front of a slow query, is cut. The timer (`graceTimer`) runs only once the client's side has closed, or once the copy to the client has ended, with a write that failed or the VM's EOF, and a relay that ends stops it for good, so the client's goroutine, which can outlive the relay, never starts it again. The relay's own context, its owner's, also closes the client's connection when it ends, so a write that waits on a client that stopped reading ends with its forward, its link or `LoopbackForward.Close`.
@@ -861,7 +861,7 @@ devvm handles values that let whoever holds them act as you or as a VM: a VM's p
The wire types keep each file's bytes as they were, so a frozen release's `proxy.json` writes back byte for byte (`TestV010ProxyConfigs`), its `Sum` doesn't change and no running VM's proxy starts again for an upgrade. An agent's login file stays the agent's own format, read and written as a map so that fields devvm doesn't know are kept, and a key or token is a `redact.Secret` once it leaves the map, through a lookup, a refresh or a capture.
**Not covered.** The company proxy's URLs as your environment gives them, `HTTPS_PROXY` and `HTTP_PROXY`, can hold a password, and they stay strings, because devvm passes them on as they are, to `proxy.json` and to the programs it runs on the host. So do the URLs `proxy.Upstream.WithPassword` returns, which hold the saved password for devvm's own clients and the programs it runs. The VM's proxy URL, which holds its password, is a string too, because it goes into the VM's Lima config and environment, where the VM needs it. `redact.String` and `redact.File` take the passwords in such URLs out of devvm's run log and Lima's logs ([your company proxy's password](../safety/attack-vectors.md#this-machine)). Two values are strings by design:
**Not covered.** The company proxy's URLs as your environment gives them, `HTTPS_PROXY` and `HTTP_PROXY`, can hold a password, and they stay strings, because devvm passes them on as they are, to `proxy.json` and to the programs it runs on the host. So do the URLs `proxy.Upstream.WithPassword` returns, which hold the saved password for devvm's own clients and the programs it runs. The VM's proxy URL, which holds its password, is a string too, because it goes into the VM's Lima config and environment, where the VM needs it. `redact.String` and `redact.In` take the passwords in such URLs out of devvm's run log and Lima's logs ([your company proxy's password](../safety/attack-vectors.md#this-machine)). Two values are strings by design:
- **The Keychain's value,** which `platform.KeychainGet` returns and `KeychainSet` takes as a string, because `internal/platform` imports no devvm package. `secrets.Store` makes it a `Secret` at once in `saved`, and reveals it only for `KeychainSet` in `save`.
- **devvm desktop's VNC password,** 8 characters that you must see to type into a VNC viewer. devvm keeps it in the desktop section of `vm.json` and shows it in `desktop_ready`.
+2 -1
View File
@@ -441,7 +441,7 @@ The proxy's own lines, such as what it loaded and what failed upstream, go to `p
The event log also holds the VM's [links](ports.md#links-between-vms)' connections, which `devvm _links` writes in the same format: `link` for a connection it carried, and `link_refused`, `link_target_stopped` or `link_limit` for one it refused, with the link's name as the host and the target VM in `target`. An open VM's event log holds its proxy's events and its links', but nothing it reached directly.
The proxy is the only program that writes `proxy.log`, and the event log has `devvm _links` as its only other writer. The proxy rotates each log before a line would take it past 10 MiB, and `devvm _links` writes the event log with the proxy's own code, so it rotates the log by the same rule and a VM that runs for months keeps at most about 20 MiB of each. A line never spans two files, and lines from the proxy's connections at the same time are written one after another, so a rotation loses none and splits none. Before each line, each writer checks that the file it has open is still `network.jsonl`, and when the other writer has rotated it, the writer opens the new `network.jsonl` and writes there, so its lines go on reaching the file that `devvm network log --follow` follows. Each writer takes the log's size from the file, so it counts the other writer's lines too. A writer rotates the log while it holds a lock on the file and checks the name again first, so when both reach the limit at once, only one renames the file and the other writes to the new one. A rotation renames `network.jsonl` to `network.jsonl.1`, which replaces the one that was there, and starts a new `network.jsonl`. `proxy.log` is also the proxy process's output, where its last error goes when it stops, so the proxy copies it to `proxy.log.1` and empties it instead, and that error still reaches the current file. Every log file and its `.1` file is readable only by you (mode 600).
The proxy is the only program that writes `proxy.log`, and the event log has `devvm _links` as its only other writer. The proxy rotates each log before a line would take it past 10 MiB, and `devvm _links` writes the event log with the proxy's own code, so it rotates the log by the same rule and a VM that runs for months keeps at most about 20 MiB of each. A line never spans two files, and lines from the proxy's connections at the same time are written one after another, so a rotation loses none and splits none. Before each line, each writer checks that the file it has open is still `network.jsonl`, and when the other writer has rotated it, the writer opens the new `network.jsonl` and writes there, so its lines go on reaching the file that `devvm network log --follow` follows. Each writer takes the log's size from the file, so it counts the other writer's lines too. A writer rotates the log while it holds a lock on the file and checks the name again first, so when both reach the limit at once, only one renames the file and the other writes to the new one. A rotation renames `network.jsonl` to `network.jsonl.1`, which replaces the one that was there, and starts a new `network.jsonl`. `proxy.log` is also the proxy process's output, where its last error goes when it stops, so the proxy copies it to `proxy.log.1` and empties it instead, and that error still reaches the current file. The proxy takes `proxy.log`'s size from the file before each line, so what reached it as the process's output counts too, and its HTTP server's errors, such as a handler's panic, go through the proxy's own lines rather than straight to that output. Every log file and its `.1` file is readable only by you (mode 600).
`devvm network log` reads `network.jsonl.1` before `network.jsonl`, so the history it shows and the blocks that `devvm network log --blocked` counts carry on across a rotation. `devvm network log --follow` reads the renamed file to its end and then follows the new one from its start. `devvm rm` deletes the `.1` files with the rest of the VM's logs.
@@ -476,6 +476,7 @@ The config is one JSON file, `proxy.Config`, which a VM's proxy and a build's pr
| `nix_cache_max` | with `nix_cache`: the cache's cap, in bytes (none: 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 |
| `link_sockets` | with `links`: the folder of the links' sockets, devvm's run folder; without it, no link is reached |
| `vm_logs` | the logs that the VM's backend writes as the VM runs and the VM can drive, such as its serial console's, which the proxy holds to their cap for as long as it runs ([Lima's hostagent](processes.md#limas-hostagent)) |
| `agent`, `agent_socket` | together, as absolute paths: the SSH agent that the VM's start forwards, your own or devvm's, and the VM's own socket in devvm's run folder, `agent-<hash>.sock`, on which the proxy relays it and which the VM's backend forwards instead ([the SSH agents](processes.md#the-ssh-agents)); devvm keeps a running VM's as its start set them |
| `devvm_sha256`, `ca_sha256`, `ca_next_sha256` | the SHA-256 of devvm's binary, of the VM's CA certificate and of its next CA's that the proxy started with; the proxy doesn't read them, and they're there so that a new binary or a new CA makes another config ([how long a proxy runs](#how-long-a-proxy-runs)) |
+3 -3
View File
@@ -190,13 +190,13 @@ Each write replaces a file whole, so a file is never left half written. devvm ma
### The run log
Each run that runs a command has one log, `~/.local/share/devvm/logs/runs/<date>-<time>-<pid>.log`, which only you can read, and devvm keeps the newest 20 ([a command fails](../using/troubleshooting.md#a-command-fails)). In the log, each command appears as a `+` line with its arguments, followed by its output, and a numbered step adds a `# [2/5] <step>` line first. A command that devvm runs in a VM adds at most 4 MiB of output to the log, because a VM could otherwise fill this machine's disk with it, and a `devvm: truncated` line marks where devvm left out the rest.
Each run that runs a command has one log, `~/.local/share/devvm/logs/runs/<date>-<time>-<pid>.log`, which only you can read. devvm keeps the newest 20, or as many as `logs.runs` sets, and deletes older ones once the logs take more than 256 MiB together, but it never deletes the newest, nor the log of a run whose process still runs, which it reads from the pid in the log's name, so a background process or another devvm never loses the log it's writing ([a command fails](../using/troubleshooting.md#a-command-fails)). In the log, each command appears as a `+` line with its arguments, followed by its output, and a numbered step adds a `# [2/5] <step>` line first. A command that devvm runs in a VM adds at most 4 MiB of output to the log, because a VM could otherwise fill this machine's disk with it, and a `devvm: truncated` line marks where devvm left out the rest. A run writes at most 128 MiB to its log in all, as one that lasts, such as `devvm desktop`'s, could otherwise log without end, and a `devvm: truncated` line marks that too.
A VM's proxy key and the build proxy's password are written as `devvm:<key>@`. Any other password in a URL, in a command's arguments or its output, is written as `user:<password>@`, and so is the password in a proxy's address without a scheme, such as `user:[email protected]:8080`, when the address has a port. So a company proxy's password from your shell's `HTTPS_PROXY`, which Lima can print as it starts a VM, stays out of the log, even when a command writes it in pieces. This covers the output of the commands devvm runs in a VM too, such as a VM's setup or a `devcontainer.json`'s commands.
With `-v`, the lines devvm shows are the log's own, so a VM's proxy key is hidden in them as it is in the log, and devvm drops the control characters a command prints, so its output can't move the cursor or change your terminal.
Lima keeps a log of its own for each VM, `ha.stderr.log` in the VM's folder in devvm's Lima home, and it writes a proxy password into that log as it starts the VM. Lima also keeps a log of each of the VM's serial consoles there, `serial.log`, `serialp.log` or `serialv.log`, and its boot scripts write the VM's proxy URL, with the VM's proxy password, to the console as they set up the VM's environment. Once Lima has started the VM, devvm replaces each password in those logs with as many `*`, so the log keeps its length and Lima goes on writing to it. If devvm can't change the file, it warns you and names it, and you can delete the file, which Lima makes again at the VM's next start.
Lima keeps a log of its own for each VM, `ha.stderr.log` in the VM's folder in devvm's Lima home, and it writes a proxy password into that log as it starts the VM. Lima also keeps a log of each of the VM's serial consoles there, `serial.log`, `serialp.log` or `serialv.log`, and its boot scripts write the VM's proxy URL, with the VM's proxy password, to the console as they set up the VM's environment. Once Lima has started the VM, devvm replaces each password in those logs with as many `*`, so the log keeps its length and Lima goes on writing to it. If devvm can't change the file, it warns you and names it, and you can delete the file, which Lima makes again at the VM's next start. While the VM runs, its proxy also replaces each password that these logs gain, within a second of its line ending, so a reboot inside the VM, which on Linux hosts QEMU carries out in place and which runs the boot scripts again, can't leave the password in the console's log. It holds the disk space each of these logs takes to 10 MiB too, with a `.1` file of as much, on a file system with holes ([Lima's hostagent](processes.md#limas-hostagent)), and a rotation's copy, such as `ha.stderr.log.1`, has each password replaced, whether the start had ended or not.
### A VM's folder
@@ -208,7 +208,7 @@ Each VM's folder, `vms/<hash>/`, is named by the hash at the end of the VM's nam
| `lock` | the lock that each change to `vm.json` holds ([locks](#locks)) |
| `policy` | the VM's own [network rules](network.md#policy-files), which `devvm network allow`, `deny` and `rm` change |
| `run/` | what the VM's runs leave: its [host keys](security.md#ssh-into-vms) for its current start (`known_hosts`), which every ssh of devvm's to the VM checks, its [port forwarder](ports.md#its-process-and-files)'s `ports.pid`, `ports.status` and `ports.lock`, its [proxy](network.md#the-proxy)'s config, `proxy.json`, which holds everything the proxy started with, its password and the [company proxy](network.md#through-a-company-proxy)'s from the environment among it ([devvm _proxy](network.md#devvm-_proxy)), and its `proxy.pid` and `proxy.status`, the VM's own [CA](network.md#the-vms-ca) and the next one in `ca/` (`ca.pem` and `ca.key`, `next.pem` and `next.key`, and their `lock`), whose keys never leave this machine, its [secrets](network.md#how-the-proxy-puts-them-in)' bindings (`secrets.json`, `secrets.policy`), its [link session](ports.md#the-link-session)'s `links.pid` and `links.json`, the [remake lock](#making-a-vm-again) (`remake.lock`), the hostagent it was started on (`started`), the [ssh port](lima.md#what-devvm-sets-on-a-vm) its last start held for a minute (`ports.ssh-hold`), and on macOS the hostagent's [sandbox profile](lima.md#confinement) (`sandbox.sb`) |
| `logs/` | its proxy's decisions (`network.jsonl`) and its proxy's own output (`proxy.log`), which the [log files](network.md#log-files) describe, its link session's output (`links.log`) and its port forwarder's (`ports.log`) |
| `logs/` | its proxy's decisions (`network.jsonl`) and its proxy's own output (`proxy.log`), which the [log files](network.md#log-files) describe, its link session's output (`links.log`) and its port forwarder's (`ports.log`), each held to 1 MiB with one `.1` file |
| `home.tar.gz` | the VM's home folder, only while devvm [makes the VM again](#making-a-vm-again) |
devvm finds a folder's VM by the state that records the folder's path as its `dir`, first in the VM folder that the hash of that path names and then in every other VM's ([a moved folder](#a-moved-folder)), 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, and when the VM folder that the path's hash names holds another VM's state, the new VM's name ends with the hash of the path and a number instead, the first whose folder is free. The VM's folder lasts as long as the VM, because `devvm rm` and `devvm gc --orphans` stop what runs for the VM, delete what devvm keeps for it outside the folder, and then delete the folder whole ([deleting a VM](#deleting-a-vm)), so the next devvm in that folder starts fresh.
+7 -7
View File
@@ -34,7 +34,7 @@ The run that starts a process reaps it if it ends first, and once that run ends,
- **Holds:** everything you keep with devvm. It reads secrets from the macOS Keychain with the `security` command or from files only you can read, and it writes each VM's proxy password and the company proxy's credentials into files only you can read, never into a process's arguments ([where secrets are saved](network.md#where-secrets-are-saved)).
- **Reads from a VM:** the output of the commands it runs there, such as a VM's host keys, its settings to save and a history export, and the files a VM can write or swap, such as the project folder's `devcontainer.json`. It reads such a file never following a link out of the folder, and with a cap on its size, and each kind of output has a cap of its own, such as 128 MiB for a VM's settings and 2 GiB for a history export ([coding agents](agents.md#saving-a-vms-settings)).
- **Writes:** its run log, `~/.local/share/devvm/logs/runs/<date>-<time>-<pid>.log`, with at most 4 MiB of output for each command it runs in a VM, and it keeps the newest 20 logs, or as many as `logs.runs` sets. It writes state files whole, renamed into place ([state files](overview.md#state-files)).
- **Writes:** its run log, `~/.local/share/devvm/logs/runs/<date>-<time>-<pid>.log`, with at most 4 MiB of output for each command it runs in a VM and at most 128 MiB in all, after which one line says the rest was left out. It keeps the newest 20 logs, or as many as `logs.runs` sets, and deletes older ones once the logs take more than 256 MiB together, but never the newest, nor a log whose run still runs, which it reads from the pid in the log's name. It writes state files whole, renamed into place ([state files](overview.md#state-files)).
- **Listens:** only in `devvm desktop` ([the desktop relay](#the-desktop-relay)) and while `devvm agent login` waits for a browser's login ([listeners](#listeners-a-vm-reaches)).
- **Confinement:** none. devvm needs your Keychain and your files, and it's the program you chose to run.
@@ -44,7 +44,7 @@ One proxy runs for each running VM, as `devvm _proxy -config FILE`, with the VM'
- **Holds:** the VM's password, the VM's CA and the next one, with their keys, and the company proxy's credentials. It looks up each bound secret's value itself, through the Keychain or the secret's file, and keeps a value for 5 minutes and an agent's login for 30 seconds. It reads the agents' login files in devvm's store and refreshes their OAuth logins there, and it saves a login that the VM makes into the store and rewrites the VM's bindings ([logins made in a VM](network.md#logins-made-in-a-vm)).
- **Reads from the VM:** every request the VM sends. It takes at most 64 KiB of a request's headers, in an intercepted or transparent connection too, within 30 seconds, requires the VM's password before anything else, and reads a ClientHello of at most 16 KiB and 256 bytes within 10 seconds of its first byte. It also reads files the VM can't write but that change while it runs: your policy files and the VM's bindings, each at most 1 MiB, and the links' list, `links.json`, at most 1 MiB, which `devvm _links` writes. For a VM that forwards an SSH agent, it also reads the agent's requests that the VM sends, each at most 256 KiB ([the SSH agents](#the-ssh-agents)).
- **Writes:** its event log, `network.jsonl`, and its own log, `proxy.log`, in the VM's logs folder, `~/.local/share/devvm/vms/<hash>/logs/`, each rotated before it passes 10 MiB, with one `.1` file kept ([log files](network.md#log-files)). For a VM with the nix layer, it fills the [shared Nix cache](network.md#the-shared-nix-cache), at most 10 GiB unless its config sets another cap. It also writes the login files and bindings above.
- **Writes:** its event log, `network.jsonl`, and its own log, `proxy.log`, in the VM's logs folder, `~/.local/share/devvm/vms/<hash>/logs/`, each rotated before it passes 10 MiB, with one `.1` file kept ([log files](network.md#log-files)). Its HTTP server's errors go to `proxy.log` too, and so does what reaches the process's error output, which counts toward the 10 MiB. It also holds the logs that the VM's backend writes as the VM runs to 10 MiB each, with a `.1` file of as much, the VM's serial console's among them, looking at each every second in a goroutine of its own ([Lima's hostagent](#limas-hostagent)). A proxy that a devvm before this one started doesn't, so a VM that's running when you upgrade gets this once its next devvm command starts its proxy again. For a VM with the nix layer, it fills the [shared Nix cache](network.md#the-shared-nix-cache), at most 10 GiB unless its config sets another cap. It also writes the login files and bindings above.
- **Bounds:** at most 1024 `CONNECT` tunnels at once, at most 2048 connections of every kind with the VM's password, plain HTTP and idle ones included, at most 128 more that haven't sent the password yet, and at most 2048 requests to hosts under way, its tunnels' included. It keeps at most 1024 of the certificates it made for intercepted hosts for each CA, dropping the one used longest ago. A connection to the proxy, and the HTTP inside an intercepted or transparent connection, waits at most 10 minutes between requests, and HTTP/2 inside one carries at most 100 requests at once. A request without the VM's password gets its `407` and its connection closed. A plain HTTP request whose client has stopped sending goes on while its answer keeps coming, and ends after a minute with nothing to pass on, so a client that went away frees what its request holds ([the proxy](network.md#the-proxy)). Nothing bounds how long a request or a tunnel lasts, so long downloads, WebSockets and slow streams go on.
- **Listens:** on `127.0.0.1`, on the VM's proxy port, and, for a VM that forwards an SSH agent, on the VM's agent socket, `~/.local/share/devvm/run/agent-<hash>.sock` ([listeners](#listeners-a-vm-reaches)).
- **Confinement:** none. It runs as you, with your Keychain and your files.
@@ -56,7 +56,7 @@ A build gets a proxy of its own only behind a company proxy, because a build VM
- **Holds:** a password made for the build, and the company proxy's credentials. It has no CA, no secrets, no links and no Nix cache.
- **Reads from the build:** its requests, with the same checks as a VM's proxy, under a policy that allows any host on ports 80 and 443, but not this machine's own or internal addresses.
- **Writes:** `events.jsonl`, rotated as a VM's event log is, and `proxy.log`, in the build proxy's folder. devvm deletes the folder after a build that succeeds and keeps it after one that fails.
- **Writes:** `events.jsonl` and `proxy.log`, in the build proxy's folder, each rotated as a VM's proxy rotates its own. devvm deletes the folder after a build that succeeds and keeps it after one that fails. The build VM's own logs are held to their caps by the build's devvm process, with a company proxy or without one, as a VM's proxy holds a VM's.
- **Confinement:** none.
- **Starts and ends:** the build starts it, keeps its process and stops it when the build ends, and a cleanup stops it when the build fails or is interrupted. It also follows the build VM's hostagent, as a VM's proxy does.
@@ -66,7 +66,7 @@ One forwarder runs for each running project VM that forwards ports, as `devvm _p
- **Holds:** the key that the backend logs in to the VM with, which on Lima is Lima's `_config/user`, and the VM's host keys for its current start. Its ssh uses no agent.
- **Reads from the VM:** the VM's report of the ports it listens on, which comes over one ssh session about every 10 seconds, as the VM paces it. A line of the report has at most 127 bytes and its newline, and a longer line, or a report of more than 4096 lines, ends the session, which the forwarder opens again, so nothing is cut. The forwarder applies at most one report every 500 ms. It also reads the bytes of each forwarded connection, which it carries as they are, and the other VMs' records of their ports.
- **Writes:** `ports.forwarded` in the VM's run folder, and its log, `ports.log`, in the VM's logs folder. The VM chooses some of what goes in the log, so the forwarder makes at most 200 writes at once and then one every 10 seconds, each cut at 512 bytes and without control characters other than newlines and tabs, and devvm empties the log at the forwarder's next start once it's over 1 MiB.
- **Writes:** `ports.forwarded` in the VM's run folder, and its log, `ports.log`, in the VM's logs folder. The VM chooses some of what goes in the log, so the forwarder makes at most 200 writes at once and then one every 10 seconds, each cut at 512 bytes and without control characters other than newlines and tabs. The log is also its process's output, and before each line the forwarder checks its size on disk, so a line that would take it past 1 MiB rotates it first: its end goes to `ports.log.1`, replacing the one there, and the log starts empty. devvm rotates a log that an earlier forwarder left past 1 MiB as it starts the next one.
- **Bounds:** at most 256 forwards, and at most 256 connections at once. When accepting a connection fails while the port still listens, such as when the forwarder runs out of open files, it tries again after a wait that starts at 5 ms and doubles with each failure in a row, up to a second, and logs only the first failure of a run, as the link session and a login's forward do.
- **Listens:** on `127.0.0.1` and `::1` for each forwarded port ([listeners](#listeners-a-vm-reaches)).
- **Confinement:** none. Its ssh processes get the higher limit of open files that devvm runs with.
@@ -78,7 +78,7 @@ One link session runs for each running client VM with [links](ports.md#links-bet
- **Holds:** the login key and the pinned host keys of the client and of each target it connects to.
- **Reads from the VMs:** the bytes of each link's connection, both ways, and the messages of the client's sshd, such as its refusal of a forward, each cut at 512 bytes.
- **Writes:** `links.json` in the client's run folder, the client's event log, `network.jsonl`, with the proxy's own writer, so it rotates by the same rule, and its log, `links.log`, in the client's logs folder, which it writes as the forwarder writes its own and which devvm empties at the next session's start once it's over 1 MiB.
- **Writes:** `links.json` in the client's run folder, the client's event log, `network.jsonl`, with the proxy's own writer, so it rotates by the same rule, and its log, `links.log`, in the client's logs folder, which it writes, limits and rotates past 1 MiB as the forwarder does its own. Its warning that the client refused to listen for a link carries the client's sshd's words, and the client chooses how often it comes, so each warning takes its turn from the same limit as the log's lines.
- **Bounds:** at most 256 of the client's connections at once.
- **Listens:** on a unix socket for each link, mode 600, in `~/.local/share/devvm/run` (mode 700).
- **Confinement:** none.
@@ -102,7 +102,7 @@ Each connection that the forwarder or the link session carries gets an ssh proce
On Linux hosts, Lima starts each VM's QEMU through a wrapper that devvm writes into `~/.local/share/devvm/run/qemu/`, which runs `devvm _qemu exec` ([confinement](lima.md#confinement)).
- **`devvm _qemu exec`** reads Lima's arguments for QEMU and adds `restrict=on` to Lima's one network, except for an open VM and a build with the internet, and for a VM confined to its proxy it adds a `guestfwd` to that proxy. It refuses arguments of any other shape (`qemu_refused`). It then runs QEMU in its place, or, for a VM with `.git` pins, which a VM whose [.git protection](git-protection.md#on-linux-hosts) is on has, starts the keeper and waits for it. Only such a VM gets a user namespace.
- **The keeper, `devvm _qemu pinned`,** runs in a user namespace and a mount namespace of its own, as you, with the capability to mount in that namespace alone. It makes `.git`'s hooks and config read-only there, and it pins a path again after any change in a folder it watches, and every 2 seconds. It records each pin it makes again in `git-pins.jsonl` in the VM's run folder, and on QEMU's error output, which Lima logs. It starts QEMU through `devvm _qemu drop`, which clears its ambient, permitted, effective and inheritable capabilities, keeping the bounding set, sets `no_new_privs`, and runs QEMU.
- **The keeper, `devvm _qemu pinned`,** runs in a user namespace and a mount namespace of its own, as you, with the capability to mount in that namespace alone. It makes `.git`'s hooks and config read-only there, and it pins a path again after any change in a folder it watches, and every 2 seconds. It records each pin it makes again in `git-pins.jsonl` in the VM's run folder, and on QEMU's error output, which Lima logs. Past 1 MiB, the file takes no more events, but a line for each saying it went unrecorded, up to 64 KiB more, which the next check names. It starts QEMU through `devvm _qemu drop`, which clears its ambient, permitted, effective and inheritable capabilities, keeping the bounding set, sets `no_new_privs`, and runs QEMU.
- **`devvm _qemu probe DIR`** checks, in a namespace of its own, that a file in DIR can be pinned.
- **`devvm _qemu connect`** is what QEMU's `guestfwd` runs for each connection that the VM makes to `192.168.5.4:3128`. It connects to the VM's proxy and carries the bytes both ways, so it reads only what the VM sends to its proxy, which the proxy checks. Each one is a process of its own, about 7.7 MB of memory, so it carries at most 256 of the VM's connections at once, about 2 GB for a VM that holds them all, each holding a slot, which is a lock file in the `proxy.slots` folder of the VM's run folder. A connection past that gets a `503` and is closed before it reaches the proxy, and QEMU's error output, which Lima logs, says so at most once a minute (`qemu_connects_full`). A VM that was running when devvm was upgraded has no slots, and so no limit, until its next start. It has no idle timeout and no limit on the bytes it carries, because the proxy bounds what each connection carries, and a long download or a quiet stream must go on.
@@ -148,7 +148,7 @@ Each running VM has a hostagent, `limactl hostagent`, which `limactl start` runs
- **Holds:** Lima's login key, `_config/user` in devvm's Lima home, which every VM there authorizes, and the VM's disk.
- **Reads from the VM:** everything the VM's network sends, on macOS. On Linux, QEMU carries it.
- **Writes:** its logs, `ha.stdout.log` and `ha.stderr.log`, in the VM's Lima folder, which devvm doesn't rotate. devvm replaces each proxy password in `ha.stderr.log`, and in the serial consoles' logs, `serial*.log`, with as many `*` once the start ends, in the first 64 MiB of each log.
- **Writes:** its logs, `ha.stdout.log` and `ha.stderr.log`, in the VM's Lima folder, which also get QEMU's errors on Linux, and the VM's serial console logs there, `serial.log`, `serialv.log` and `serialp.log`, which QEMU or Apple's Virtualization framework writes for it and which the VM's root writes to through `/dev/hvc0` and the other consoles. Each start writes them anew. devvm replaces each proxy password in `ha.stderr.log` and the serial consoles' logs with as many `*` once the start ends, in the first 64 MiB of each log. While the VM runs, its proxy looks at each of these logs every second, skipping one that hasn't grown: it replaces each password in what the log gained since, because a reboot inside the VM, which QEMU on Linux carries out in place, runs Lima's boot scripts again and writes the password to the console again, and it rotates a log once it holds more than 10 MiB. A look reads a line that hasn't ended yet again from its start when that's within 64 KiB of where the last look stopped, and otherwise from 64 KiB before, where it stars what runs on to an `@` as the rest of a secret, so a line that never ends costs at most 64 KiB more than what's new in it, and a secret of any length is found. A rotation copies the log's last 10 MiB, from a line's start, to the log's `.1` file, replacing the one there, with each password and proxy key in it replaced, and the start of one that the copy cuts before its `@` masked, and empties the log. The rest of that one, which the writer goes on with, is starred at the next look, up to its `@`. So each of these logs takes at most 10 MiB and 10 MiB more in its `.1` file, plus what a VM writes in a second. Its writer goes on at its own offset, past a hole that takes no disk, so what's capped is the space the log takes on disk, not its length, which keeps growing, and only on a file system with holes, such as APFS, ext4, XFS and btrfs, as one without them would write the emptied part out as zeros. What the writer adds between the copy and the emptying is lost. On macOS, a reboot inside the VM stops it, as Apple's Virtualization framework ends a VM that restarts.
- **Listens:** on the VM's ssh port on this machine's loopback, on macOS, where on Linux QEMU listens. It also listens on unix sockets in the VM's Lima folder and, for an open VM or a build, on loopback ports for Lima's DNS resolver ([listeners](#listeners-a-vm-reaches)).
- **Confinement:** on macOS, a confined VM's hostagent and a build's run under a Seatbelt profile, `sandbox.sb` in the VM's run folder, which denies `com.apple.dnssd.service`. A confined VM's profile lets it connect only to the VM's ssh port and its proxy on the host's loopback, to the unix sockets in the VM's Lima folder and, when the VM forwards an agent, to that SSH agent, and it lets the hostagent listen only on the VM's ssh port and those unix sockets. A build's profile reaches either the internet but not the host's loopback, apart from its ssh port and its build proxy's port, or nothing, and it doesn't limit what the hostagent listens on. Every profile limits only the network, so the hostagent can still read and write your files. An open VM's hostagent and every hostagent on Linux run unconfined, and on Linux, QEMU's restricted network confines a confined VM instead ([confinement](lima.md#confinement)).
- **Starts and ends:** devvm records the hostagent it started in `started` in the VM's run folder and checks that the VM still runs on it ([the self-check](network.md#the-self-check)), and the proxy and the forwarder follow its `ha.pid`. Nothing waits for it, and `limactl stop`, which `devvm stop` runs, ends it.
+1 -1
View File
@@ -127,7 +127,7 @@ The attacks in this section run the attacker's code, and devvm doesn't stop that
- **The proxy's CA keys.** Inside a VM, its CA vouches for any site, so someone with a copy of its key and a place on your network could impersonate sites to that VM. Each VM has CAs of its own, so a copy reaches one VM and no other. Only you can read the keys, they never leave this machine, and devvm keeps them out of Time Machine. Each CA lasts 30 days, so a copy goes stale, but the next CA's key is on disk for up to 23 days before that CA starts, so a copy of it taken then works until that CA ends, up to 53 days later. Keep `~/.local/share/devvm/vms` out of other backup and sync tools as well, and on Linux, which has no Time Machine, out of your backups ([the VM's CA](../internals/network.md#the-vms-ca)).
- **Your company proxy's password.** No VM gets the company proxy's settings: an open VM goes through its own proxy, which goes through the company proxy for it.
- devvm keeps the password out of its run logs only where it can tell it's a password, so one in an address with neither a scheme nor a port, one with a raw `/`, `?`, `#` or `@` in it, or one in a run of more than 4 KiB without a space that a command writes in pieces can stay.
- Lima's own log for the VM holds the password until the VM has started, when devvm replaces it with as many `*`, so the log still shows its length. If devvm is killed before then, or you run `limactl start` outside devvm, the log keeps it. Lima's logs of the VM's serial consoles hold the VM's own proxy password in the same way, until the VM has started. With `config.toml`'s proxy, the mise that devvm runs on this machine gets the password in its environment, where programs that run as you can read it ([open VMs and builds](network.md#open-vms-and-builds), [the run log](../using/troubleshooting.md#a-command-fails)).
- Lima's own log for the VM holds the password until the VM has started, when devvm replaces it with as many `*`, so the log still shows its length. If devvm is killed before then, or you run `limactl start` outside devvm, the log keeps it. Lima's logs of the VM's serial consoles hold the VM's own proxy password in the same way, until the VM has started. A reboot inside the VM writes it to the console's log again, and while the VM runs, its proxy replaces it within about a second of its line ending, so for that second, or for as long as the proxy isn't running, the log holds it ([Lima's hostagent](../internals/processes.md#limas-hostagent)). With `config.toml`'s proxy, the mise that devvm runs on this machine gets the password in its environment, where programs that run as you can read it ([open VMs and builds](network.md#open-vms-and-builds), [the run log](../using/troubleshooting.md#a-command-fails)).
## Left to you
+1 -1
View File
@@ -224,7 +224,7 @@ devvm gc --retention # gc as usual, then apply
| Key | What devvm deletes |
| --- | --- |
| `logs.runs` | the [run logs](troubleshooting.md#a-command-fails) beyond the newest this many, which is 20 when it's off |
| `logs.runs` | the [run logs](troubleshooting.md#a-command-fails) beyond the newest this many, which is 20 when it's off, and older ones past 256 MiB together whatever it is |
| `history.age` | the [exports of agents' history](coding-agents.md#history) written this long ago or more, such as `90d` |
| `history.count` | the exports of agents' history beyond the newest this many |
| `tools.unused-age` | the current shared tools that no VM has had for this long, counted from when devvm first found that no VM has them. While a VM is being made or is getting new shared tools, retention deletes none of them in that run, because that VM may not list the tools it picked yet, and it still applies the other settings |
+2 -2
View File
@@ -112,9 +112,9 @@ Only you can read it, because each time devvm runs, it makes this folder and the
| `cache/` | what devvm makes again whenever it needs it: its own mise, the shared Nix cache, and in `from-digests.json` the digest that each container image a `--from` base starts from had when devvm last looked it up | you can delete it at any time, and devvm makes each part again when it's needed. An image built from a container image keeps that digest in its own record, so it stays current without the cache |
| `cache/mise/<version>` | the mise that devvm runs on this machine to resolve the tools lock, one folder per mise version | `devvm gc` deletes the folders of older versions, which an upgrade of devvm leaves |
| `exports/` | the agents' [history](coding-agents.md#history) that `devvm history export` and `devvm rm` save, one `.tar.gz` per export, each with a `.folder` file beside it that names its VM's project folder | `devvm gc --history` deletes them, or with `--older-than 30d` those that old, and nothing else does |
| `logs/runs/` | the [run logs](troubleshooting.md#a-command-fails), one per devvm run that runs a command | devvm keeps the newest 20 |
| `logs/runs/` | the [run logs](troubleshooting.md#a-command-fails), one per devvm run that runs a command | devvm keeps the newest 20, and deletes older ones once they take more than 256 MiB together, but never one that a running devvm still writes |
| `logs/tools-check.log` | the output of the daily check for newer shared tools | each check replaces it |
| `vms/<hash>/logs/` | a VM's network log, `network.jsonl`, which holds its proxy's decisions, its proxy's own output, `proxy.log`, and its link session's output, `links.log`. Before the network log or the proxy's log would grow past 10 MiB, the proxy moves it to the same name with `.1` added, replacing the older one, so each of them takes at most about 20 MiB, and `devvm network log` reads both of the network log's files | `devvm rm` deletes them with the VM's folder, `.1` files included |
| `vms/<hash>/logs/` | a VM's network log, `network.jsonl`, which holds its proxy's decisions, its proxy's own output, `proxy.log`, its link session's output, `links.log`, and its port forwarder's, `ports.log`. Before the network log or the proxy's log would grow past 10 MiB, the proxy moves it to the same name with `.1` added, replacing the older one, so each of them takes at most about 20 MiB, and `devvm network log` reads both of the network log's files. The link session's and the forwarder's logs do the same at 1 MiB | `devvm rm` deletes them with the VM's folder, `.1` files included |
| `vms/<hash>/run/ca/` | the certificate authorities that the VM trusts for its proxy, its current one and the next, with their keys, which never leave this machine | devvm makes a new one when the current one has less than a week of its 30 days left, the VM's first start after `devvm network open` deletes them, and `devvm rm` deletes them with the VM's folder |
| `cache/nix-cache/` | the [shared Nix cache](toolchains.md#nix-projects): the packages that VMs with the `nix` layer downloaded from Nix's binary cache, once for all of them | the VMs' proxies and `devvm gc` delete its least recently used files while it takes more than its cap, `nix-cache.size`, which is 10 GiB when it's off, and `devvm gc --nix-cache` deletes all of it |
| `run/` | what running VMs need that isn't one VM's or whose path must be short, such as the QEMU wrapper on Linux hosts, the claims lock, `claims.lock`, which devvm holds while it chooses a new VM's ssh alias or a VM's host ports, the sockets of port forwarders and link sessions, and those that VMs' proxies relay their SSH agents on, which are named by hashes, in `build-ports/` the ssh port of each build VM that's starting, and in `builds/` a folder for each build VM, laid out as a VM's folder is | devvm deletes a VM's sockets when it deletes the VM, a build VM's port once the VM has started or failed to, or, if the devvm that started the VM was killed, the first time it chooses a port 15 minutes later, and a build VM's folder once its image is built, or else when it deletes the build VM |
+8 -2
View File
@@ -17,7 +17,7 @@ devvm -v build base # the same for any command
With `-v`, devvm shows each line on standard error as the log gets it, in place of the status line, and it still writes the log. When a step fails with `-v`, devvm names the log instead of printing its end again. Without `-v`, a status line in a terminal shows the step, how long it has run and the log's latest line, and a step that takes more than a few seconds leaves a line with its time.
- **The log** is `~/.local/share/devvm/logs/runs/<date>-<time>-<pid>.log`, one for each run that runs a command, which only you can read, and devvm keeps the newest 20.
- **The log** is `~/.local/share/devvm/logs/runs/<date>-<time>-<pid>.log`, one for each run that runs a command, which only you can read, and devvm keeps the newest 20, fewer when they take more than 256 MiB together.
- **Each command** appears in it as a `+` line with its arguments, followed by its output, and a numbered step adds a `# [2/5] <step>` line first.
- **Passwords and a VM's proxy key** stay out of it, written as `user:<password>@` and `devvm:<key>@`, including a company proxy's password from your shell's `HTTPS_PROXY` ([the run log](../internals/overview.md#the-run-log)).
@@ -244,7 +244,13 @@ A stopped VM can give up its port to a VM that starts, and it gets another at it
## A VM won't boot
A Lima VM that doesn't answer over ssh within a minute of starting is stopped. Read its console log before you start it again, because every start overwrites the log. The log is `serialv.log`, or another `serial*.log`, in the VM's folder in devvm's Lima home, which is `~/.local/share/devvm/lima/<vm>/` unless you set `DEVVM_LIMA_HOME` ([Lima's limits](../backends/lima.md#limits)).
A Lima VM that doesn't answer over ssh within a minute of starting is stopped. Read the end of its console log before you start it again, because every start overwrites the log:
```sh
tail -n 100 ~/.local/share/devvm/lima/<vm>/serialv.log
```
The log is `serialv.log`, or another `serial*.log`, in the VM's folder in devvm's Lima home, which is `~/.local/share/devvm/lima/<vm>/` unless you set `DEVVM_LIMA_HOME` ([Lima's limits](../backends/lima.md#limits)). A log that passed 10 MiB while the VM ran has its earlier lines in the same name with `.1` added, and its own start is then a long run of empty bytes, which is why `tail` reads it better than an editor.
## A VM whose creation didn't finish
+6
View File
@@ -200,6 +200,12 @@ type Run struct {
// when that process does. A stopped VM has it too, as its proxy starts
// first. Not a VM's own file: the VM can't write it.
Lifeline string
// Logs are the files the backend's processes write as the VM runs
// that the VM can drive, such as its serial console's, each written
// by its program at its own offset or appended to: the VM's proxy
// holds each to its cap while it runs (vmlog.KeepVM), and so does a
// build while its VM runs. None for a backend that writes none.
Logs []string
// ReadOnly is, where the backend can tell (FeatureReadOnlyPaths), the
// host paths its running VM sees through a read-only mount of their
// own, as the process that serves its folders has them now: what its
+4 -2
View File
@@ -54,6 +54,7 @@ type Fake struct {
ShellCmd backend.Command // Shell's answer
Unconfined bool // Running's Confined is false (else: true, or for a VM Start started, whether with NetProxy)
LifelineFile string // Running's Lifeline
LogFiles []string // Running's Logs
Missing []backend.Problem // Problems' answer
Format string // ToolFormat's answer
OriginSteps []image.Step // Origin's answer, for any base
@@ -375,7 +376,8 @@ func (f *machines) Start(_ context.Context, vm vmname.VM, w backend.Want, c back
return nil
}
// Running records the call and returns LifelineFile as its Lifeline, a
// Running records the call and returns LifelineFile as its Lifeline,
// LogFiles as its Logs, a
// running instance's start as its ID ("start-N" for its Nth by Start,
// "start-0" for one preset running; Restart, a start outside Start, gives
// it another) and Confined: false with Unconfined; else, for a VM the
@@ -391,7 +393,7 @@ func (f *machines) Running(_ context.Context, vm vmname.VM) (backend.Run, error)
}
in, ok := f.Instances[vm]
running := ok && in.Status == backend.StatusRunning
r := backend.Run{Lifeline: f.LifelineFile, Confined: running && !f.Unconfined}
r := backend.Run{Lifeline: f.LifelineFile, Logs: f.LogFiles, Confined: running && !f.Unconfined}
if n, ok := f.nets[vm]; ok && r.Confined {
r.Confined = n == backend.NetProxy
}
+3 -1
View File
@@ -64,7 +64,9 @@ func (s ProxyStarter) Start(dir string, c proxy.Config) (*BuildProxy, error) {
if err := state.WriteFile(policy, []byte("# a build: any host, not this machine's own or internal addresses\n**\n")); err != nil {
return nil, err
}
c.Listen, c.Password, c.Policies, c.Log = "127.0.0.1:0", pw, []string{policy}, filepath.Join(dir, "events.jsonl")
// Its own log is its output, which it holds to its limit as a VM's
// proxy does (proxy.Config.ProxyLog).
c.Listen, c.Password, c.Policies, c.Log, c.ProxyLog = "127.0.0.1:0", pw, []string{policy}, filepath.Join(dir, "events.jsonl"), logPath
// The password and the company proxy's credentials go in the config,
// the user's alone: a process's arguments are visible to other users.
config := filepath.Join(dir, configFile)
+2
View File
@@ -48,6 +48,8 @@ func TestProxyStarter(t *testing.T) {
if want := (proxy.Config{
Version: proxy.ConfigVersion, Listen: "127.0.0.1:0", VM: "devvm-img-x", Password: p.Password,
Policies: []string{filepath.Join(dir, "policy")}, Log: filepath.Join(dir, "events.jsonl"), Lifeline: "/run/ha.pid",
// Its own log, held to its limit as a VM's proxy holds its own.
ProxyLog: filepath.Join(dir, "proxy.log"),
Upstream: up, UpstreamUnresolved: true,
}); err != nil || !reflect.DeepEqual(c, want) {
t.Errorf("config = %+v, %v; want %+v", c, err, want)
+16 -1
View File
@@ -9,6 +9,7 @@ import (
"github.com/devvmhq/devvm/internal/proxy"
"github.com/devvmhq/devvm/internal/settings"
"github.com/devvmhq/devvm/internal/shell"
"github.com/devvmhq/devvm/internal/vmlog"
"github.com/devvmhq/devvm/internal/vmname"
)
@@ -55,8 +56,22 @@ func buildUpstream(ctx context.Context, cp *settings.CompanyProxy, n backend.Net
// variable the host sets, and the host's NO_PROXY), and done, which stops
// the proxy and with ok deletes its folder (a failed build keeps its
// logs). Without a company proxy, nothing is started and the scripts get
// nothing.
// nothing. Either way, this process holds the build VM's logs to their
// cap (vmlog.KeepVM) until done, or until ctx ends, as a VM's proxy does
// for a VM it runs for.
func buildProxy(ctx context.Context, l *Lima, vm vmname.VM, n backend.Net) (backend.Confinement, backend.HostProxy, func(ok bool), error) {
c, hp, done, err := companyProxy(ctx, l, vm, n)
if err != nil {
return c, hp, done, err
}
keep, stop := context.WithCancel(ctx)
go vmlog.KeepVM(keep, l.vmLogs(vm))
return c, hp, func(ok bool) { stop(); done(ok) }, nil
}
// companyProxy is buildProxy's proxy: devvm's for the build alone, with
// the company proxy buildUpstream finds; none without one.
func companyProxy(ctx context.Context, l *Lima, vm vmname.VM, n backend.Net) (backend.Confinement, backend.HostProxy, func(ok bool), error) {
c := backend.Confinement{Net: n}
none := func(bool) {}
host, up, err := buildUpstream(ctx, l.Company, n)
+21
View File
@@ -1,6 +1,7 @@
package lima
import (
"cmp"
"encoding/json"
"errors"
"os"
@@ -211,7 +212,20 @@ func recordPinEvent(file string, e backend.PinEvent) {
}
}
// The most the events file takes: pinEventsMax for events, and past it
// pinEventsSlack more for the backend.PinUnrecorded lines that say an
// event wasn't added, which the next check names. A run whose pins keep
// changing can't fill the disk with them.
const (
pinEventsMax = 1 << 20
pinEventsSlack = 64 << 10
)
// errPinEventsFull is addPinEvent's error for an events file at its cap.
var errPinEventsFull = errors.New("the pin events file is full")
// addPinEvent adds e to the events file, as a line of JSON; "" is none.
// A file at its cap takes no more (errPinEventsFull).
func addPinEvent(file string, e backend.PinEvent) error {
if file == "" {
return nil
@@ -221,6 +235,13 @@ func addPinEvent(file string, e backend.PinEvent) error {
if err != nil {
return err
}
limit := int64(pinEventsMax)
if e.What == backend.PinUnrecorded {
limit += pinEventsSlack
}
if fi, err := f.Stat(); err != nil || fi.Size()+int64(len(b))+1 > limit {
return errors.Join(cmp.Or(err, errPinEventsFull), f.Close())
}
_, err = f.Write(append(b, '\n'))
return errors.Join(err, f.Close())
}
+24
View File
@@ -206,6 +206,30 @@ func TestRecordPinEvent(t *testing.T) {
}
}
// The events file has a cap: past it, an event isn't added but marked
// unrecorded, which the next check names, and those marks have a cap of
// their own, so a run whose pins keep changing can't fill the disk.
func TestPinEventsCapped(t *testing.T) {
file := filepath.Join(t.TempDir(), "git-pins.jsonl")
if err := os.WriteFile(file, []byte(strings.Repeat("x", pinEventsMax-10)+"\n"), 0o600); err != nil {
t.Fatal(err)
}
if err := addPinEvent(file, backend.PinEvent{Path: ".git/config", What: platform.PinAgain}); !errors.Is(err, errPinEventsFull) {
t.Errorf("past the cap: %v", err)
}
recordPinEvent(file, backend.PinEvent{Path: ".git/config", What: platform.PinAgain})
b, _ := os.ReadFile(file) //nolint:gosec // the test's own file
if want := `{"path":".git/config","what":"unrecorded"}` + "\n"; !strings.HasSuffix(string(b), "x\n"+want) {
t.Errorf("the file ends %q", b[len(b)-min(len(b), 80):])
}
for range 2 * pinEventsSlack / 40 {
recordPinEvent(file, backend.PinEvent{Path: ".git/config", What: platform.PinAgain})
}
if fi, err := os.Stat(file); err != nil || fi.Size() > pinEventsMax+pinEventsSlack {
t.Errorf("the file: %v, %v", fi, err)
}
}
// What QEMU's process sees through mounts of its own, from its
// mountinfo: its pins, the read-only ones apart, their escapes undone;
// nothing without a QEMU to read.
+23 -2
View File
@@ -18,6 +18,7 @@ import (
"github.com/devvmhq/devvm/internal/msg"
"github.com/devvmhq/devvm/internal/redact"
"github.com/devvmhq/devvm/internal/state"
"github.com/devvmhq/devvm/internal/vmlog"
"github.com/devvmhq/devvm/internal/vmname"
)
@@ -34,6 +35,26 @@ const limaHostName = "host.lima.internal"
// for it.
func (l *Lima) haPIDFile(vm vmname.VM) string { return filepath.Join(l.Dirs.LimaVM(vm), "ha.pid") }
// vmLogs are the logs Lima's processes write in the VM's Lima folder as it
// runs, each started anew by its start and written at its writer's own
// offset (backend.Run.Logs): the serial consoles' (serial.log, and
// serialv.log and serialp.log, Lima's other consoles), which QEMU or
// Apple's Virtualization framework writes and the VM's root reaches
// through /dev/hvc0 and the others, and the hostagent's output, which
// carries QEMU's errors too. The hostagent's error log and the consoles'
// hold the proxy's password at its start (redactLog), and a console's
// again at each reboot inside the VM, which QEMU carries out in place
// (vz ends the VM): the keeper replaces what they gain as they grow
// (redact.In), and a rotation's copy has it replaced too.
func (l *Lima) vmLogs(vm vmname.VM) []string {
dir := l.Dirs.LimaVM(vm)
var out []string
for _, name := range []string{"serial.log", "serialv.log", "serialp.log", "ha.stdout.log", "ha.stderr.log"} {
out = append(out, filepath.Join(dir, name))
}
return out
}
// Start starts a stopped VM as w wants it, confined as c asks, and
// returns once it answers over ssh. A running VM is left as it is.
//
@@ -150,7 +171,7 @@ func (l *machines) redactLog(vm vmname.VM) {
dir := l.Dirs.LimaVM(vm)
serial, _ := filepath.Glob(filepath.Join(dir, "serial*.log"))
for _, path := range append([]string{filepath.Join(dir, "ha.stderr.log")}, serial...) {
if err := redact.File(path); err != nil {
if err := vmlog.Redact(path); err != nil {
l.Warn(msg.LimaLogUnredacted(path, err.Error()).Because(err))
}
}
@@ -439,7 +460,7 @@ func (l *machines) recordStart(vm vmname.VM, n backend.Net) error {
// Start started with NetProxy (recordStart): anything else (limactl
// start) is a new hostagent, unconfined.
func (l *machines) Running(_ context.Context, vm vmname.VM) (backend.Run, error) {
r := backend.Run{Lifeline: l.haPIDFile(vm)}
r := backend.Run{Lifeline: l.haPIDFile(vm), Logs: l.vmLogs(vm)}
fi, err := os.Stat(r.Lifeline)
if errors.Is(err, os.ErrNotExist) {
return r, nil
+39 -1
View File
@@ -21,6 +21,7 @@ import (
"github.com/devvmhq/devvm/internal/redact"
"github.com/devvmhq/devvm/internal/shell"
"github.com/devvmhq/devvm/internal/state"
"github.com/devvmhq/devvm/internal/vmlog"
)
// envOf returns the value the call's environment gives key, and whether
@@ -1076,6 +1077,36 @@ func TestStartRedactsTheHostagentLog(t *testing.T) {
}
}
// A build without a company proxy has no proxy to hold its VM's logs to
// their cap: the build's own process does, until it's done.
func TestBuildKeepsLogs(t *testing.T) {
l, _, _ := testLima(t, "darwin")
const vm = "devvm-img-0123456789ab"
serial := filepath.Join(l.Dirs.LimaVM(vm), "serialv.log")
if err := os.MkdirAll(filepath.Dir(serial), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(serial, []byte(strings.Repeat("boot\n", vmlog.VMMax/4)), 0o600); err != nil {
t.Fatal(err)
}
_, _, done, err := buildProxy(t.Context(), l, vm, backend.NetNone)
if err != nil {
t.Fatal(err)
}
defer done(true)
for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(20 * time.Millisecond) {
if fi, err := os.Stat(serial); err == nil && fi.Size() == 0 {
break
}
if time.Now().After(deadline) {
t.Fatal("not rotated")
}
}
if fi, err := os.Stat(serial + ".1"); err != nil || fi.Size() > vmlog.VMMax {
t.Errorf(".1: %v, %v", fi, err)
}
}
// Running: the hostagent's pid file is the lifeline, stopped or not; its
// pid and when it was written are the start's ID; and the VM is confined
// while it runs on the hostagent Start started with NetProxy, which runs.
@@ -1083,7 +1114,14 @@ func TestRunning(t *testing.T) {
l, f, _ := testLima(t, "darwin")
f.out["limactl list --json"] = `{"name":"v","status":"Stopped"}`
ha := l.haPIDFile("v")
if r, err := l.Running(t.Context(), "v"); !reflect.DeepEqual(r, backend.Run{Lifeline: ha}) || err != nil {
// The logs Lima writes as the VM runs, which its proxy holds to their
// cap: the serial consoles' and the hostagent's.
dir := l.Dirs.LimaVM("v")
logs := []string{
filepath.Join(dir, "serial.log"), filepath.Join(dir, "serialv.log"), filepath.Join(dir, "serialp.log"),
filepath.Join(dir, "ha.stdout.log"), filepath.Join(dir, "ha.stderr.log"),
}
if r, err := l.Running(t.Context(), "v"); !reflect.DeepEqual(r, backend.Run{Lifeline: ha, Logs: logs}) || err != nil {
t.Errorf("never started: %+v, %v", r, err)
}
if err := os.MkdirAll(l.Dirs.LimaVM("v"), 0o700); err != nil {
+5 -1
View File
@@ -8,6 +8,7 @@ import (
"github.com/devvmhq/devvm/internal/netpolicy"
"github.com/devvmhq/devvm/internal/paths"
"github.com/devvmhq/devvm/internal/proxy"
"github.com/devvmhq/devvm/internal/vmlog"
)
// newProxyCmd is devvm _proxy: one VM's proxy, run with
@@ -16,7 +17,8 @@ import (
// log lines are data, written to devvm's stdout and stderr. Its built-in
// policies (its config's) come from devvm's own files in the binary, its
// secrets' values from devvm's store, looked up in this process, and the
// logins it captures go there too.
// logins it captures go there too. It holds the logs the VM's backend
// writes as the VM runs to their cap (vmlog.KeepVM).
func newProxyCmd(a *app) *cobra.Command {
u := a.u
return &cobra.Command{
@@ -37,6 +39,8 @@ func newProxyCmd(a *app) *cobra.Command {
FS: assets.FS, // the built-in policies, read from the binary
Secret: store.Get,
Capture: netpolicy.Capturer{Dirs: d, Secrets: store},
// The VM's backend's logs, held to their cap while the VM runs.
KeepLogs: vmlog.KeepVM,
})
}
if err != nil {
+2 -1
View File
@@ -11,6 +11,7 @@ import (
"testing"
"github.com/devvmhq/devvm/internal/agentlogin"
"github.com/devvmhq/devvm/internal/backend"
"github.com/devvmhq/devvm/internal/msg"
"github.com/devvmhq/devvm/internal/proxy"
"github.com/devvmhq/devvm/internal/redact"
@@ -33,7 +34,7 @@ func TestCapturer(t *testing.T) {
}
for _, vm := range []*state.VM{st, newVM(t, d, "devvm-plain-0123456789abc4", "base")} {
for _, tier := range []Tier{TierAllowlist, TierInternet, TierNone, TierOpen} {
cfg, err := p.config(vm, tier, redact.NewSecret("k3y"), "", common{})
cfg, err := p.config(vm, tier, redact.NewSecret("k3y"), backend.Run{}, common{})
if err != nil || !reflect.DeepEqual(cfg.Captures, all) {
t.Errorf("%s, %s: captures %+v, %v", vm.Name(), tier, cfg.Captures, err)
}
+4 -1
View File
@@ -454,6 +454,7 @@ func TestPrepare(t *testing.T) {
p, f := testProxy(t, d)
lima := backendtest.New("lima", nil)
lima.LifelineFile = "/lima/vm/ha.pid"
lima.LogFiles = []string{"/lima/vm/serial.log", "/lima/vm/ha.stderr.log"}
var excluded []string
p.OS = "darwin"
p.ExcludeFromBackup = func(_ context.Context, dir string) error { excluded = append(excluded, dir); return nil }
@@ -514,7 +515,9 @@ func TestPrepare(t *testing.T) {
BuiltinPolicies: []string{"layers/base.policy", "shared-tools/node.policy", "shared-tools/claude.policy"},
Policies: []string{d.Policy(), files.Policy(), files.SecretsPolicy()},
Log: files.EventLog(), ProxyLog: files.ProxyLog(), Lifeline: "/lima/vm/ha.pid",
CA: ca.Cert(), CAKey: ca.Key(), CANext: ca.NextCert(), CANextKey: ca.NextKey(),
// The logs its backend writes as it runs, which the proxy holds to their cap.
VMLogs: []string{"/lima/vm/serial.log", "/lima/vm/ha.stderr.log"},
CA: ca.Cert(), CAKey: ca.Key(), CANext: ca.NextCert(), CANextKey: ca.NextKey(),
Secrets: files.Secrets(), Captures: agentlogin.Endpoints(),
// Its links' list: in its run folder, devvm's alone.
Links: files.LinkList(), LinkSockets: d.Run(),
+5 -4
View File
@@ -280,7 +280,7 @@ func prepare(ctx context.Context, p *Proxy, b backend.Backend, st *state.VM, run
// start gets a new one. A running VM's proxy starts again, on the same
// port, when its config would differ from the one it started with
// (stale).
cfg, err := p.config(st, tier, key, run.Lifeline, sh)
cfg, err := p.config(st, tier, key, run, sh)
if err != nil {
return none, false, err
}
@@ -338,7 +338,8 @@ func (p *Proxy) secretsReady(ctx context.Context, st *state.VM) error {
// config is the config the VM's proxy would start with now, on tier t,
// listening on the proxy port the VM has (none: port 0), with its key
// (the password) and following its lifeline. It holds everything that,
// (the password), following the lifeline of its run, and holding the
// logs its backend writes to their cap (Run.Logs). It holds everything that,
// changed, starts a running VM's proxy again: its tier and policies
// (tools added or removed, a layer of the user's), devvm's binary (an
// upgrade, which may change the built-in policies' rules), the VM's CAs
@@ -348,7 +349,7 @@ func (p *Proxy) secretsReady(ctx context.Context, st *state.VM) error {
// (shared), and the shared Nix cache's cap. Every tier's proxy has the
// VM's CAs and its secrets: an open VM's applies no rules, but still puts
// its secrets in.
func (p *Proxy) config(st *state.VM, t Tier, key redact.Secret, lifeline string, sh common) (proxy.Config, error) {
func (p *Proxy) config(st *state.VM, t Tier, key redact.Secret, run backend.Run, sh common) (proxy.Config, error) {
vm, files := st.Name(), p.Dirs.VM(st.Name())
ca := files.CA()
set := Policies(p.Dirs, vm, t, image.Name(st.Image), tools.Names(st))
@@ -364,7 +365,7 @@ func (p *Proxy) config(st *state.VM, t Tier, key redact.Secret, lifeline string,
c := proxy.Config{
Listen: listenOn(pp.Host.Proxy), VM: vm, Password: key,
BuiltinPolicies: set.Builtin, Policies: set.Files, DenyPolicies: set.Denies, Open: t == TierOpen,
Log: files.EventLog(), ProxyLog: files.ProxyLog(), Lifeline: lifeline,
Log: files.EventLog(), ProxyLog: files.ProxyLog(), Lifeline: run.Lifeline, VMLogs: run.Logs,
UpstreamCAs: string(cas.Bundle()), Upstream: upstream,
Links: files.LinkList(), LinkSockets: p.Dirs.Run(),
DevvmSHA256: bin,
+8
View File
@@ -0,0 +1,8 @@
//go:build !darwin && !linux
package platform
import "os"
// DataStart is where f's data starts: 0 on this system, which can't tell.
func DataStart(*os.File) int64 { return 0 }
+43
View File
@@ -0,0 +1,43 @@
package platform
import (
"os"
"path/filepath"
"runtime"
"testing"
)
// DataStart: 0 for a file without a hole; past a hole at a file's start,
// at most where its data starts (a file system that can't tell says 0);
// a file that's all hole, its length or 0.
func TestDataStart(t *testing.T) {
t.Parallel()
dir := t.TempDir()
open := func(name string, write func(f *os.File) error) *os.File {
t.Helper()
f, err := os.OpenFile(filepath.Join(dir, name), os.O_RDWR|os.O_CREATE, 0o600) //nolint:gosec // the test's own file
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = f.Close() })
if err := write(f); err != nil {
t.Fatal(err)
}
return f
}
plain := open("plain.log", func(f *os.File) error { _, err := f.WriteString("boot\n"); return err })
if n := DataStart(plain); n != 0 {
t.Errorf("a file without a hole: %d", n)
}
const at = 4 << 20
holed := open("holed.log", func(f *os.File) error { _, err := f.WriteAt([]byte("later\n"), at); return err })
// macOS's and Linux's file systems that devvm's folders are on have
// holes, and say where data starts past one.
if n := DataStart(holed); n <= 0 && (runtime.GOOS == "darwin" || runtime.GOOS == "linux") || n < 0 || n > at {
t.Errorf("past a hole: %d", n)
}
empty := open("empty.log", func(f *os.File) error { return f.Truncate(at) })
if n := DataStart(empty); n != 0 && n != at {
t.Errorf("all hole: %d", n)
}
}
+28
View File
@@ -0,0 +1,28 @@
//go:build darwin || linux
package platform
import (
"errors"
"os"
"golang.org/x/sys/unix"
)
// DataStart is where f's data starts, past a hole at its start: a log
// emptied while its writer went on at its own offset holds data only
// from there, and what's before it takes no disk. 0 for a file without
// such a hole, or one whose file system can't tell; f's length for one
// that is all hole.
func DataStart(f *os.File) int64 {
off, err := unix.Seek(int(f.Fd()), 0, unix.SEEK_DATA)
if errors.Is(err, unix.ENXIO) {
if fi, err := f.Stat(); err == nil {
return fi.Size()
}
}
if err != nil || off < 0 {
return 0
}
return off
}
+2 -1
View File
@@ -32,7 +32,7 @@ Once it listens, it says so with the address it listens on (`daemon.Ready`) in t
| File | What |
| --- | --- |
| `config.go` | `Config`, the one config a VM's proxy and a build's run with (`Encode`, `Sum`, `ReadConfig`, `ConfigVersion`), its password a `redact.Secret`, and `configFile`, the config as its file has it, the password a string, which `Encode` writes and `ReadConfig` reads, and `readPrivate`, the checked read of the files devvm writes for the proxy alone (the config, the bindings, the links' list and the CA): a regular file that isn't a symbolic link, at most its cap, as `safefile` reads it (`safefile.ErrNotRegular`, `safefile.ErrTooLong`), owned by the proxy's user and with none of the permission bits it refuses (`ErrNotPrivate`), which `ReadPrivate` gives `internal/secrets` for the list of your secrets |
| `proxy.go` | `Main` and its one flag, `-config`, the proxy's `server`, which `newServer` makes from the config (below), the listener (`serve`), CONNECT and absolute-form handling, the address floor (`egress`, `hostAddrs`, and `Public`, its ranges, which `devvm network lock` leaves out), the log (`Event`, `events`, `AllowRule`: `devvm network log` reads it), the `devvm.proxy` endpoints |
| `proxy.go` | `Main` and its one flag, `-config`, the proxy's `server`, which `newServer` makes from the config (below), the backend's logs kept to their cap (`IO.KeepLogs`, for `vm_logs`), the listener (`serve`), CONNECT and absolute-form handling, the address floor (`egress`, `hostAddrs`, and `Public`, its ranges, which `devvm network lock` leaves out), the log (`Event`, `events`, `AllowRule`: `devvm network log` reads it), the `devvm.proxy` endpoints |
| `host.go` | the one form of a host (`Host`, `NormHost`) that the requests, the SNI check, the rules, the bindings and `NO_PROXY` read hosts in, and that `netpolicy`'s risks and ticks, a secret's `--host`, an MCP server's host, `--from`'s registry and a partial clone's promisor remotes read theirs in too: a host of printable ASCII lowercased, in ASCII alone, with its one trailing dot dropped, and any other left as it is; the host names the proxy takes (`HostOK`, which `agentlogin` checks MCP servers' hosts with too), and a request's host and port (`splitHostPort`). The structure test refuses another copy of it |
| `request.go` | requests by method and path: the one matcher (`match`, `allows` strict for allows and bindings, `denies` broad for denies), the methods (`Methods`, `ParseMethods`) and those a request names besides its own (`overrides`: every override-like header in any spelling, `overrideLike`, and the query's `_method`), path patterns (`PathOK`, `matchPath`), the plain form a path must have (`plainPath`), and judging each forwarded request (`server.judgeRequest`) |
| `policy.go` | the rule syntax and matching (`ValidRule`, `CanonicalRule`, `NarrowRule`, `Narrowable`: `devvm network allow`, `deny` and `rm` take only these), the host's verdict and its requests' (`verdict`, `byRequest`, `judge`); `ReadAllowlist`, a VM's policies read as the proxy reads them, whose `Allows` is the proxy's own decision by its rules, which `devvm network lock` judges a learning VM's hosts with; `ParsePolicy`, the one strict parser of policy files, which `devvm network` and doctor use too: each line that holds more than a comment, with its number and whether it's a rule; the built-in policies are read once (`readBuiltins`), every line a rule, and come first in the union; the user's policy files are re-read when they change, each only as a regular file of at most 1 MiB (`ReadPolicy`, which `devvm network` and doctor read them with too, and `PolicyMax`; one that isn't keeps its last rules, logged once), and each line that isn't a rule is logged and skipped, except one that starts with `!` (`BrokenDeny`), which makes the policy deny everything, as refused blocks naming the file and line, until it's fixed |
@@ -85,6 +85,7 @@ Flags take one dash or two. The proxy has one, `-config`, and everything it runs
| `nix_cache_max` | with `nix_cache`: the cache's cap, in bytes (devvm sets `nix-cache.size`, 10 GiB when it's off; none: `NixCacheDefault`) |
| `links` | the VM's links' list, which `devvm _links` writes (`~/.local/share/devvm/vms/<hash>/run/links.json`): reach each link through its socket, before any rule; a missing list has no links |
| `link_sockets` | with `links`: the folder of the links' sockets, devvm's run folder (`~/.local/share/devvm/run`); without it, no link is reached |
| `vm_logs` | the logs the VM's backend writes as the VM runs, which the VM can drive, such as its serial console's: the proxy, which runs as long as the VM, holds each to its cap through `IO.KeepLogs`, which devvm sets to `vmlog.KeepVM` and which they need |
| `agent`, `agent_socket` | together, absolute: the SSH agent the VM's start forwards, your own or devvm's, and the VM's own socket in devvm's run folder (`~/.local/share/devvm/run/agent-<hash>.sock`) that the proxy relays it on, which the VM's backend forwards instead ([the SSH agent's relay](#the-ssh-agents-relay)); devvm keeps a running VM's as its start set them |
| `devvm_sha256`, `ca_sha256`, `ca_next_sha256` | the SHA-256 of the devvm binary, of the VM's CA certificate and of its next one's: not read by the proxy, there so a new binary or CA changes the config's `Sum` and devvm starts the proxy again |
+7 -2
View File
@@ -61,6 +61,10 @@ type Config struct {
// ProxyLog is the file the proxy's stderr appends to, devvm opens it for the process: the
// proxy's own log lines go through it, rotated past LogLimit by copying.
ProxyLog string `json:"proxy_log,omitempty"`
// VMLogs are the logs the VM's backend writes as the VM runs, which the VM can drive, such as
// its serial console's (backend.Run.Logs): the proxy, which runs as long as the VM, holds
// each to its cap through IO.KeepLogs, required with them.
VMLogs []string `json:"vm_logs,omitempty"`
// Lifeline is the pid file of the VM's hostagent (daemon.Lifeline): the proxy returns once it
// no longer holds the process it followed. "": it runs until it's stopped.
Lifeline string `json:"lifeline,omitempty"`
@@ -145,6 +149,7 @@ type configFile struct {
Open bool `json:"open,omitempty"`
Log string `json:"log,omitempty"`
ProxyLog string `json:"proxy_log,omitempty"`
VMLogs []string `json:"vm_logs,omitempty"`
Lifeline string `json:"lifeline,omitempty"`
CA string `json:"ca,omitempty"`
CAKey string `json:"ca_key,omitempty"`
@@ -171,7 +176,7 @@ func (c Config) file() configFile {
password := c.Password.Reveal() //nolint:forbidigo // proxy.json holds the password: the proxy reads it from there alone
return configFile{
c.Version, c.Listen, c.VM, password, c.BuiltinPolicies, c.Policies, c.DenyPolicies, c.Open,
c.Log, c.ProxyLog, c.Lifeline, c.CA, c.CAKey, c.CANext, c.CANextKey, c.Secrets, c.Captures,
c.Log, c.ProxyLog, c.VMLogs, c.Lifeline, c.CA, c.CAKey, c.CANext, c.CANextKey, c.Secrets, c.Captures,
c.UpstreamCAs, c.Upstream, c.UpstreamUnresolved, c.NixCache, c.NixCacheMax, c.Links, c.LinkSockets,
c.Agent, c.AgentSocket, c.DevvmSHA256, c.CASHA256, c.CANextSHA256,
}
@@ -181,7 +186,7 @@ func (c Config) file() configFile {
func (f configFile) config() Config {
return Config{
f.Version, f.Listen, f.VM, redact.NewSecret(f.Password), f.BuiltinPolicies, f.Policies, f.DenyPolicies, f.Open,
f.Log, f.ProxyLog, f.Lifeline, f.CA, f.CAKey, f.CANext, f.CANextKey, f.Secrets, f.Captures,
f.Log, f.ProxyLog, f.VMLogs, f.Lifeline, f.CA, f.CAKey, f.CANext, f.CANextKey, f.Secrets, f.Captures,
f.UpstreamCAs, f.Upstream, f.UpstreamUnresolved, f.NixCache, f.NixCacheMax, f.Links, f.LinkSockets,
f.Agent, f.AgentSocket, f.DevvmSHA256, f.CASHA256, f.CANextSHA256,
}
+14 -1
View File
@@ -1213,18 +1213,23 @@ type IO struct {
// Capture saves the logins in Config.Captures' replies, in this process (devvm's store of
// agents' logins): required with them.
Capture Capturer
// KeepLogs holds Config.VMLogs to their cap until ctx ends, in this process (devvm's
// vmlog.KeepVM, which rotates them): required with them.
KeepLogs func(ctx context.Context, paths []string)
}
// httpServer is the HTTP server that serves s, its handlers counted by its conns, as run serves it
// and the tests do: a request's headers get 30 seconds and maxHeaderBytes, and a connection
// idleTimeout between requests. Nothing bounds a request's whole time, so an upload, a download or
// a stream takes as long as it does.
// a stream takes as long as it does. Its errors, a handler's panic among them, go to s's own log,
// held to its limit (rotating), not to the process's stderr, outside it.
func httpServer(s *server) *http.Server {
return &http.Server{
Handler: s.conns.handle(s.handler),
ReadHeaderTimeout: 30 * time.Second,
IdleTimeout: idleTimeout,
MaxHeaderBytes: maxHeaderBytes,
ErrorLog: s.log,
// Each request knows its connection, which its first request with the password admits.
ConnContext: func(ctx context.Context, c net.Conn) context.Context { return context.WithValue(ctx, connKey{}, c) },
}
@@ -1265,6 +1270,9 @@ func run(args []string, std IO, tick time.Duration) error {
if len(c.Captures) > 0 && std.Capture == nil {
return errors.New("captures without a capturer")
}
if len(c.VMLogs) > 0 && std.KeepLogs == nil {
return errors.New("the VM's logs without a keeper")
}
return serve(c, std, tick)
}
@@ -1296,6 +1304,11 @@ func serve(c Config, std IO, tick time.Duration) error {
if err != nil {
return err
}
if len(c.VMLogs) > 0 && std.KeepLogs != nil {
ctx, stop := context.WithCancel(context.Background()) //nolint:forbidigo // the proxy's process has no caller: the VM's logs are kept until it ends
defer stop()
go std.KeepLogs(ctx, c.VMLogs)
}
ln, err := net.Listen("tcp", c.Listen) //nolint:noctx // listens for the proxy's whole life
if err != nil {
return err
+50 -2
View File
@@ -1363,6 +1363,36 @@ func writeConfig(t *testing.T, c Config) string {
return f
}
// The VM's requests are served by an http.Server whose errors, a handler's panic among them, go
// to the proxy's own log, held to its limit, never to the process's stderr: the handler that
// panics here is the test's.
func TestHTTPServerLogs(t *testing.T) {
t.Parallel()
s := testServer(t, Config{}, "")
var b syncBuffer
s.log = log.New(&b, "devvm proxy: ", 0)
srv := httpServer(s)
if srv.ErrorLog != s.log {
t.Fatal("not the proxy's own log")
}
srv.Handler = http.HandlerFunc(func(http.ResponseWriter, *http.Request) { panic("a bug") })
ln, err := new(net.ListenConfig).Listen(t.Context(), "tcp", "127.0.0.1:0")
must(t, err)
go func() { _ = srv.Serve(ln) }()
t.Cleanup(func() { _ = srv.Close() })
req, _ := http.NewRequestWithContext(t.Context(), http.MethodGet, "http://"+ln.Addr().String()+"/", nil)
if resp, err := http.DefaultClient.Do(req); err == nil {
_ = resp.Body.Close()
}
for range 100 {
if strings.Contains(b.String(), "devvm proxy: http: panic serving") {
return
}
time.Sleep(20 * time.Millisecond)
}
t.Errorf("log %q", b.String())
}
// Main: -help prints the one flag, -config; bad arguments, a missing config and one that can't run
// are errors, and nothing is served then. The proxy has no other mode: what the host does alone
// (the CA, agents' logins, redaction) isn't reachable from its arguments.
@@ -1388,6 +1418,8 @@ func TestMainRefuses(t *testing.T) {
{"-config", writeConfig(t, Config{Listen: "127.0.0.1:0", Password: redact.NewSecret("k3y"), Secrets: filepath.Join(t.TempDir(), "secrets.json")})},
// The company proxy's password in a secret, without IO.Secret.
{"-config", writeConfig(t, Config{Listen: "127.0.0.1:0", Password: redact.NewSecret("k3y"), Upstream: &Upstream{HTTPS: "http://u@corp:3128", Secret: UpstreamSecret}})},
// The VM's logs without IO.KeepLogs: nothing would hold them to their cap.
{"-config", writeConfig(t, Config{Listen: "127.0.0.1:0", Password: redact.NewSecret("k3y"), VMLogs: []string{filepath.Join(t.TempDir(), "serial.log")}})},
} {
if err := Main(args, std); err == nil {
t.Errorf("%q: no error", args)
@@ -1435,13 +1467,24 @@ func TestMainRuns(t *testing.T) {
errs := &syncBuffer{}
done := make(chan error)
// The VM's logs are kept for as long as the proxy runs.
kept, keptEnd := make(chan []string, 1), make(chan struct{})
keep := func(ctx context.Context, paths []string) {
kept <- paths
<-ctx.Done()
close(keptEnd)
}
serial := filepath.Join(dir, "serial.log")
go func() {
done <- run([]string{"--config", writeConfig(t, Config{
Listen: addr, VM: "devvm-x", Password: redact.NewSecret("k3y"), Lifeline: pidFile, Log: logFile,
Policies: []string{filepath.Join(dir, "missing")}, Links: filepath.Join(dir, "devvm-x.links.json"),
BuiltinPolicies: []string{"layers/base.policy"},
})}, IO{Stdout: io.Discard, Stderr: errs, FS: fstest.MapFS{"layers/base.policy": {Data: []byte("base.test:8443\n")}}}, tick)
BuiltinPolicies: []string{"layers/base.policy"}, VMLogs: []string{serial},
})}, IO{Stdout: io.Discard, Stderr: errs, FS: fstest.MapFS{"layers/base.policy": {Data: []byte("base.test:8443\n")}}, KeepLogs: keep}, tick)
}()
if got := <-kept; !slices.Equal(got, []string{serial}) {
t.Errorf("kept %q", got)
}
pu, _ := url.Parse("http://devvm:k3y@" + addr)
client := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(pu)}}
fetch := func(u string) (int, string, error) {
@@ -1486,6 +1529,11 @@ func TestMainRuns(t *testing.T) {
case <-time.After(10 * time.Second):
t.Fatalf("still running after the hostagent was gone: %s", errs.String())
}
select {
case <-keptEnd:
case <-time.After(10 * time.Second):
t.Error("the VM's logs still kept after the proxy ended")
}
if s := errs.String(); !strings.Contains(s, "devvm proxy: ") || !strings.Contains(s, "listening on "+addr+" for devvm-x") ||
!strings.Contains(s, "hostagent is gone") || !strings.Contains(s, "built-in policy layers/base.policy: 1 rules") {
t.Errorf("stderr = %q", s)
+9 -1
View File
@@ -28,7 +28,11 @@ const LogLimit = 10 << 20
// log (Config.ProxyLog) is also the proxy process's stdout and stderr, which
// devvm opened, where its last error and any crash go: that file is
// copied to <log>.1 and emptied instead, so those writes, appended to
// the same file, reach the current log.
// the same file, reach the current log, and its size is taken from the
// file before each line, so they count too. The proxy's http.Servers
// log their errors through it (ErrorLog). devvm's other logs that a VM
// can drive are internal/vmlog's, which this package, the standard
// library only, doesn't import.
type rotating struct {
mu sync.Mutex
path string
@@ -91,6 +95,10 @@ func (r *rotating) Write(p []byte) (int, error) {
// A failed check keeps writing to the open file: a line kept
// beats a line in the right file.
_ = r.follow()
} else if fi, err := os.Stat(r.path); err == nil {
// A copied log is also the process's stderr: what reached it
// there, an error a library printed, counts too.
r.size = fi.Size()
}
if r.size > 0 && r.size+int64(len(p)) > r.limit {
// A failed rotation keeps writing to the log as it is: a line
+8
View File
@@ -207,4 +207,12 @@ func TestRotateCopies(t *testing.T) {
t.Errorf("%s: mode %v", filepath.Base(p), m)
}
}
// What reached the log as stderr counts toward its limit: the next
// line, which its own lines alone would leave under it, rotates it.
if _, err := r.Write([]byte("x\n")); err != nil {
t.Fatal(err)
}
if a, b := readLog(t, path+".1"), readLog(t, path); a != "failed upstream\ndevvm: the last error\n" || b != "x\n" {
t.Errorf("after stderr: .1 %q, log %q", a, b)
}
}
+156 -19
View File
@@ -2,7 +2,8 @@
// password in any URL's user info, such as a company proxy's in the shell's HTTPS_PROXY, with a
// scheme or without one (user:password@host:port). String takes them out of a line on its way to
// devvm's run log, and Split says how much of a line still to be ended a writer may write
// first; File takes them out of a log another program keeps writing (Lima's hostagent's). Secret
// first; In takes them out of a log another program keeps writing (Lima's hostagent's and
// consoles'), as it grows, and Unended out of the cut end of a copy of one. Secret
// (secret.go) is the type of every such value in devvm's own code, which never prints as itself.
package redact
@@ -10,7 +11,6 @@ import (
"bytes"
"errors"
"io"
"os"
"regexp"
"strings"
)
@@ -19,7 +19,8 @@ import (
// URL, which lets a process act as that VM or build.
var proxyKey = regexp.MustCompile(`devvm:([0-9a-f]{32,64})@`)
// urlPassword is the password in a URL's user info (scheme://user:password@).
// urlPassword is the password in a URL's user info (scheme://user:password@), of any length, as a
// token in a URL can run to kilobytes.
var urlPassword = regexp.MustCompile(`(?i)\b([a-z][a-z0-9+.-]*://[^\s/:@"'` + "`" + `]*):([^\s@/?#]+)@`)
// barePassword is the password in a proxy URL without a scheme (user:password@host:port), as in
@@ -28,6 +29,12 @@ var urlPassword = regexp.MustCompile(`(?i)\b([a-z][a-z0-9+.-]*://[^\s/:@"'` + "`
// mailto: link) isn't taken for one.
var barePassword = regexp.MustCompile(`(^|[\s"'` + "`" + `=(,;<\[{])([^\s/:@"'` + "`" + `=(,;<\[{]+):([^\s@/?#]+)@(?:[a-zA-Z0-9.-]+|\[[0-9a-fA-F:.]+\]):[0-9]{1,5}\b`)
// MatchMax is how much of what a look at a log that grows (In) read before it reads again, from
// the start of a line not yet ended when that's within it: a secret whose end came since is
// found whole when it's shorter, and a longer one has its part in what's read starred instead
// (Leading).
const MatchMax = 64 << 10
// secrets are the patterns whose last group is a secret, in the order String applies them: the
// proxy key, then the passwords.
func secrets() []*regexp.Regexp {
@@ -88,29 +95,159 @@ func Split(b []byte, tail int) int {
return i
}
// fileMax is as much of a log as File reads: a hostagent's log right after its start is far
// smaller.
const fileMax = 64 << 20
// Look is how far a log that grows has been redacted (In): Line is where its last line not yet
// ended starts, and Read how far it was read. Cut says that what's at Line may go on a secret
// whose start went before it, such as one a rotation's copy took the start of (Unended). The zero
// Look is a log not read yet.
type Look struct {
Line, Read int64
Cut bool
}
// File overwrites each proxy key and URL password in the log at path with as many "*", in place:
// the file keeps its length and every other byte, so a program that is still writing to it at
// its own offset (Lima's hostagent, which opened it without O_APPEND) goes on where it was. A
// missing file has nothing to redact.
func File(path string) error {
f, err := os.OpenFile(path, os.O_RDWR, 0) //nolint:gosec // a log in devvm's own folders
if errors.Is(err, os.ErrNotExist) {
return nil
// leading is the start of b as the rest of a secret whose start went before it: past any zeros
// (a hole), the run of what a password or a key can hold, up to its "@". It returns the run's
// span, which holds a secret's rest only when ended says an "@" ends it, and open when b ends
// first.
func leading(b []byte) (span [2]int, ended, open bool) {
start := len(b) - len(bytes.TrimLeft(b, "\x00"))
i := start
for i < len(b) && !bytes.ContainsRune([]byte(" \t\r\n\f\v@/?#"), rune(b[i])) {
i++
}
switch {
case i == len(b):
return [2]int{start, i}, false, true
case b[i] == '@' && i > start:
return [2]int{start, i}, true, false
}
return [2]int{start, i}, false, false
}
// File is a log's file that In redacts in place: what it reads, and writes "*" over.
type File interface {
io.ReaderAt
io.WriterAt
}
// In overwrites each proxy key and URL password in the log f, size bytes long, with as many "*",
// in place, in what it gained since at: the file keeps its length and every other byte, so a
// program that is still writing to it at its own offset (Lima's hostagent, which opened it
// without O_APPEND) goes on where it was. It reads from the start of the line not yet ended at
// the last look, but no earlier than MatchMax before where that look stopped, so a long line that
// never ends is read once, not at every look, and reads at most limit bytes. It returns the look
// to start from next. A secret never spans a line, and only a line with an "@" can hold one. A
// look past the log's end, as after the log was emptied and started again, starts at 0.
func In(f File, size int64, at Look, limit int64) (Look, error) {
if at.Line > size || at.Read > size {
at = Look{}
}
from := max(at.Line, at.Read-MatchMax)
b := make([]byte, min(size-from, limit))
n, err := f.ReadAt(b, from)
b = b[:n]
if errors.Is(err, io.EOF) {
err = nil
}
found := lineSpans(b)
// What's read starts inside a line, past a secret's start that a look no longer reads, or
// after one a rotation cut: the rest of a secret there is starred once its "@" comes.
cut := at.Cut || from > at.Line
open := false
if cut {
span, ended, more := leading(b)
if ended {
found = append(found, span)
}
open = more
}
if err == nil {
err = overwrite(offsetWriter{f, from}, found)
}
if err != nil {
return err
return at, err
}
b, err := io.ReadAll(io.LimitReader(f, fileMax))
if err == nil {
err = overwrite(f, spans(b))
next := Look{Line: at.Line, Read: from + int64(len(b)), Cut: at.Cut && open}
if i := bytes.LastIndexByte(b, '\n'); i >= 0 {
next.Line, next.Cut = from+int64(i)+1, false
}
return errors.Join(err, f.Close())
return next, nil
}
// unendedKey and unendedPassword are the starts of a secret that a line cut before its end can
// hold: a proxy key without its "@" yet, and a URL's password without its "@" yet.
var (
unendedKey = regexp.MustCompile(`devvm:([0-9a-f]{1,64})$`)
unendedPassword = regexp.MustCompile(`(?i)\b[a-z][a-z0-9+.-]*://[^\s/:@"'` + "`" + `]*:([^\s@/?#]+)$`)
)
// Unended overwrites in b, a log's part whose last line may be cut before its end (a rotation's
// copy), the start of a secret at that end, which the patterns can't tell is one until its "@"
// comes: a proxy key's digits, and what follows a URL's user. A company proxy's address without
// a scheme can't be told from other text until its port, and stays. It reports whether it masked
// one, whose rest the log's writer goes on with (Look.Cut).
func Unended(b []byte) (masked bool) {
if len(b) == 0 || b[len(b)-1] == '\n' {
return false
}
last := b[bytes.LastIndexByte(b, '\n')+1:]
for _, re := range []*regexp.Regexp{unendedKey, unendedPassword} {
if m := re.FindSubmatchIndex(last); m != nil {
copy(last[m[2]:m[3]], bytes.Repeat([]byte{'*'}, m[3]-m[2]))
masked = true
}
}
return masked
}
// Bytes is a file in memory, whose part In can redact as it does a log's.
type Bytes []byte
// ReadAt reads b from off.
func (b Bytes) ReadAt(p []byte, off int64) (int, error) {
if off >= int64(len(b)) {
return 0, io.EOF
}
n := copy(p, b[off:])
if n < len(p) {
return n, io.EOF
}
return n, nil
}
// WriteAt writes over b at off, never past its end.
func (b Bytes) WriteAt(p []byte, off int64) (int, error) {
if off+int64(len(p)) > int64(len(b)) {
return 0, io.ErrShortWrite
}
return copy(b[off:], p), nil
}
// lineSpans are the offsets of each secret in b, a line at a time, in the lines with an "@" alone.
func lineSpans(b []byte) [][2]int {
var found [][2]int
for start := 0; start < len(b); {
end := bytes.IndexByte(b[start:], '\n') + 1
if end == 0 {
end = len(b) - start
}
if line := b[start : start+end]; bytes.IndexByte(line, '@') >= 0 {
for _, s := range spans(line) {
found = append(found, [2]int{start + s[0], start + s[1]})
}
}
start += end
}
return found
}
// offsetWriter writes at its offsets plus off.
type offsetWriter struct {
w io.WriterAt
off int64
}
func (o offsetWriter) WriteAt(p []byte, at int64) (int, error) { return o.w.WriteAt(p, o.off+at) }
// spans are the offsets of each secret in b, start and end.
func spans(b []byte) [][2]int {
var out [][2]int
+192 -21
View File
@@ -2,6 +2,8 @@ package redact
import (
"bytes"
"errors"
"io"
"os"
"path/filepath"
"strings"
@@ -26,6 +28,8 @@ func TestString(t *testing.T) {
{"[email protected]:org/repo.git and ssh alice@host -p 22", "[email protected]:org/repo.git and ssh alice@host -p 22"},
{"mailto:[email protected], Contact: [email protected]:25", "mailto:[email protected], Contact: [email protected]:25"},
{"[email protected]:8080 at 10:30", "[email protected]:8080 at 10:30"},
// A password at its bound is found; one past it isn't a password the patterns know.
{"http://u:" + strings.Repeat("p", 512) + "@h", "http://u:<password>@h"},
} {
if got := String(tc.in); got != tc.want {
t.Errorf("String(%q) = %q, want %q", tc.in, got, tc.want)
@@ -139,48 +143,215 @@ func FuzzSplit(f *testing.F) {
})
}
// File overwrites each secret with as many stars in place, so the file keeps its length, and a
// writer that still has it open at its own offset, as Lima's hostagent does, goes on where it was.
func TestFile(t *testing.T) {
// In overwrites each secret with as many stars in place, in a real file a writer still has open
// at its own offset, as Lima's hostagent does: the file keeps its length, and the writer goes on
// where it was.
func TestInFile(t *testing.T) {
t.Parallel()
pass := "e2e-not-a-secret" //nolint:gosec // a fake password
key := strings.Repeat("fedcba9876543210", 4)
path := filepath.Join(t.TempDir(), "ha.stderr.log")
before := `level=info msg="Replacing \"HTTPS_PROXY\" value ` + "`http://alice:" + pass + "@127.0.0.1:3128`" + `"` + "\n" +
"proxy http://devvm:" + key + "@192.168.5.2:3129 kept\nno user https://host:443/a@b\n"
w, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0o600) //nolint:gosec // the test's own file
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0o600) //nolint:gosec // the test's own file
if err != nil {
t.Fatal(err)
}
defer func() { _ = w.Close() }()
if _, err := w.WriteString(before); err != nil {
defer func() { _ = f.Close() }()
if _, err := f.WriteString(before); err != nil {
t.Fatal(err)
}
if err := File(path); err != nil {
t.Fatal(err)
at, err := In(f, int64(len(before)), Look{}, 1<<20)
if err != nil || at != (Look{Line: int64(len(before)), Read: int64(len(before))}) {
t.Fatalf("look %+v, %v", at, err)
}
if _, err := w.WriteString("later\n"); err != nil {
if _, err := f.WriteString("later\n"); err != nil {
t.Fatal(err)
}
want := strings.NewReplacer(pass, strings.Repeat("*", len(pass)), key, strings.Repeat("*", len(key))).Replace(before) + "later\n"
b, err := os.ReadFile(path) //nolint:gosec // the test's own file
if b, _ := os.ReadFile(path); string(b) != want { //nolint:gosec // the test's own file
t.Errorf("got %q\nwant %q", b, want)
}
}
// counting is a log in memory that counts what's read of it.
type counting struct {
Bytes
read int
}
func (c *counting) ReadAt(p []byte, off int64) (int, error) {
n, err := c.Bytes.ReadAt(p, off)
c.read += n
return n, err
}
// In redacts a log as it grows: each look takes the lines from where the last one left off, so
// a secret the writer hadn't ended yet is found once its line is, one written again later is
// found too, and a log emptied and started again is read from its start.
func TestIn(t *testing.T) {
t.Parallel()
pass := "e2e-not-a-secret" //nolint:gosec // a fake password
log := Bytes("[ OK ] boot\n+ echo HTTPS_PROXY=http://devvm:" + pass[:5])
at, err := In(log, int64(len(log)), Look{}, 1<<20)
if err != nil || at.Line != int64(len("[ OK ] boot\n")) || at.Read != int64(len(log)) {
t.Fatalf("look %+v, %v", at, err)
}
log = append(log, pass[5:]+"@192.168.5.2:3129\nlater\n"...)
if at, err = In(log, int64(len(log)), at, 1<<20); err != nil || at.Line != int64(len(log)) {
t.Fatalf("look %+v of %d, %v", at, len(log), err)
}
if strings.Contains(string(log), pass) || !strings.Contains(string(log), strings.Repeat("*", len(pass))) {
t.Errorf("after the line ended: %q", log)
}
// A reboot writes it again, past where the last look ended.
log = append(log, "+ echo HTTPS_PROXY=http://devvm:"+pass+"@192.168.5.2:3129\n"...)
if _, err := In(log, int64(len(log)), at, 1<<20); err != nil || strings.Contains(string(log), pass) {
t.Errorf("written again: %q, %v", log, err)
}
// Emptied and started again: from its start.
log = Bytes("x http://a:" + pass + "@h:1\n")
if _, err := In(log, int64(len(log)), Look{Line: 1 << 10, Read: 1 << 10}, 1<<20); err != nil || strings.Contains(string(log), pass) {
t.Errorf("started again: %q, %v", log, err)
}
// At most limit bytes a look, the next going on from there.
log = Bytes(strings.Repeat("y", 100))
if at, err := In(log, int64(len(log)), Look{}, 10); err != nil || at != (Look{Read: 10}) {
t.Errorf("limited: %+v, %v", at, err)
}
}
// A line that never ends is read once, not at every look: a look reads again only MatchMax of
// what came before, so a VM can't make each look cost its whole line, and a secret whose "@"
// comes in what's new is still found whole.
func TestInLongLine(t *testing.T) {
t.Parallel()
pass := "e2e-not-a-secret" //nolint:gosec // a fake password
c := &counting{Bytes: Bytes("@" + strings.Repeat("x", 1<<20) + " http://u:" + pass)}
at, err := In(c, int64(len(c.Bytes)), Look{}, 64<<20)
if err != nil || at.Line != 0 {
t.Fatalf("look %+v, %v", at, err)
}
c.read = 0
if again, err := In(c, int64(len(c.Bytes)), at, 64<<20); err != nil || again != at || c.read > MatchMax {
t.Errorf("a still line: look %+v, read %d bytes, %v", again, c.read, err)
}
c.Bytes = append(c.Bytes, "@proxy:3128"...)
c.read = 0
if _, err := In(c, int64(len(c.Bytes)), at, 64<<20); err != nil || c.read > MatchMax+20 || strings.Contains(string(c.Bytes), pass) {
t.Errorf("its end: read %d bytes, %v, ends %q", c.read, err, c.Bytes[len(c.Bytes)-40:])
}
}
// Long secrets, such as a registry's token in an index URL, are found whatever their length: by
// String in the run log, and by In in a log that grows, the line's end coming at a later look.
func TestLongSecrets(t *testing.T) {
t.Parallel()
for _, tc := range []struct{ user, pass int }{{5, 513}, {5, 1000}, {5, 2048}, {600, 40}} {
user, pass := strings.Repeat("u", tc.user), strings.Repeat("p", tc.pass-1)+"Z"
line := "index-url = https://" + user + ":" + pass + "@pkgs.example/simple\n"
if got := String(line); strings.Contains(got, pass) || !strings.Contains(got, user+":"+passwordStandIn+"@") {
t.Errorf("String, user %d, password %d: %.80q", tc.user, tc.pass, got)
}
log := Bytes(line[:len(line)-len("@pkgs.example/simple\n")])
at, err := In(log, int64(len(log)), Look{}, 1<<20)
if err != nil {
t.Fatal(err)
}
log = append(log, "@pkgs.example/simple\n"...)
if _, err := In(log, int64(len(log)), at, 1<<20); err != nil || strings.Contains(string(log), pass) {
t.Errorf("In, user %d, password %d: %v", tc.user, tc.pass, err)
}
}
}
// A look that reads a long line from MatchMax before where the last one stopped, past the start
// of a secret, stars the rest of it up to its "@", as it does what a rotation left after a cut
// (Look.Cut); a run that the "@" doesn't end is left, and one still open is looked at again.
func TestInLeading(t *testing.T) {
t.Parallel()
pass := strings.Repeat("q", MatchMax+100)
log := Bytes("@" + strings.Repeat("x", 2*MatchMax) + " http://u:" + pass)
at, err := In(log, int64(len(log)), Look{}, 1<<30)
if err != nil {
t.Fatal(err)
}
if string(b) != want {
t.Errorf("got %q\nwant %q", b, want)
log = append(log, "@h\n"...)
if _, err := In(log, int64(len(log)), at, 1<<30); err != nil || strings.Contains(string(log), pass[:MatchMax]) {
t.Errorf("past MatchMax: %v, the password's last part left", err)
}
// Once more changes nothing; a file without secrets, or none, is left alone.
if err := File(path); err != nil {
t.Fatal(err)
// After a cut: zeros of a hole, then a key's rest, still open, then ended.
tail := "\x00\x00" + "89abcdef"
log = Bytes(tail)
at, err = In(log, int64(len(log)), Look{Cut: true}, 1<<20)
if err != nil || !at.Cut || string(log) != tail {
t.Fatalf("open: %+v, %v, %q", at, err, log)
}
if b2, _ := os.ReadFile(path); string(b2) != want { //nolint:gosec // the test's own file
t.Errorf("again: %q", b2)
log = append(log, "@192.168.5.2:3129\nnext\n"...)
if at, err = In(log, int64(len(log)), at, 1<<20); err != nil || at.Cut || strings.Contains(string(log), "89abcdef") {
t.Errorf("ended: %+v, %v, %q", at, err, log)
}
if err := File(filepath.Join(t.TempDir(), "missing.log")); err != nil {
t.Errorf("a missing file: %v", err)
// A run that something else ends isn't a secret's rest.
log = Bytes("plain words@ and more\n")
if _, err := In(log, int64(len(log)), Look{Cut: true}, 1<<20); err != nil || string(log) != "plain words@ and more\n" {
t.Errorf("a word: %q", log)
}
if err := File(t.TempDir()); err == nil {
t.Error("a folder: no error")
}
// Unended masks the start of a secret at a copy's cut end, which the patterns can't tell yet;
// a copy that ends a line is left as it is.
func TestUnended(t *testing.T) {
t.Parallel()
for in, want := range map[string]string{ //nolint:gosec // fake passwords
"a\nproxy http://devvm:0123abcd": "a\nproxy http://devvm:********",
"a\nHTTPS_PROXY=http://alice:s3cr": "a\nHTTPS_PROXY=http://alice:****",
"a\nhttp://devvm:0123abcd@h:1\n": "a\nhttp://devvm:0123abcd@h:1\n",
"plain text, cut": "plain text, cut",
"": "",
} {
b := []byte(in)
if Unended(b); string(b) != want {
t.Errorf("Unended(%q) = %q, want %q", in, b, want)
}
}
}
// Bytes reads and writes within itself, as a file of its length does.
func TestBytes(t *testing.T) {
t.Parallel()
b := Bytes("abc")
p := make([]byte, 5)
if n, err := b.ReadAt(p, 1); n != 2 || !errors.Is(err, io.EOF) {
t.Errorf("ReadAt past the end: %d, %v", n, err)
}
if n, err := b.ReadAt(p[:2], 0); n != 2 || err != nil {
t.Errorf("ReadAt: %d, %v", n, err)
}
if n, err := b.ReadAt(p, 3); n != 0 || !errors.Is(err, io.EOF) {
t.Errorf("ReadAt at the end: %d, %v", n, err)
}
if _, err := b.WriteAt([]byte("xyz"), 1); err == nil {
t.Error("WriteAt past the end")
}
if _, err := b.WriteAt([]byte("x"), 1); err != nil || string(b) != "axc" {
t.Errorf("WriteAt: %q, %v", b, err)
}
}
type failingWriterAt struct{}
func (failingWriterAt) WriteAt([]byte, int64) (int, error) { return 0, os.ErrPermission }
// A write that fails stops the overwrite with its error.
func TestOverwriteFails(t *testing.T) {
t.Parallel()
if err := overwrite(offsetWriter{failingWriterAt{}, 5}, [][2]int{{0, 3}}); err == nil {
t.Error("no error")
}
if _, err := In(struct {
io.ReaderAt
io.WriterAt
}{Bytes("http://a:b@h\n"), failingWriterAt{}}, 13, Look{}, 100); err == nil {
t.Error("In: no error")
}
}
+1 -1
View File
@@ -50,7 +50,7 @@ func TestSecret(t *testing.T) {
}
}
if NewSecret("") != (Secret{}) || !NewSecret(" x ").TrimSpace().Empty() && NewSecret(" x ").TrimSpace().Reveal() != "x" ||
!NewSecret(" ").TrimSpace().Empty() || (Secret{}).Reveal() != "" {
!NewSecret(" ").TrimSpace().Empty() || (Secret{}).Reveal() != "" || (Secret{}).TrimSpace() != (Secret{}) {
t.Error("NewSecret, TrimSpace or Reveal of the zero Secret")
}
if got := fmt.Sprint(s) + s.String() + s.GoString(); got != Hidden+Hidden+Hidden {
+6
View File
@@ -32,11 +32,17 @@ type Opts struct {
Follow bool
// OneLink refuses a file with another hard link, which a link in another folder could change.
OneLink bool
// Write opens it for writing too, as a log that's redacted and emptied in place is: what's
// checked is the same.
Write bool
}
// flags are the open flags for o.
func (o Opts) flags() int {
f := os.O_RDONLY | noBlock
if o.Write {
f = os.O_RDWR | noBlock
}
if !o.Follow {
f |= noFollow
}
+35
View File
@@ -113,6 +113,41 @@ func TestRead(t *testing.T) {
}
// An error names the file it's about.
// Write opens a regular file to write it too, and refuses a link at the path's end, a FIFO
// without waiting on it, and a folder, as a read does.
func TestOpenWrite(t *testing.T) {
t.Parallel()
dir := t.TempDir()
path := filepath.Join(dir, "a.log")
if err := os.WriteFile(path, []byte("abc"), 0o600); err != nil {
t.Fatal(err)
}
f, err := Open(path, Opts{Write: true})
if err != nil {
t.Fatal(err)
}
if _, err := f.WriteAt([]byte("x"), 1); err != nil {
t.Errorf("write: %v", err)
}
_ = f.Close()
if b, _ := os.ReadFile(path); string(b) != "axc" { //nolint:gosec // the test's own file
t.Errorf("file %q", b)
}
link, fifo := filepath.Join(dir, "link"), filepath.Join(dir, "fifo")
if err := os.Symlink(path, link); err != nil {
t.Fatal(err)
}
if err := syscall.Mkfifo(fifo, 0o600); err != nil {
t.Fatal(err)
}
for _, p := range []string{link, fifo, dir} {
if f, err := Open(p, Opts{Write: true}); err == nil {
_ = f.Close()
t.Errorf("%s: opened", p)
}
}
}
func TestReadErrorNamesFile(t *testing.T) {
t.Parallel()
dir, _ := folder(t)
+3 -1
View File
@@ -332,6 +332,8 @@ func devvmExecSites() map[string]string {
// what waits for them to end, or detached and why nothing does.
func devvmGoroutineSites() map[string]string {
return map[string]string{
"internal/backend/lima/buildproxy.go: buildProxy": detached + "the build VM's logs' keeper (vmlog.KeepVM), which the build's done or the end of its context stops",
"internal/vmlog/rotate.go: Keep": "Keep's wg.Wait, each log's look ending with ctx",
"internal/backend/lima/packages.go: sendPackages": "sendPackages, on sent, once the VM's tar has stopped reading and the pipe is closed",
"internal/backend/lima/packages.go: takePackages": "takePackages, on taken, once the VM's tar has ended and the pipe is closed",
"internal/backend/lima/qemu.go: Connect": detached + "QEMU's side to the connection, which ends as Connect closes it; devvm _qemu connect exits once Connect returns",
@@ -347,7 +349,7 @@ func devvmGoroutineSites() map[string]string {
"internal/platform/pin_linux.go: WatchFolders": "WatchFolders's stop, which closes the inotify file its read in Go's poller is on",
"internal/platform/pinrun_linux.go: runChild": "runChild, on passed, once it has closed the signals' channel",
"internal/platform/pinrun_linux.go: RunPinned": "keep, which returns the child's end that it sends",
"internal/proxy/proxy.go: serve": detached + "the lifeline's watch, which runs for the proxy's life and ends it once the VM's hostagent is gone, and the SSH agent relay's accept loop, which ends once serve's deferred close closes its listener",
"internal/proxy/proxy.go: serve": detached + "the lifeline's watch, which runs for the proxy's life and ends it once the VM's hostagent is gone, the SSH agent relay's accept loop, which ends once serve's deferred close closes its listener, and the VM's logs' keeper (IO.KeepLogs), which serve's deferred stop ends",
"internal/proxy/agent.go: agentRelay.serve": detached + "each connection's relay, which ends when either side closes, when the client sends no whole request within agentIdle, or with the proxy; nothing waits for one waiting on the agent's answer",
"internal/proxy/splice.go: splice": "splice, on done, once both directions have ended",
"internal/proxy/proxy.go: whileHeard": "whileHeard's cancel, which handleHTTP defers, so it ends with the request's handler",
+78 -14
View File
@@ -15,6 +15,7 @@ import (
"sync"
"time"
"github.com/devvmhq/devvm/internal/daemon"
"github.com/devvmhq/devvm/internal/msg"
"github.com/devvmhq/devvm/internal/redact"
"github.com/devvmhq/devvm/internal/state"
@@ -86,13 +87,46 @@ func (s *stream) Write(p []byte) (int, error) {
return len(p), nil
}
// logTo is where a command's output goes: the run log, and while
// verbose, the stream too.
func logTo(u *UI, f *os.File) io.Writer {
// logTo is where a command's output goes: the run log w (its logCap),
// and while verbose, the stream too.
func logTo(u *UI, w io.Writer) io.Writer {
if !verbose(u) {
return f
return w
}
return io.MultiWriter(f, &stream{u: u})
return io.MultiWriter(w, &stream{u: u})
}
// runLogMax is the most one run writes to its log, as a run that lasts,
// such as devvm desktop's, can be made to log without end.
const runLogMax = 128 << 20
// runLogFull is the run log's last line once it's past runLogMax.
const runLogFull = "\ndevvm: truncated: this run wrote more than 128 MiB to its log, and the rest isn't in it\n"
// logCap is the run's log file, held to runLogMax: the write that would
// take it past is dropped, with every one after it, and runLogFull says
// so once.
type logCap struct {
f io.Writer
mu sync.Mutex
n int64
full bool
}
func (c *logCap) Write(p []byte) (int, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.full {
return len(p), nil
}
if c.n+int64(len(p)) > runLogMax {
c.full = true
_, err := io.WriteString(c.f, runLogFull)
return len(p), err
}
n, err := c.f.Write(p)
c.n += int64(n)
return n, err
}
// logPath is the run's log, "" before it's opened.
@@ -103,12 +137,13 @@ func (u *UI) logPath() string {
}
// openLog opens the run's log, the first time in a run, in the run logs
// folder (owner-only), and deletes all but the newest logs there.
func (u *UI) openLog() *os.File {
// folder (owner-only), and deletes all but the newest logs there
// (pruneLogs).
func (u *UI) openLog() *logCap {
u.log.Lock()
defer u.log.Unlock()
if u.log.f != nil {
return u.log.f
return u.log.cap
}
dir, err := u.runLogs()
if err != nil {
@@ -121,9 +156,9 @@ func (u *UI) openLog() *os.File {
if err != nil {
u.die(msg.RunLogFailed(dir, err.Error()).Because(err))
}
u.log.f, u.log.path = f, f.Name()
u.log.f, u.log.path, u.log.cap = f, f.Name(), &logCap{f: f}
pruneLogs(dir, cmp.Or(u.log.keep, keepLogs))
return f
return u.log.cap
}
// KeepRunLogs sets how many run logs are kept, the newest (retention's
@@ -144,28 +179,57 @@ func createLog(dir string, now time.Time, pid int) (*os.File, error) {
return os.OpenFile(filepath.Join(dir, name), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o600) //nolint:gosec // devvm's own folder
}
// pruneLogs deletes all but the newest keep logs in dir.
// runLogsMax is as much as the run logs in the folder take together: past
// it, the oldest go, however many logs.runs keeps, but the newest.
const runLogsMax = 256 << 20
// pruneLogs deletes all but the newest keep logs in dir, and older ones
// past runLogsMax together, but never the newest, nor a log whose run
// still runs (logPID): a background process, or another devvm, writing
// it still, which the system would keep on disk after its name went.
func pruneLogs(dir string, keep int) {
files, _ := filepath.Glob(filepath.Join(dir, "*.log"))
type log struct {
path string
mod time.Time
size int64
}
var logs []log
for _, f := range files {
if fi, err := os.Stat(f); err == nil {
logs = append(logs, log{f, fi.ModTime()})
logs = append(logs, log{f, fi.ModTime(), fi.Size()})
}
}
slices.SortFunc(logs, func(a, b log) int { return b.mod.Compare(a.mod) })
for _, l := range logs[min(keep, len(logs)):] {
var total int64
for i, l := range logs {
total += l.size
if i == 0 || i < keep && total <= runLogsMax {
continue
}
if pid, ok := logPID(l.path); ok && daemon.Alive(pid) {
continue
}
_ = os.Remove(l.path)
}
}
// logPID is the pid of the run that writes the run log at path, from its
// name (createLog's): false for a name of another form. A pid the system
// gave another process since keeps its log until that one ends.
func logPID(path string) (int, bool) {
parts := strings.Split(strings.TrimSuffix(filepath.Base(path), ".log"), "-")
if len(parts) != 3 || len(parts[0]) != len("20060102") || len(parts[1]) != len("150405") {
return 0, false
}
pid, err := strconv.Atoi(parts[2])
return pid, err == nil && pid > 0
}
// LogNote says where the details of slow steps go, once per run.
func (u *UI) LogNote() {
path := u.openLog().Name()
u.openLog()
path := u.logPath()
u.log.Lock()
noted := u.log.noted
u.log.noted = true
+73
View File
@@ -7,6 +7,7 @@ import (
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"testing"
"time"
@@ -341,6 +342,78 @@ func TestKeepsTheLast20Logs(t *testing.T) {
}
}
// Past runLogsMax together, the oldest run logs go however many are
// kept, but never the newest, nor one whose run still runs, read from its
// name.
func TestRunLogsCapped(t *testing.T) {
t.Parallel()
dir := t.TempDir()
old := time.Now().Add(-time.Hour)
// Each a third of runLogsMax long, all of it a hole: no disk taken.
big := func(path string, n int64) {
t.Helper()
writeFile(t, path, "")
if err := os.Truncate(path, n); err != nil {
t.Fatal(err)
}
}
live := fmt.Sprintf("20260101-000000-%d.log", os.Getpid()) // this test's: it runs
names := []string{live, "20260101-000001-999999999.log", "20260101-000002-999999998.log", "20260101-000003-999999997.log", "20260101-000004-999999996.log"}
for i, name := range names {
f := filepath.Join(dir, name)
big(f, runLogsMax/3)
mod := old.Add(time.Duration(i) * time.Minute)
if err := os.Chtimes(f, mod, mod); err != nil {
t.Fatal(err)
}
}
pruneLogs(dir, 20)
kept, _ := filepath.Glob(filepath.Join(dir, "*.log"))
for i, f := range kept {
kept[i] = filepath.Base(f)
}
// The newest three take runLogsMax; the two older go, but the live one.
if want := []string{live, names[2], names[3], names[4]}; !slices.Equal(kept, want) {
t.Errorf("kept %q, want %q", kept, want)
}
// The newest stays even past runLogsMax alone.
single := t.TempDir()
big(filepath.Join(single, names[1]), 2*runLogsMax)
if pruneLogs(single, 20); len(mustGlob(t, single)) != 1 {
t.Error("the newest log went")
}
for name, want := range map[string]int{names[1]: 999999999, "old-5.log": 0, "a-b-c.log": 0, "20260101-000000-x.log": 0} {
if pid, ok := logPID(filepath.Join(dir, name)); pid != want || ok != (want > 0) {
t.Errorf("logPID(%s) = %d, %v", name, pid, ok)
}
}
}
// One run writes at most runLogMax to its log: the write that would pass
// it, and every one after, is dropped, and one line says so.
func TestLogCap(t *testing.T) {
t.Parallel()
var b strings.Builder
c := &logCap{f: &b, n: runLogMax - 4}
for _, s := range []string{"abc\n", "past\n", "more\n"} {
if n, err := c.Write([]byte(s)); n != len(s) || err != nil {
t.Errorf("Write(%q) = %d, %v", s, n, err)
}
}
if b.String() != "abc\n"+runLogFull {
t.Errorf("log %q", b.String())
}
}
func mustGlob(t *testing.T, dir string) []string {
t.Helper()
m, err := filepath.Glob(filepath.Join(dir, "*.log"))
if err != nil {
t.Fatal(err)
}
return m
}
func TestRunLogFailures(t *testing.T) {
t.Parallel()
u, _, errOut := testUI(t, "")
+1
View File
@@ -89,6 +89,7 @@ type UI struct {
sync.Mutex
path string
f *os.File
cap *logCap // f, held to runLogMax
w *redacting // LogWriter's, made at its first call
noted bool
keep int // run logs kept, the newest; keepLogs when 0
+6 -8
View File
@@ -16,6 +16,7 @@ import (
"github.com/devvmhq/devvm/internal/project"
"github.com/devvmhq/devvm/internal/state"
"github.com/devvmhq/devvm/internal/tools"
"github.com/devvmhq/devvm/internal/vmlog"
"github.com/devvmhq/devvm/internal/vmname"
"github.com/devvmhq/devvm/internal/vmssh"
)
@@ -27,10 +28,6 @@ import (
// (Proxy.Start, Args and Signal), through daemon.Proc.
type linkRuns struct{ *Env }
// linksLogMax is the most a link session's log keeps: one over it is
// emptied when the next session starts.
const linksLogMax = 1 << 20
// linksReportWait bounds how long devvm waits for a session it started,
// or one whose links changed, to say what came of each link.
const linksReportWait = 10 * time.Second
@@ -111,11 +108,12 @@ func (e linkRuns) start(vm vmname.VM) (int64, error) {
return 0, err
}
}
flags := os.O_APPEND | os.O_CREATE | os.O_WRONLY
if fi, err := os.Stat(logPath); err == nil && fi.Size() > linksLogMax {
flags |= os.O_TRUNC //nolint:forbidigo // the session's log, which it writes as it runs: started again empty once too long
// The session holds its log to its cap as it runs (Session); one an
// earlier one left past it is rotated first.
if _, err := vmlog.Trim(logPath, vmlog.OwnMax); err != nil {
return 0, err
}
out, err := os.OpenFile(logPath, flags, 0o600) //nolint:gosec // devvm's own log
out, err := os.OpenFile(logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) //nolint:gosec // devvm's own log
if err != nil {
return 0, err
}
+26
View File
@@ -21,6 +21,7 @@ import (
"github.com/devvmhq/devvm/internal/netpolicy"
"github.com/devvmhq/devvm/internal/paths"
"github.com/devvmhq/devvm/internal/state"
"github.com/devvmhq/devvm/internal/vmlog"
"github.com/devvmhq/devvm/internal/vmname"
)
@@ -364,6 +365,31 @@ func TestLinkRuns(t *testing.T) {
}
}
// A session's log that an earlier one left past its cap is rotated as the
// next starts, which writes from its start.
func TestLinkRunTrimsLog(t *testing.T) {
vm := vmname.VM("devvm-app-0123456789abc1")
r, _ := linkRunsEnv(t, "devvm links: started\n")
log := r.Dirs.VM(vm).LinksLog()
if err := os.MkdirAll(filepath.Dir(log), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(log, []byte(strings.Repeat("ssh: a line from the VM\n", vmlog.OwnMax/16)), 0o600); err != nil {
t.Fatal(err)
}
ok, from, err := r.ensure(vm)
if err != nil || !ok || from != 0 {
t.Fatalf("ensure = %v, %d, %v", ok, from, err)
}
if b, _ := os.ReadFile(log); string(b) != "devvm links: started\n" { //nolint:gosec // the test's own file
t.Errorf("log %q", b)
}
if fi, err := os.Stat(log + ".1"); err != nil || fi.Size() > vmlog.OwnMax {
t.Errorf(".1: %v, %v", fi, err)
}
r.stop(t.Context(), vm)
}
// zombie reports whether pid ended and only waits to be reaped: the
// test's own sleeps are reaped by their Wait.
func zombie(pid int) bool {
+22 -7
View File
@@ -14,6 +14,7 @@ import (
"github.com/devvmhq/devvm/internal/netpolicy"
"github.com/devvmhq/devvm/internal/proxy"
"github.com/devvmhq/devvm/internal/state"
"github.com/devvmhq/devvm/internal/vmlog"
"github.com/devvmhq/devvm/internal/vmname"
"github.com/devvmhq/devvm/internal/vmssh"
)
@@ -74,23 +75,37 @@ func (e Links) Session(ctx context.Context, vm vmname.VM, log io.Writer) error {
return err
}
events := linkEvents{path: e.Dirs.VM(vm).EventLog(), vm: vm, mu: &sync.Mutex{}}
// Its log is the VM's links log, which devvm opened as its output:
// held to its cap, and limited, the warnings included, as each
// carries the client's sshd's words and the client paces them.
limited := vmlog.NewLimit(vmlog.NewCapped(log, e.Dirs.VM(vm).LinksLog(), vmlog.OwnMax), "links", time.Now)
s := &vmssh.Links{
VM: vm, SSH: ssh, Dir: e.Dirs.Run(), Log: log, List: e.Dirs.VM(vm).LinkList(),
VM: vm, SSH: ssh, Dir: e.Dirs.Run(), Log: limited, List: e.Dirs.VM(vm).LinkList(),
Every: linkAliveEvery, Sync: linkSyncEvery, Tick: 2 * time.Second,
Alive: func(ctx context.Context) bool {
now, err := b.Running(ctx, vm)
return err == nil && now.ID == start
},
Want: func() ([]vmssh.Link, error) { return e.sessionLinks(vm) },
Check: e.linkCheck(vm),
Event: events.add,
Failed: func(l vmssh.Link, err error) {
e.Warn(Link{Name: l.Name, Port: l.Port}.PortTaken(vm).Because(err))
},
Want: func() ([]vmssh.Link, error) { return e.sessionLinks(vm) },
Check: e.linkCheck(vm),
Event: events.add,
Failed: e.linkFailed(vm, limited),
}
return s.Run(ctx)
}
// linkFailed is how client vm's session warns of a link the client
// refused to listen for: each warning takes a turn of the session's
// limited log (vmlog.Limit.Allow), which its warnings reach too, as the
// client paces them and each carries its sshd's words.
func (e Links) linkFailed(vm vmname.VM, log *vmlog.Limit) func(vmssh.Link, error) {
return func(l vmssh.Link, err error) {
if log.Allow() {
e.Warn(Link{Name: l.Name, Port: l.Port}.PortTaken(vm).Because(err))
}
}
}
// sessionLinks returns a client's links as its session carries them:
// every one its state has, whether it applies now or not, as each
// connection is checked again, with the names its proxy takes it by. A
+24
View File
@@ -1,6 +1,7 @@
package vm
import (
"bytes"
"context"
"errors"
"net/netip"
@@ -19,6 +20,7 @@ import (
"github.com/devvmhq/devvm/internal/netpolicy"
"github.com/devvmhq/devvm/internal/paths"
"github.com/devvmhq/devvm/internal/state"
"github.com/devvmhq/devvm/internal/vmlog"
"github.com/devvmhq/devvm/internal/vmname"
"github.com/devvmhq/devvm/internal/vmssh"
)
@@ -364,6 +366,28 @@ func TestWarnUnenforced(t *testing.T) {
}
}
// The client can make its session warn of a refused link as often as it
// likes: the warnings take their turns from the session's limited log.
func TestLinkFailedLimited(t *testing.T) {
e, _, client, _, _ := linkSessionEnv(t)
var warned msg.Recorder
e.Reporter = &msg.Fake{OnWarn: warned.Add}
var log bytes.Buffer
now := time.Unix(1000, 0)
failed := e.linkFailed(client.Name(), vmlog.NewLimit(&log, "links", func() time.Time { return now }))
for range vmlog.Burst + 5 {
failed(vmssh.Link{Name: "db", Port: 5432}, errors.New("refused by the VM"))
}
if n := len(warned.Names()); n != vmlog.Burst {
t.Errorf("%d warnings, want %d", n, vmlog.Burst)
}
now = now.Add(vmlog.Every)
failed(vmssh.Link{Name: "db", Port: 5432}, errors.New("refused by the VM"))
if n := len(warned.Names()); n != vmlog.Burst+1 {
t.Errorf("%d warnings after Every, want %d", n, vmlog.Burst+1)
}
}
// A session carries every link its client's state has, applying or not,
// and none once the client is gone; it refuses a client that isn't
// running, or whose ssh isn't devvm's.
+93
View File
@@ -0,0 +1,93 @@
// Package vmlog is a log a VM can drive: one that a VM's output, its
// servers' messages or its serial console reach, which must not fill the
// host's disk however much the VM writes. Limit holds the writes of
// devvm's own processes to a rate and a length; Capped, Trim and Keep
// hold a log's file to a size while it's written, copying its end to
// <log>.1 and emptying it, whether devvm's process appends to it or
// another program (Lima, QEMU, Apple's Virtualization framework) writes
// it at its own offset. The proxy keeps its own logs (proxy.rotating), as
// it imports only the standard library.
package vmlog
import (
"fmt"
"io"
"sync"
"time"
"github.com/devvmhq/devvm/internal/msg"
)
// What the VM can make a limited log take (Limit): Burst writes at once,
// then one per Every, each at most WriteMax bytes.
const (
Burst = 200
Every = 10 * time.Second
WriteMax = 512
)
// Limit is a log the VM can make devvm's process write to (its ports, its
// ssh's errors, its sshd's stderr): Burst writes at once, then one per
// Every, each cut at WriteMax bytes, so it can't fill the host's disk,
// and without control characters but newlines and tabs (msg.Printable).
// The writes it drops are counted, and the next it takes says how many.
type Limit struct {
w io.Writer
name string
now func() time.Time
mu sync.Mutex
tokens int
at time.Time
dropped int
}
// NewLimit limits what goes to w, the log of devvm's process name ("ports", "links"), which the
// line that counts the writes dropped names, on the clock now.
func NewLimit(w io.Writer, name string, now func() time.Time) *Limit {
return &Limit{w: w, name: name, now: now, tokens: Burst, at: now()}
}
// take takes one of the limit's writes, refilled since, and reports
// whether there was one; a write it can't take is counted as dropped.
// l.mu is held.
func (l *Limit) take() bool {
if n := int(l.now().Sub(l.at) / Every); n > 0 {
l.tokens, l.at = min(Burst, l.tokens+n), l.at.Add(time.Duration(n)*Every)
}
if l.tokens == 0 {
l.dropped++
return false
}
l.tokens--
return true
}
// Allow takes one of the limit's writes for something said another way,
// such as a warning through the process's Reporter, which goes to the
// same log: false when there's none, and it's dropped, counted as the
// log's writes are.
func (l *Limit) Allow() bool {
l.mu.Lock()
defer l.mu.Unlock()
return l.take()
}
func (l *Limit) Write(p []byte) (int, error) {
l.mu.Lock()
defer l.mu.Unlock()
if !l.take() {
return len(p), nil
}
var b []byte
if l.dropped > 0 {
b = fmt.Appendf(b, "devvm %s: %d writes not logged\n", l.name, l.dropped)
l.dropped = 0
}
b = append(b, msg.Printable(string(p[:min(len(p), WriteMax)]))...)
if len(p) > WriteMax {
b = append(b, "…\n"...)
}
_, err := l.w.Write(b)
return len(p), err
}
+63
View File
@@ -0,0 +1,63 @@
package vmlog
import (
"bytes"
"strings"
"testing"
"time"
)
// What the VM makes a process log is limited: a burst, then one write
// per Every, those dropped counted; control characters dropped, C1
// included, long writes cut.
func TestLimit(t *testing.T) {
t.Parallel()
var b bytes.Buffer
now := time.Unix(1000, 0)
l := NewLimit(&b, "ports", func() time.Time { return now })
for range Burst + 50 {
_, _ = l.Write([]byte("x\n"))
}
if got := strings.Count(b.String(), "x\n"); got != Burst {
t.Errorf("%d writes logged, want %d", got, Burst)
}
b.Reset()
now = now.Add(2 * Every)
_, _ = l.Write([]byte("a\x1b[2Jb\302\233c\x9bd\r\n"))
_, _ = l.Write([]byte(strings.Repeat("y", WriteMax+10)))
_, _ = l.Write([]byte("dropped\n"))
want := "devvm ports: 50 writes not logged\na[2Jbcd\n" + strings.Repeat("y", WriteMax) + "…\n"
if b.String() != want {
t.Errorf("log:\n%q\nwant\n%q", b.String(), want)
}
}
// Allow takes its turn from the same writes: a warning said another way
// counts against the log, and one past the limit is dropped and counted.
func TestLimitAllow(t *testing.T) {
t.Parallel()
var b bytes.Buffer
now := time.Unix(1000, 0)
l := NewLimit(&b, "links", func() time.Time { return now })
allowed := 0
for range Burst + 5 {
if l.Allow() {
allowed++
}
}
if allowed != Burst {
t.Errorf("%d allowed, want %d", allowed, Burst)
}
if _, _ = l.Write([]byte("x\n")); b.Len() != 0 {
t.Errorf("a write past the limit: %q", b.String())
}
now = now.Add(Every)
if !l.Allow() || l.Allow() {
t.Error("one more after Every, and only one")
}
now = now.Add(Every)
_, _ = l.Write([]byte("y\n"))
if want := "devvm links: 7 writes not logged\ny\n"; b.String() != want {
t.Errorf("log %q, want %q", b.String(), want)
}
}
+10
View File
@@ -0,0 +1,10 @@
package vmlog
import (
"testing"
"github.com/devvmhq/devvm/internal/leaktest"
)
// TestMain fails the tests if a goroutine of theirs outlives them.
func TestMain(m *testing.M) { leaktest.Main(m) }
+282
View File
@@ -0,0 +1,282 @@
package vmlog
import (
"bytes"
"context"
"errors"
"io"
"io/fs"
"os"
"path/filepath"
"sync"
"time"
"github.com/devvmhq/devvm/internal/platform"
"github.com/devvmhq/devvm/internal/redact"
"github.com/devvmhq/devvm/internal/safefile"
"github.com/devvmhq/devvm/internal/state"
)
// The caps of the logs a VM can drive: each also keeps one .1 file of as much.
const (
// VMMax is the cap of each log that a VM's backend writes as the VM
// runs (KeepVM's): its serial console's, and its host process's own.
VMMax = 10 << 20
// OwnMax is the cap of the log of one of devvm's background
// processes for a VM (Capped's): the port forwarder's and the link
// session's.
OwnMax = 1 << 20
)
// KeepEvery is how often KeepVM looks at its logs: a VM writing its
// serial console as fast as it can gets this long past the cap.
const KeepEvery = time.Second
// openLog opens the log at path to redact and empty it in place: a
// regular file, not one a symbolic link at its path leads to, and never
// waiting on a FIFO (safefile).
func openLog(path string) (*safefile.File, error) {
return safefile.Open(path, safefile.Opts{Write: true})
}
// dataStart is where f's data starts, at most size: the later of where
// the file system says it does (platform.DataStart, 0 on one without
// holes) and hole, the log's length when its keeper last emptied it,
// which its writer goes on past at its own offset. On a file system
// without holes, the emptied part reads as zeros and still takes disk.
func dataStart(f *os.File, size, hole int64) int64 {
return min(max(platform.DataStart(f), hole), size)
}
// appendedFrom0 reports whether f, emptied by its keeper, holds data from
// its start again, as a writer that appends writes it: the file system
// says its data starts at 0, and its first block isn't all zeros, which
// a file system without holes, whose DataStart is always 0, reads there
// past a writer at its own offset.
func appendedFrom0(f *os.File) bool {
if platform.DataStart(f) != 0 {
return false
}
b := make([]byte, 4096)
n, _ := f.ReadAt(b, 0)
return len(bytes.Trim(b[:n], "\x00")) > 0
}
// Rotate copies the end of the log at path, at most keep bytes, to
// <log>.1, replacing the one there, and empties the log, with each
// password and proxy key in the copy replaced (rotate).
func Rotate(path string, keep int64) error {
f, err := openLog(path)
if err != nil {
return err
}
defer func() { _ = f.Close() }()
size := f.Info.Size()
_, err = rotate(f.File, path, size, dataStart(f.File, size, 0), keep, redact.Look{})
return err
}
// rotate copies the end of the log f at path, size bytes long and holding
// data from start, at most keep bytes, to <log>.1, replacing the one
// there, and empties the log. The copy starts at a line's start unless it
// holds all of the log's data or one line alone, and leaves out the zeros
// a hole reads as. What f gained past where look stopped (all of it for
// the zero Look) has each password and proxy key in it replaced
// (redact.In); what's before was replaced in f already. A secret cut at
// the copy's end is masked (redact.Unended), and masked reports it, as
// the rest of it is the next the writer writes. The copy is written
// whole, the user's alone. What the log's writer adds between the copy
// and the emptying is lost.
func rotate(f *os.File, path string, size, start, keep int64, look redact.Look) (masked bool, err error) {
// Past keep, the byte before the copy too: whether it starts a line.
from := max(size-keep-1, start)
cut := from > start
data := make([]byte, size-from)
n, err := f.ReadAt(data, from)
if err != nil && !errors.Is(err, io.EOF) {
return false, err
}
data = data[:n]
if held := bytes.TrimLeft(data, "\x00"); len(held) < len(data) {
from += int64(len(data) - len(held))
data = held
} else if cut && len(data) > 0 {
skip := 1
if i := bytes.IndexByte(data, '\n'); i >= 0 && i+1 < len(data) {
skip = i + 1
}
from += int64(skip)
data = data[skip:]
}
at := redact.Look{Line: max(look.Line-from, 0), Read: max(look.Read-from, 0)}
if _, err := redact.In(redact.Bytes(data), int64(len(data)), at, int64(len(data))); err != nil {
return false, err
}
masked = redact.Unended(data)
if err := state.WriteFile(path+".1", data); err != nil {
return false, err
}
return masked, f.Truncate(0)
}
// redactMax is as much of a log as Redact reads: a hostagent's log right
// after its start is far smaller.
const redactMax = 64 << 20
// Redact overwrites each proxy key and URL password in the log at path
// with as many "*", in place (redact.In), in its first redactMax bytes:
// the file keeps its length and every other byte, so a program still
// writing to it at its own offset (Lima's hostagent, which opened it
// without O_APPEND) goes on where it was. A missing log has nothing to
// redact.
func Redact(path string) error {
f, err := openLog(path)
if errors.Is(err, fs.ErrNotExist) {
return nil
}
if err != nil {
return err
}
_, err = redact.In(f.File, f.Info.Size(), redact.Look{}, redactMax)
return errors.Join(err, f.Close())
}
// cleanTemps removes what a rotation of the log at path left when it was
// killed while writing <log>.1: its temporary files (state.WriteFile's).
func cleanTemps(path string) {
old, _ := filepath.Glob(filepath.Join(filepath.Dir(path), "."+filepath.Base(path)+".1.tmp-*"))
for _, p := range old {
_ = os.Remove(p)
}
}
// Trim rotates the log at path (Rotate) once it holds more than limit
// past the hole at its start, keeping limit, and reports whether it did,
// after removing what an earlier rotation killed midway left. A missing
// log has nothing to trim.
func Trim(path string, limit int64) (bool, error) {
cleanTemps(path)
f, err := openLog(path)
if errors.Is(err, fs.ErrNotExist) {
return false, nil
}
if err != nil {
return false, err
}
defer func() { _ = f.Close() }()
size := f.Info.Size()
start := dataStart(f.File, size, 0)
if size-start <= limit {
return false, nil
}
_, err = rotate(f.File, path, size, start, limit, redact.Look{})
return true, err
}
// Keep holds each log at paths to limit until ctx ends, each in a
// goroutine of its own, so one that a VM floods never holds up the
// others, looking every every (kept.look).
func Keep(ctx context.Context, paths []string, limit int64, every time.Duration) {
var wg sync.WaitGroup
for _, p := range paths {
wg.Go(func() {
cleanTemps(p)
k := &kept{path: p, limit: limit}
t := time.NewTicker(every)
defer t.Stop()
for {
k.look()
select {
case <-ctx.Done():
return
case <-t.C:
}
}
})
}
wg.Wait()
}
// KeepVM holds the logs that a VM's backend writes as it runs
// (backend.Run.Logs) to VMMax until ctx ends, looking every KeepEvery.
func KeepVM(ctx context.Context, paths []string) { Keep(ctx, paths, VMMax, KeepEvery) }
// kept is a log Keep holds: how far it's redacted, its length at the last
// look, and its length when Keep last emptied it, where its writer's data
// starts again.
type kept struct {
path string
limit int64
at redact.Look
size int64
hole int64
}
// look redacts in place what the log gained since the last look, at most
// limit bytes (redact.In), so a password the VM's boot writes to its
// console again, as a reboot that QEMU carries out in place does, is
// replaced within a look, not only at the VM's next start. A log that
// hasn't changed length costs nothing. Then one that holds more than
// limit past the hole at its start is rotated (rotate), its copy
// redacted only past what the look reached. A log that's gone, or that
// got shorter than this keeper left it (made again), starts afresh.
func (k *kept) look() {
f, err := openLog(k.path)
if err != nil {
*k = kept{path: k.path, limit: k.limit}
return
}
defer func() { _ = f.Close() }()
size := f.Info.Size()
if size == k.size {
return
}
// Shorter than this keeper left it, or, after a rotation, with data
// from its start (a writer that appends, not one at its own offset):
// a log to read afresh.
if size < k.size || size < k.hole || k.hole > 0 && appendedFrom0(f.File) {
*k = kept{path: k.path, limit: k.limit}
}
start := dataStart(f.File, size, k.hole)
k.at.Line, k.at.Read = max(k.at.Line, start), max(k.at.Read, start)
if at, err := redact.In(f.File, size, k.at, k.limit); err == nil {
k.at = at
}
k.size = size
if size-start <= k.limit {
return
}
// A secret the copy's end cut has its rest at the start of what the
// writer writes next (Look.Cut).
if cut, err := rotate(f.File, k.path, size, start, k.limit, k.at); err == nil {
k.hole, k.size, k.at = size, 0, redact.Look{Line: size, Read: size, Cut: cut}
}
}
// Capped is w, which appends to the log at path (a background process's
// output, which devvm opened for it), held to limit: before a write that
// would take the log past it, the log is rotated (Rotate). It takes the
// log's size from the file, so what reaches the log another way, such as
// the process's warnings and its last error, counts too. A failed
// rotation goes on writing: a line kept beats a log of the right size.
type Capped struct {
w io.Writer
path string
limit int64
mu sync.Mutex
}
// NewCapped holds w, which appends to path, to limit.
func NewCapped(w io.Writer, path string, limit int64) *Capped {
return &Capped{w: w, path: path, limit: limit}
}
func (c *Capped) Write(p []byte) (int, error) {
c.mu.Lock()
defer c.mu.Unlock()
if fi, err := os.Stat(c.path); err == nil && fi.Size() > 0 && fi.Size()+int64(len(p)) > c.limit {
_ = Rotate(c.path, c.limit)
}
return c.w.Write(p)
}
+383
View File
@@ -0,0 +1,383 @@
package vmlog
import (
"bytes"
"context"
"errors"
"io/fs"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/devvmhq/devvm/internal/redact"
)
func readLog(t *testing.T, path string) string {
t.Helper()
b, err := os.ReadFile(path) //nolint:gosec // the test's own file
if err != nil && !os.IsNotExist(err) {
t.Fatal(err)
}
return string(b)
}
// A log devvm's process appends to (Capped): rotated before the write
// that would take it past its cap, the whole log copied when it holds no
// more, and what reaches it another way (the process's last error)
// counted from the file.
func TestCapped(t *testing.T) {
t.Parallel()
path := filepath.Join(t.TempDir(), "ports.log")
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) //nolint:gosec // the test's own file
if err != nil {
t.Fatal(err)
}
defer func() { _ = f.Close() }()
c := NewCapped(f, path, 20)
for _, s := range []string{"started 0123\n", "loaded\n", "failed upstream\n"} { // 13, 20, then past
if _, err := c.Write([]byte(s)); err != nil {
t.Fatal(err)
}
}
if _, err := f.WriteString("devvm: the last error\n"); err != nil { // 38: past, unseen by c
t.Fatal(err)
}
if a, b := readLog(t, path+".1"), readLog(t, path); a != "started 0123\nloaded\n" || b != "failed upstream\ndevvm: the last error\n" {
t.Errorf(".1 %q, log %q", a, b)
}
if _, err := c.Write([]byte("next\n")); err != nil {
t.Fatal(err)
}
// The log was past its cap: its last 20 bytes, from a line's start
// unless that would leave nothing.
if a, b := readLog(t, path+".1"), readLog(t, path); a != "vvm: the last error\n" || b != "next\n" {
t.Errorf(".1 %q, log %q", a, b)
}
fi, err := os.Stat(path + ".1")
if err != nil || fi.Mode().Perm() != 0o600 {
t.Errorf(".1: %v, %v", fi, err)
}
}
// A log another program writes at its own offset (Lima's hostagent and
// serial console, opened without O_APPEND): once it holds more than its
// cap, its end goes to .1 with the passwords in it replaced, and it's
// emptied; the writer goes on past a hole, which counts for nothing, so
// the log isn't rotated again until it holds as much again.
func TestTrimHole(t *testing.T) {
t.Parallel()
path := filepath.Join(t.TempDir(), "ha.stderr.log")
w, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0o644) //nolint:gosec // the test's own file, as Lima makes it
if err != nil {
t.Fatal(err)
}
defer func() { _ = w.Close() }()
const limit = 64 << 10
key := strings.Repeat("0123456789abcdef", 2)
line := "proxy http://devvm:" + key + "@192.168.5.2:3129 serving\n"
var all strings.Builder
for all.Len() <= limit+len(line) {
all.WriteString(line)
}
if _, err := w.WriteString(all.String()); err != nil {
t.Fatal(err)
}
if done, err := Trim(path, 2*limit); done || err != nil {
t.Fatalf("under its cap: %v, %v", done, err)
}
if done, err := Trim(path, limit); !done || err != nil {
t.Fatalf("past its cap: %v, %v", done, err)
}
old := readLog(t, path+".1")
if strings.Contains(old, key) || !strings.HasPrefix(old, "proxy http://devvm:"+strings.Repeat("*", len(key))+"@") || len(old) > limit {
t.Errorf(".1 not redacted, not from a line's start, or too long: %d bytes, starting %q", len(old), old[:min(len(old), 40)])
}
if s := readLog(t, path); s != "" {
t.Errorf("not emptied: %d bytes", len(s))
}
if _, err := w.WriteString("later\n"); err != nil {
t.Fatal(err)
}
if done, err := Trim(path, limit); done || err != nil {
t.Errorf("a hole counted: %v, %v", done, err)
}
if s := readLog(t, path); !strings.HasSuffix(s, "later\n") || strings.Trim(strings.TrimSuffix(s, "later\n"), "\x00") != "" {
t.Errorf("the writer's offset: %q", s[len(s)-min(len(s), 20):])
}
// A copy reaching back into the hole leaves its zeros out.
if err := Rotate(path, limit); err != nil {
t.Fatal(err)
}
if old := readLog(t, path+".1"); old != "later\n" {
t.Errorf(".1 %q", old[:min(len(old), 20)])
}
if _, err := w.WriteString(strings.Repeat("x", limit) + "\n"); err != nil {
t.Fatal(err)
}
if done, err := Trim(path, limit); !done || err != nil {
t.Fatalf("past its cap again: %v, %v", done, err)
}
if old := readLog(t, path+".1"); bytes.ContainsRune([]byte(old), 0) || old != strings.Repeat("x", limit-1)+"\n" {
t.Errorf(".1 holds the hole, or not the end: %d bytes", len(old))
}
}
// Nothing to trim: a missing log; and what isn't a regular file isn't
// rotated.
func TestTrimNothing(t *testing.T) {
t.Parallel()
dir := t.TempDir()
if done, err := Trim(filepath.Join(dir, "missing.log"), 1); done || err != nil {
t.Errorf("missing: %v, %v", done, err)
}
if err := Rotate(dir, 1); err == nil {
t.Error("a folder rotated")
}
if _, err := os.Stat(dir + ".1"); !os.IsNotExist(err) {
t.Errorf("a folder's copy: %v", err)
}
}
// Keep looks at its logs until ctx ends, rotating each past its cap.
func TestKeep(t *testing.T) {
t.Parallel()
dir := t.TempDir()
logs := []string{filepath.Join(dir, "serial.log"), filepath.Join(dir, "missing.log")}
if err := os.WriteFile(logs[0], []byte(strings.Repeat("boot\n", 100)), 0o600); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(t.Context())
done := make(chan struct{})
go func() {
defer close(done)
Keep(ctx, logs, 100, 10*time.Millisecond)
}()
for deadline := time.Now().Add(10 * time.Second); readLog(t, logs[0]) != ""; {
if time.Now().After(deadline) {
t.Fatal("not rotated")
}
time.Sleep(10 * time.Millisecond)
}
cancel()
<-done
if old := readLog(t, logs[0]+".1"); old != strings.Repeat("boot\n", 20) {
t.Errorf(".1 %q", old)
}
if _, err := os.Stat(logs[1]); !errors.Is(err, fs.ErrNotExist) {
t.Errorf("a missing log made: %v", err)
}
}
// A VM rebooted in place (QEMU) traces its boot to its console again,
// the proxy's password with it: Keep replaces it as the log grows, under
// its cap, and goes on after a rotation, past the hole it left.
func TestKeepRedacts(t *testing.T) {
t.Parallel()
path := filepath.Join(t.TempDir(), "serial.log")
w, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0o644) //nolint:gosec // the test's own file, as QEMU makes it
if err != nil {
t.Fatal(err)
}
defer func() { _ = w.Close() }()
key := strings.Repeat("0123456789abcdef", 2)
traced := "+ echo HTTPS_PROXY=http://devvm:" + key + "@192.168.5.2:3129\n"
ctx, cancel := context.WithCancel(t.Context())
done := make(chan struct{})
go func() {
defer close(done)
Keep(ctx, []string{path}, 4<<10, 10*time.Millisecond)
}()
defer func() { cancel(); <-done }()
waitRedacted := func(what string) {
t.Helper()
for deadline := time.Now().Add(10 * time.Second); strings.Contains(readLog(t, path), key); time.Sleep(10 * time.Millisecond) {
if time.Now().After(deadline) {
t.Fatalf("%s: not redacted", what)
}
}
}
for _, s := range []string{"boot\n", traced, "reboot\n", traced} {
if _, err := w.WriteString(s); err != nil {
t.Fatal(err)
}
time.Sleep(20 * time.Millisecond)
}
waitRedacted("written twice")
// Past its cap, rotated, then written again past the hole.
if _, err := w.WriteString(strings.Repeat("boot\n", 1<<10)); err != nil {
t.Fatal(err)
}
for deadline := time.Now().Add(10 * time.Second); readLog(t, path+".1") == ""; time.Sleep(10 * time.Millisecond) {
if time.Now().After(deadline) {
t.Fatal("not rotated")
}
}
if _, err := w.WriteString(traced); err != nil {
t.Fatal(err)
}
waitRedacted("after a rotation")
}
// A log that hasn't grown since the last look costs that look nothing,
// and one that grew is read again only MatchMax back, not from the start
// of a long line that hasn't ended: what's further back is left as the
// earlier look found it (here, a secret put there behind its back, which
// a look that read it again would replace).
func TestKeptStillLine(t *testing.T) {
t.Parallel()
path := filepath.Join(t.TempDir(), "serial.log")
line := "@" + strings.Repeat("x", 1<<20)
if err := os.WriteFile(path, []byte(line), 0o600); err != nil {
t.Fatal(err)
}
k := &kept{path: path, limit: VMMax}
k.look()
if k.at != (redact.Look{Line: 0, Read: int64(len(line))}) || k.size != int64(len(line)) {
t.Fatalf("after the first look: %+v", k)
}
f, err := os.OpenFile(path, os.O_RDWR, 0) //nolint:gosec // the test's own file
if err != nil {
t.Fatal(err)
}
defer func() { _ = f.Close() }()
secret := " http://u:e2e-not-a-secret@h" //nolint:gosec // a fake password
if _, err := f.WriteAt([]byte(secret), 10); err != nil {
t.Fatal(err)
}
k.look()
if !strings.Contains(readLog(t, path), "e2e-not-a-secret") {
t.Error("a log that didn't grow was read again")
}
if _, err := f.WriteAt([]byte("y\n"), int64(len(line))); err != nil {
t.Fatal(err)
}
k.look()
if !strings.Contains(readLog(t, path), "e2e-not-a-secret") || k.at.Line != int64(len(line))+2 {
t.Errorf("a long line read again from its start, or its end not seen: %+v", k.at)
}
}
// A rotation that cuts a log in the middle of a secret whose "@" hasn't
// come yet doesn't copy its start to .1 as it is.
func TestRotateCutSecret(t *testing.T) {
t.Parallel()
path := filepath.Join(t.TempDir(), "serial.log")
key := strings.Repeat("0123456789abcdef", 2)
if err := os.WriteFile(path, []byte(strings.Repeat("boot\n", 100)+"+ echo http://devvm:"+key[:20]), 0o600); err != nil {
t.Fatal(err)
}
if err := Rotate(path, 1<<10); err != nil {
t.Fatal(err)
}
if old := readLog(t, path+".1"); strings.Contains(old, key[:20]) || !strings.HasSuffix(old, "devvm:"+strings.Repeat("*", 20)) {
t.Errorf(".1 ends %q", old[len(old)-min(len(old), 40):])
}
}
// The rest of a key that a rotation cut, which the log's writer then
// writes at its own offset past the hole, is starred up to its "@" once
// it comes; and a log whose data starts at 0 again after a rotation (a
// writer that appends) is read afresh, from its start.
func TestKeptCutAndAppend(t *testing.T) {
t.Parallel()
path := filepath.Join(t.TempDir(), "serial.log")
w, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0o644) //nolint:gosec // the test's own file, as QEMU makes it
if err != nil {
t.Fatal(err)
}
defer func() { _ = w.Close() }()
key := strings.Repeat("0123456789abcdef", 2)
if _, err := w.WriteString(strings.Repeat("boot\n", 1<<10) + "+ echo http://devvm:" + key[:20]); err != nil {
t.Fatal(err)
}
k := &kept{path: path, limit: 1 << 10}
k.look()
if !k.at.Cut || k.hole == 0 || strings.Contains(readLog(t, path+".1"), key[:20]) {
t.Fatalf("not rotated with its cut: %+v", k)
}
if _, err := w.WriteString(key[20:] + "@192.168.5.2:3129\nlater\n"); err != nil {
t.Fatal(err)
}
k.look()
if s := readLog(t, path); strings.Contains(s, key[20:]) || !strings.HasSuffix(s, strings.Repeat("*", len(key)-20)+"@192.168.5.2:3129\nlater\n") || k.at.Cut {
t.Errorf("the key's rest: %q, %+v", s[len(s)-min(len(s), 60):], k.at)
}
// Emptied and written again from its start, by appending, past where
// the hole would end: data at 0 says it's no writer at its offset.
hole := k.hole
if err := os.WriteFile(path, []byte("x http://a:e2e-not-a-secret@h:1\n"+strings.Repeat("y", int(hole))), 0o600); err != nil {
t.Fatal(err)
}
k.limit = 1 << 20 // under its cap now
k.look()
if s := readLog(t, path); strings.Contains(s, "e2e-not-a-secret") || k.hole != 0 {
t.Errorf("appended from 0: log starts %q, %+v", s[:min(len(s), 30)], k.at)
}
}
// On a file system without holes, what a rotation emptied reads as real
// zeros and DataStart says 0: the keeper goes on past them from where it
// emptied the log, rather than reading it afresh and rotating again.
func TestKeptNoHoles(t *testing.T) {
t.Parallel()
path := filepath.Join(t.TempDir(), "serial.log")
if err := os.WriteFile(path, []byte(strings.Repeat("boot\n", 1<<10)), 0o600); err != nil {
t.Fatal(err)
}
k := &kept{path: path, limit: 1 << 10}
k.look()
hole, old := k.hole, readLog(t, path+".1")
if hole == 0 || old == "" {
t.Fatalf("not rotated: %+v", k)
}
// The writer goes on at its offset, the emptied part written out as zeros.
line := "+ echo http://devvm:" + strings.Repeat("0123456789abcdef", 2) + "@192.168.5.2:3129\n"
if err := os.WriteFile(path, append(make([]byte, hole), line...), 0o600); err != nil {
t.Fatal(err)
}
k.look()
s := readLog(t, path)
if k.hole != hole || readLog(t, path+".1") != old || strings.Contains(s, "0123456789abcdef") || !strings.HasSuffix(s, strings.Repeat("*", 32)+"@192.168.5.2:3129\n") {
t.Errorf("read afresh or not redacted: %+v, ends %q", k, s[len(s)-min(len(s), 60):])
}
}
// Redact replaces each secret in place in a log's file, refuses what
// isn't a regular file, a link to one included, and has nothing to do for
// a missing log; Trim first removes what a rotation killed midway left.
func TestRedactAndTemps(t *testing.T) {
t.Parallel()
dir := t.TempDir()
path := filepath.Join(dir, "ha.stderr.log")
if err := os.WriteFile(path, []byte("HTTPS_PROXY=http://alice:e2e-not-a-secret@h:1\n"), 0o600); err != nil {
t.Fatal(err)
}
if err := Redact(path); err != nil || strings.Contains(readLog(t, path), "e2e-not-a-secret") {
t.Errorf("Redact: %v, %q", err, readLog(t, path))
}
if err := Redact(filepath.Join(dir, "missing.log")); err != nil {
t.Errorf("missing: %v", err)
}
link := filepath.Join(dir, "link.log")
if err := os.Symlink(path, link); err != nil {
t.Fatal(err)
}
if err := Redact(link); err == nil {
t.Error("followed a link")
}
if err := Redact(dir); err == nil {
t.Error("a folder: no error")
}
tmp := filepath.Join(dir, ".ha.stderr.log.1.tmp-123")
if err := os.WriteFile(tmp, []byte("half"), 0o600); err != nil {
t.Fatal(err)
}
if _, err := Trim(path, VMMax); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(tmp); !errors.Is(err, fs.ErrNotExist) {
t.Errorf("a stale copy stays: %v", err)
}
}
+2 -52
View File
@@ -31,9 +31,9 @@ import (
"github.com/devvmhq/devvm/internal/backend"
"github.com/devvmhq/devvm/internal/daemon"
"github.com/devvmhq/devvm/internal/msg"
"github.com/devvmhq/devvm/internal/platform"
"github.com/devvmhq/devvm/internal/proxy"
"github.com/devvmhq/devvm/internal/vmlog"
"github.com/devvmhq/devvm/internal/vmname"
)
@@ -287,56 +287,6 @@ func waitUntil(ctx context.Context, t time.Time) error {
}
}
// What the VM can make the forwarder log (logLimit): logBurst writes at
// once, then one per logEvery, each at most logWriteMax bytes.
const (
logBurst = 200
logEvery = 10 * time.Second
logWriteMax = 512
)
// logLimit is the forwarder's log, which the VM can make it write to (its
// ports, its ssh's errors, and its sshd's stderr): limited, so it can't
// fill the host's disk, and without control characters but newlines and
// tabs (msg.Printable).
type logLimit struct {
w io.Writer
now func() time.Time
mu sync.Mutex
tokens int
at time.Time
dropped int
}
func newLogLimit(w io.Writer, now func() time.Time) *logLimit {
return &logLimit{w: w, now: now, tokens: logBurst, at: now()}
}
func (l *logLimit) Write(p []byte) (int, error) {
l.mu.Lock()
defer l.mu.Unlock()
if n := int(l.now().Sub(l.at) / logEvery); n > 0 {
l.tokens, l.at = min(logBurst, l.tokens+n), l.at.Add(time.Duration(n)*logEvery)
}
if l.tokens == 0 {
l.dropped++
return len(p), nil
}
l.tokens--
var b []byte
if l.dropped > 0 {
b = fmt.Appendf(b, "devvm ports: %d writes not logged\n", l.dropped)
l.dropped = 0
}
b = append(b, msg.Printable(string(p[:min(len(p), logWriteMax)]))...)
if len(p) > logWriteMax {
b = append(b, "…\n"...)
}
_, err := l.w.Write(b)
return len(p), err
}
// wanted reports whether the forwarder forwards a port the VM listens on:
// one of Only's, or any from 1024 up without it.
func (f *Forwarder) wanted(port int) bool {
@@ -796,7 +746,7 @@ func (f *Flags) Forwarder(script []byte, reserved func(vm vmname.VM) (map[int]bo
return nil, err
}
}
log = newLogLimit(log, time.Now)
log = vmlog.NewLimit(log, "ports", time.Now)
return &Forwarder{
VM: f.VM, Only: only, Log: log, Tick: 2 * time.Second, Gap: 500 * time.Millisecond,
Reserved: func() (map[int]bool, error) {
-24
View File
@@ -384,30 +384,6 @@ func TestForwarderGap(t *testing.T) {
})
}
// What the VM makes the forwarder log is limited: a burst, then one write
// per logEvery, those dropped counted; control characters dropped, C1
// included, long writes cut.
func TestLogLimit(t *testing.T) {
var b bytes.Buffer
now := time.Unix(1000, 0)
l := newLogLimit(&b, func() time.Time { return now })
for range logBurst + 50 {
_, _ = l.Write([]byte("x\n"))
}
if got := strings.Count(b.String(), "x\n"); got != logBurst {
t.Errorf("%d writes logged, want %d", got, logBurst)
}
b.Reset()
now = now.Add(2 * logEvery)
_, _ = l.Write([]byte("a\x1b[2Jb\302\233c\x9bd\r\n"))
_, _ = l.Write([]byte(strings.Repeat("y", logWriteMax+10)))
_, _ = l.Write([]byte("dropped\n"))
want := "devvm ports: 50 writes not logged\na[2Jbcd\n" + strings.Repeat("y", logWriteMax) + "…\n"
if b.String() != want {
t.Errorf("log:\n%q\nwant\n%q", b.String(), want)
}
}
// While devvm's ports can't be read, nothing new is forwarded.
func TestForwarderReservedUnknown(t *testing.T) {
p := freePorts(t, 1)[0]
+6 -13
View File
@@ -22,6 +22,7 @@ import (
"github.com/devvmhq/devvm/internal/platform"
"github.com/devvmhq/devvm/internal/ports"
"github.com/devvmhq/devvm/internal/state"
"github.com/devvmhq/devvm/internal/vmlog"
"github.com/devvmhq/devvm/internal/vmname"
)
@@ -94,10 +95,6 @@ func (f Forwards) Control(vm vmname.VM) string {
// listens on, devvm gc --orphans deletes.
const ControlGlob = "port-*.ctl"
// logMax is the most a forwarder's log keeps from earlier starts: past
// it, a start empties it.
const logMax = 1 << 20
// ControlMax is the longest control socket path ssh can make.
const ControlMax = paths.SocketMax - 1 - 17
@@ -380,20 +377,16 @@ func (f Forwards) run(vm vmname.VM, s spec) error {
return err
}
}
// The forwarder holds its log to its cap as it runs (Main); one an
// earlier one left past it is rotated first.
if _, err := vmlog.Trim(f.Log(vm), vmlog.OwnMax); err != nil {
return err
}
out, err := os.OpenFile(f.Log(vm), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
if err != nil {
return err
}
defer func() { _ = out.Close() }()
fi, err := out.Stat()
if err != nil {
return err
}
if fi.Size() > logMax {
if err := out.Truncate(0); err != nil {
return err
}
}
var reserve []string
for _, p := range s.Reserve {
if p > 0 {
+25
View File
@@ -5,6 +5,7 @@ import (
"errors"
"os"
"os/exec"
"path/filepath"
"slices"
"strconv"
"strings"
@@ -18,6 +19,7 @@ import (
"github.com/devvmhq/devvm/internal/paths"
"github.com/devvmhq/devvm/internal/ports"
"github.com/devvmhq/devvm/internal/state"
"github.com/devvmhq/devvm/internal/vmlog"
"github.com/devvmhq/devvm/internal/vmname"
)
@@ -65,6 +67,29 @@ func testForwards(t *testing.T) (*Forwards, *[][]string, *msg.Recorder) {
return f, &starts, warned
}
// A forwarder's log that an earlier one left past its cap is rotated as
// the next starts.
func TestForwardsRunTrimsLog(t *testing.T) {
f, starts, _ := testForwards(t)
const vm = "devvm-p-0123456789abcd"
log := f.Log(vm)
if err := os.MkdirAll(filepath.Dir(log), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(log, []byte(strings.Repeat("devvm ports: port 5173: forwarded\n", vmlog.OwnMax/32)), 0o600); err != nil {
t.Fatal(err)
}
if err := f.run(vm, spec{Lifeline: "/lima/ha.pid"}); err != nil || len(*starts) != 1 {
t.Fatalf("run: %v, started %q", err, *starts)
}
if fi, err := os.Stat(log); err != nil || fi.Size() != 0 {
t.Errorf("log: %v, %v", fi, err)
}
if fi, err := os.Stat(log + ".1"); err != nil || fi.Size() > vmlog.OwnMax {
t.Errorf(".1: %v, %v", fi, err)
}
}
// The forwarder's start reads which ports the VM forwards from its state
// and how to reach it from its backend: every port, or its listed ones
// less those a host program has (warned), asked once its old forwarder
+8
View File
@@ -11,6 +11,8 @@ import (
"github.com/devvmhq/devvm/internal/daemon"
"github.com/devvmhq/devvm/internal/paths"
"github.com/devvmhq/devvm/internal/platform"
"github.com/devvmhq/devvm/internal/vmlog"
"github.com/devvmhq/devvm/internal/vmname"
)
// recheck is how often a forwarder gives up the ports devvm reserves now,
@@ -36,6 +38,12 @@ func Main(ctx context.Context, args []string, script []byte, d paths.Dirs, log i
return errors.New("-lifeline is needed")
}
fw := Forwards{Dirs: d, Args: platform.ProcessArgs}
// Its log is the VM's forwarder log, which devvm opened as its
// output: held to its cap as it runs. A -vm that isn't a name fails
// in Forwarder.
if vm, err := vmname.Parse(fl.name); err == nil {
log = vmlog.NewCapped(log, fw.Log(vm), vmlog.OwnMax)
}
f, err := fl.Forwarder(script, fw.Reserved, log)
if err != nil {
return err
+11 -6
View File
@@ -23,6 +23,7 @@ import (
"github.com/devvmhq/devvm/internal/platform"
"github.com/devvmhq/devvm/internal/proxy"
"github.com/devvmhq/devvm/internal/state"
"github.com/devvmhq/devvm/internal/vmlog"
"github.com/devvmhq/devvm/internal/vmname"
)
@@ -120,7 +121,9 @@ type Links struct {
// carried or not, written whenever they change (writeList). Empty:
// none.
List string
// Log gets its lines.
// Log gets its lines, limited (vmlog.Limit): Run limits one that
// isn't already, and a caller that warns another way too (Failed)
// passes its own, which the warnings take their turns from.
Log io.Writer
// Tick is how long a lost connection waits to be made again, and
// Wait how long a master gets to be ready.
@@ -232,7 +235,9 @@ func (l *Links) Control(target vmname.VM, start string) string {
// defaults sets what Run needs that its caller left unset.
func (l *Links) defaults() {
l.Log = newLogLimit(cmp.Or[io.Writer](l.Log, io.Discard), time.Now)
if _, limited := l.Log.(*vmlog.Limit); !limited {
l.Log = vmlog.NewLimit(cmp.Or[io.Writer](l.Log, io.Discard), "links", time.Now)
}
if l.Start == nil {
l.Start = l.startSSH
}
@@ -878,7 +883,7 @@ const sshPrefix = "ssh: "
// logPrefix, which only the session's own lines do (ReadLinksLog). ssh
// prints what the remote side sends it, a disconnect's reason say, with
// its newlines, so either VM's root could otherwise write a line that
// reads as the session's. A line longer than logWriteMax is cut, its
// reads as the session's. A line longer than vmlog.WriteMax is cut, its
// rest a line of its own; a carriage return ending a line is dropped.
type sshLines struct {
w io.Writer
@@ -895,10 +900,10 @@ func (s *sshLines) Write(p []byte) (int, error) {
for {
line, rest, ok := bytes.Cut(s.buf, []byte("\n"))
if !ok {
if len(s.buf) < logWriteMax {
if len(s.buf) < vmlog.WriteMax {
break
}
line, rest = s.buf[:logWriteMax], s.buf[logWriteMax:]
line, rest = s.buf[:vmlog.WriteMax], s.buf[vmlog.WriteMax:]
}
out = appendSSHLine(out, line)
s.buf = rest
@@ -935,7 +940,7 @@ func (l *Links) commandSSH(ctx context.Context, args []string) error {
defer cancel()
out, err := exec.CommandContext(ctx, "ssh", args...).CombinedOutput() //nolint:gosec // devvm's own arguments
if err != nil {
return fmt.Errorf("%w: %s", err, oneLine(out[:min(len(out), logWriteMax)]))
return fmt.Errorf("%w: %s", err, oneLine(out[:min(len(out), vmlog.WriteMax)]))
}
return nil
}
+4 -3
View File
@@ -24,6 +24,7 @@ import (
"github.com/devvmhq/devvm/internal/leaktest"
"github.com/devvmhq/devvm/internal/proxy"
"github.com/devvmhq/devvm/internal/state"
"github.com/devvmhq/devvm/internal/vmlog"
"github.com/devvmhq/devvm/internal/vmname"
)
@@ -1000,15 +1001,15 @@ func (s *syncBuffer) String() string {
}
// sshLines writes whole lines, each behind sshPrefix, cuts one past
// logWriteMax, and drops the carriage return ending one.
// vmlog.WriteMax, and drops the carriage return ending one.
func TestSSHLines(t *testing.T) {
var b strings.Builder
s := &sshLines{w: &b}
for _, p := range []string{"a\r\nb", "c\n", strings.Repeat("x", logWriteMax+1), "\nend"} {
for _, p := range []string{"a\r\nb", "c\n", strings.Repeat("x", vmlog.WriteMax+1), "\nend"} {
_, _ = s.Write([]byte(p))
}
s.flush()
want := "ssh: a\nssh: bc\nssh: " + strings.Repeat("x", logWriteMax) + "\nssh: x\nssh: end\n"
want := "ssh: a\nssh: bc\nssh: " + strings.Repeat("x", vmlog.WriteMax) + "\nssh: x\nssh: end\n"
if b.String() != want {
t.Errorf("got %q, want %q", b.String(), want)
}
+2 -1
View File
@@ -30,7 +30,7 @@ internal/platform 90.4
internal/ports 92.6
internal/project 98.5
internal/proxy 93.6
internal/redact 98.3
internal/redact 98.9
internal/safefile 97.7
internal/secrets 93.4
internal/settings 96.4
@@ -49,6 +49,7 @@ internal/ui 97.2
internal/upgrade 93.8
internal/upgrade/upgradetest 97.4
internal/vm 88.4
internal/vmlog 95.8
internal/vmname 100.0
internal/vmssh 92.6
packaging 71.4
+1
View File
@@ -49,6 +49,7 @@ internal/ui 94.6
internal/upgrade 93.2
internal/upgrade/upgradetest 97.4
internal/vm 87.5
internal/vmlog 91.1
internal/vmname 100.0
internal/vmssh 88.7
packaging 71.4