chore: CI time zones, test isolation from the repo, a flaky test and the agents page (#45)

Upkeep: CI, flaky tests, dead code and the coding agents page.

- test: tests never run git on the repo they're run from. A git that
  runs the tests (a hook, git rebase --exec) sets GIT_DIR and friends,
  and the tests' plain git followed them into the real repo's config.
  Every test's git now runs through internal/stubtest (Git, GitEnv,
  NoGitRepo), the structure test enforces it, and the whole suite
  passes with GIT_DIR pointing at a decoy repo that stays untouched.
- ci: two test jobs instead of three: Linux in America/Los_Angeles
  (DST) and macOS in UTC, with lint on both, since golangci-lint checks
  only the runner's OS's files.
- test(e2e): accept Codex 0.167's wording for an API-key login.
- test: internal/safefile's swap-after-look branch is tested on purpose
  through a seam, so its coverage no longer depends on a race (97.7%
  every run).
- test(fetch): TestRetryUnanswered's "no answer" comes from a listener
  that keeps its port, so a parallel test's server can no longer take
  the freed port and answer in its place (Linux reuses ports at once).
- refactor(proxy): the test-only policy.decide and policy.byRequest
  move to the tests; the proxy already judges a host from one read of
  the rules (rulesFor).
- docs(agents): "Pasting images" moves down the coding agents page,
  before History, and its run of paragraphs becomes commands and
  lists, every fact and anchor kept.

Gate and coverage pass on each commit; e2e `network` and `project` pass
on Linux (251 passed, 4 macOS-only skips).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
This commit is contained in:
CJandClaude Opus 5.5 authored and GitHub committed 2026-11-12 07:20:42 -07:00
1 parent 2f0cc97392
commit 2b49967b4e
35 files changed
+473 -126

No files matched your search

+5 -5
View File
@@ -26,15 +26,16 @@ concurrency:
jobs:
check:
# The tests run in UTC, then again on Linux in a zone with DST, so a
# test that depends on the zone fails here, not only on a laptop.
# The tests run on macOS in UTC and on Linux in a zone with DST, so a
# test that depends on the zone fails here, not only on a laptop. Lint
# runs on both, because golangci-lint checks only the files built for
# the runner's OS, such as internal/platform's *_darwin.go or *_linux.go.
strategy:
fail-fast: false
matrix:
include:
- { os: ubuntu-latest, tz: UTC }
- { os: macos-latest, tz: UTC }
- { os: ubuntu-latest, tz: America/Los_Angeles }
- { os: macos-latest, tz: UTC }
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -44,7 +45,6 @@ jobs:
with:
version: 2026.10.18
- run: mise run lint
if: matrix.tz == 'UTC'
- run: mise run test
env:
TZ: ${{ matrix.tz }}
+2 -2
View File
@@ -107,10 +107,10 @@ An owner gets a check only when a second copy would be a bug or a security hole,
| forbidigo, HTTP clients | `internal/fetch`, whose `NewClient` sets each client's timeout and redirect policy (`HTTPSOnly` or `SameScheme`), and whose `Retry`, `Transient`, `ReadCapped`, `Get`, `Resolve` and `Download` try again after the failures that may pass, cap what a body or a download may hold, follow a HEAD's redirects to where they end and check a download's SHA-256 before anything uses it. `fetch.Client` is its own type, so a client that `NewClient` didn't make, such as `&fetch.Client{}`, fails every request, and a caller changes a client's transport through its `Transport` method | `internal/proxy`, which is the standard library only, and tests, which make their own servers' clients |
| forbidigo, `os.WriteFile`, `os.Create` and `os.O_TRUNC` | `internal/state`, whose `WriteFile` and `WriteFileMode` write a file whole through a temporary file in its folder, renamed over it, so a reader never sees half of it | `internal/proxy`, which imports only the standard library and has its own writer, `writeAtomic`; `internal/msg/gen`, which imports no devvm package; `internal/stubtest`; tests; and, with a `nolint` saying why, a file written another way: a log that a process writes as it runs, a download that streams into its file, and `internal/daemon`'s pid and status files, each written in one write that a reader takes as missing until its line ends |
| forbidigo, `os.Open`, `os.OpenFile`, `os.ReadFile`, `os.OpenRoot`, `os.OpenInRoot`, `os.DirFS` and `os.Root`'s `Open`, `OpenFile`, `ReadFile` and `FS`, in the code that reads files a VM can write or swap: `internal/gitprotect`, `internal/agentlogin`, `internal/vm`'s `devcontainer.go`, `detect.go`, `paste.go` and `agentsave*.go`, `internal/netpolicy/rules.go`, and `internal/proxy`'s `config.go` and `policy.go` | `internal/safefile`, which imports only the standard library, so the proxy reads with it too. Its `Read` and `Open` open a file without blocking and, unless the caller passes `Follow`, without following a symbolic link at the path's end. They then check the file they opened, not its name, so a FIFO, a device or a folder is refused with `ErrNotRegular`, a file past its cap with `ErrTooLong`, and, with `OneLink`, a file with another hard link with `ErrLinked`. A FIFO that the VM swaps in after a check can't hold devvm, and a link to `/dev/zero` can't flood it. `Checked` checks a file its caller opened another way in the same way, such as devvm paste's copied file, which `platform.OpenNoLinks` opens following no link but the system's, through `openat`, which the standard library doesn't have on macOS. `OpenRoot` opens beneath a folder through `os.Root`, never through a link out of it, and its `FS` lists and stats what's there but opens only regular files | every other file, which is devvm's own or the user's; tests, which make their own fixtures; and, with a `nolint` saying why, what opens a file to write it or a folder to lock it |
| forbidigo, `os.Setenv`, `os.Unsetenv`, `os.Clearenv` and `syscall`'s | each command's own environment, its `exec.Cmd`'s `Env`, because every command and background process devvm starts inherits devvm's. A VM's SSH agent is one: the finder's `target` carries its socket, which goes to the backend in `backend.ExecOpts.Agent`, `backend.ShellOpts.Agent` and `Confinement.AgentSocket`, and Lima sets `SSH_AUTH_SOCK` on that VM's `limactl` commands alone, so a run that reaches several VMs never gives one another's | `daemon.Ready` in `internal/daemon/status.go`, which takes the status file's name out of a background process's own environment, and tests, which use `t.Setenv` |
| forbidigo, `os.Setenv`, `os.Unsetenv`, `os.Clearenv` and `syscall`'s | each command's own environment, its `exec.Cmd`'s `Env`, because every command and background process devvm starts inherits devvm's. A VM's SSH agent is one: the finder's `target` carries its socket, which goes to the backend in `backend.ExecOpts.Agent`, `backend.ShellOpts.Agent` and `Confinement.AgentSocket`, and Lima sets `SSH_AUTH_SOCK` on that VM's `limactl` commands alone, so a run that reaches several VMs never gives one another's | `daemon.Ready` in `internal/daemon/status.go`, which takes the status file's name out of a background process's own environment; `stubtest.NoGitRepo`, which takes git's variables that pick a repo out of a test's environment until the test ends; and tests, which use `t.Setenv` |
| the structure test's `owners`, host commands | the runners: the UI's `LoggedCmd`, which a package takes as a field and which runs a command into the run log, a backend's `Runner`, and `internal/hostgit`. A host command that one of them doesn't run is made only in the files `execSites` lists: those that make the command a runner then runs, such as Lima's `limactl` and mise's, and those whose command can't go into the run log, because it streams for as long as a link, the port forwarder or the desktop's relay lasts, asks on the terminal, outlives the run, or carries a secret | tests |
| the structure test's `owners`, a backend's other interfaces | `backend.As` in `internal/backend/guard.go`, because the registry's backends are behind its guard, whose type has only `backend.Backend`'s methods, so a type assertion to `backend.Forgetter` or `*lima.Lima` on one is always false | tests |
| the structure test's `owners`, git | `internal/hostgit`, which runs git without the repo's fsmonitor, hooks or filters, over ssh only, without the environment's `GIT_*` variables and prompts | tests, which run git to make their repos |
| the structure test's `owners`, git | `internal/hostgit`, which runs git without the repo's fsmonitor, hooks or filters, over ssh only, without the environment's `GIT_*` variables and prompts. In tests, which run plain git to make their repos, it's `internal/stubtest`'s `Git`, which leaves out git's variables that pick a repo, its files or its config (`GitEnv`), so a git that runs the tests, such as a hook's or `git rebase --exec`'s, never sends a test's git to the checkout itself | nothing else |
| forbidigo, `os.UserHomeDir`, and the structure test's `owners`, `HOME` | `paths.FromEnv` in `internal/paths/dirs.go`, which reads `HOME` once into `paths.Dirs.Home`, so a test or an e2e run that sets its own `HOME` moves every path devvm takes from it | tests |
| the structure test's `owners`, `DEVVM_` variables | `readOverrides` in `internal/cli/overrides.go`, which reads a test build's stand-ins, while a release reads none | the settings in `envSettings`, and tests |
| the structure test's `owners`, shell quoting | `internal/shell`, whose `Quote` and `QuoteJoin` quote words for a POSIX shell, so a value never runs as a command | tests |
+1 -1
View File
@@ -279,7 +279,7 @@ To go back to the large host later in the same script, set the large values agai
## Any time zone
The tests pass in any time zone and on any date, because a test that compares times counts them from an instant it parsed or fixed, or works in UTC, and never sets `time.Local`. A testscript that needs an old file uses a date far in the past, such as `touch -t 202001010000`, and one that needs a file that stays new uses a date far in the future, such as an export named `20991231-235959`, so the scripts keep passing as the calendar moves on. CI runs `mise run test` in UTC on macOS and Linux, and a third job runs it on Linux with `TZ=America/Los_Angeles`, which has daylight saving time, so a test that only passes in one zone fails in CI and not only on a laptop. To check a change the same way, run the tests with another zone, including one with an odd offset or a half-hour DST change:
The tests pass in any time zone and on any date, because a test that compares times counts them from an instant it parsed or fixed, or works in UTC, and never sets `time.Local`. A testscript that needs an old file uses a date far in the past, such as `touch -t 202001010000`, and one that needs a file that stays new uses a date far in the future, such as an export named `20991231-235959`, so the scripts keep passing as the calendar moves on. CI runs `mise run test` on macOS in UTC and on Linux with `TZ=America/Los_Angeles`, which has daylight saving time, so a test that only passes in one zone fails in CI and not only on a laptop. To check a change the same way, run the tests with another zone, including one with an odd offset or a half-hour DST change:
```sh
TZ=America/Los_Angeles mise run test
+1
View File
@@ -9,6 +9,7 @@ weight: 6
Every change to devvm's logic comes with a test, and Go tests are table tests next to the code they test. Neither the Go tests nor the [CLI tests](#cli-tests) touch the Keychain, real VMs or your own folders. A Go test that writes state points the XDG folders at `t.TempDir()`, and a Go test makes VMs only on the fake backend, `backendtest`. The CLI tests run the built devvm against the [stubs](#stubs), so only the [end-to-end tests](#end-to-end-tests) make real VMs. The Go tests share a few helpers, so each one reads the same way:
- **`stubtest.New(t)`** puts the [stubs](#stubs) first on `PATH` for one test, as the CLI tests have them, with a new folder under `/tmp` as their `STUB_DIR` and its `calls` file as their `STUB_LOG`. The folder goes when the test ends. `stubtest.New(t, "ssh")` puts only the stubs it names on `PATH`, so the host's other commands, such as git, stay. Its `Calls` returns the calls the stubs logged, `Reset` forgets them, and `Touch`, `Write` and `Read` work on the files the stubs read, such as a switch, a file whose presence makes a stub fail. `VM`, `Size` and `VMs` set and read Lima's instances in the stubs' state, and `Keychain` and `SetKeychain` the Keychain's items. `stubtest.Command(t, "mise")` returns the path of one stub, for a test that runs it by its path, as `DEVVM_HOST_MISE` does.
- **`stubtest.Git(ctx, args...)`** is plain git for a test's own repo, and a test runs git only through it, which the structure test checks. Its environment is the test's without git's variables that pick a repo, its files or its config, such as `GIT_DIR`, `GIT_WORK_TREE` and `GIT_CONFIG_PARAMETERS` (`stubtest.GitEnv`), and it reads no global or system config. A git that runs the tests, such as a hook's or `git rebase --exec`'s, sets some of those variables, and a test's git that kept them would work on the checkout itself, writing its config and commits there. A test that runs something else that runs git, such as a script or a stub, calls `stubtest.NoGitRepo(t)` first, which takes the same variables out of the test's environment until it ends, and `stubtest.New` calls it for the stubs. The CLI tests' environment leaves them out too.
- **`stubtest.ExecRunner`** is a backend's runner that runs each command as it is, with no run log, so a backend under test runs the stubs.
- **`msg.IDOf(err)`** returns the ID of the message an error carries, or "" when it carries none, and **`msg.NamesOf(err)`** returns the message's names, as names mode prints them, or the error's own text when it isn't a message. A test compares either with what it expects.
- **A `msg.Fake`** is the `msg.Reporter` a package under test prints and asks through. Its zero value is quiet: it prints nothing, has no terminal, so it refuses every question as the UI does where it can't ask, and runs a logged command as it is. Its fields change that: `OnInfo`, `OnWarn` and the other `On` funcs are given each message or question of their kind, with a question's context going to `OnNote` first, `OnAny` every message, and `Terminal`, `Picks`, `Interrupt` and the writers stand for the terminal, the picker, an interrupt and the output.
+2 -2
View File
@@ -186,7 +186,7 @@ A rule can narrow a host name to some of its requests, by method, by path or bot
- **Allows add up, and a deny beats any allow, as before.** An allow that narrows allows its host for the connection and only its requests one by one, and a deny that narrows refuses only its requests. So narrowing a host that a rule allows whole, devvm's built-in GitHub among them, takes a deny, and devvm network allow warns when an allow by method and path would narrow nothing because the VM's allowlist, or every VM's with `-g`, allows its host whole (`proxy.Allowlist.CoversWhole`, `rule_narrows_nothing`). An allow that replaced the whole allows of earlier policies was ruled out: adding an allow would then take access away, and a user's file would silently override devvm's.
- **Methods from a closed list.** `proxy.Methods` are RFC 9110's, `PATCH` and `QUERY`, without `CONNECT`. A method outside them isn't a rule, so a typo in a deny, such as `PSOT`, is a broken deny, which denies everything until it's fixed, rather than a deny of nothing.
- **Paths as patterns, judged only in a plain form.** `*` within a segment, `**` for one segment or more, and a last `/` for everything below, which is what a binding's path below which its value goes in already meant. Rather than decode and clean a path, which servers do differently, the matcher takes only a path that every server reads alike (`plainPath`), as custom secrets' `--path` did. An allow, and a binding, match exactly, in case too, and never a path in another form, while a deny matches broadly, so each fails closed in its own direction. A deny matches in any case, every path that isn't plain, the path above one that ends with `/`, as `/gists` is to `/gists/` for most servers, and a last segment cut at its first `.`, as Rails and Spring route `/admin.json` to `/admin` and some servers drop a trailing dot. Cutting at the first dot rather than the last covers `/admin.tar.gz` too, and it refuses a few more requests than a deny names, which is the side a deny errs on. The cost is that a request to a host with path rules whose path has an encoded character, such as a file name with a space, is refused unless a rule without a path allows it.
- **Rules that need requests force interception, or a refusal.** A host whose requests the rules judge (`policy.byRequest`) is decrypted on `:443` with the VM's CA, and refused on any other port and without a CA, never tunneled unjudged. A host that a whole allow covers, with no deny that narrows, stays a tunnel, so the cost falls only where the rules need it. No host is spliced by name: devvm already decrypts GitHub, Anthropic's API and the agents' token endpoints for secrets, and git, the GitHub CLI and Claude Code work through it. A client that pins its certificates or ignores the VM's CA fails its handshake, which `devvm network log` shows as `TLS with the VM failed`, so devvm notes that a host is now decrypted when a rule narrows it (`rule_narrows`) rather than refusing the rule. Addresses, CIDRs and `**` can't narrow, because an address has no name to make a certificate for and `**` would decrypt every host.
- **Rules that need requests force interception, or a refusal.** A host whose requests the rules judge (`hostRules.byRequest`) is decrypted on `:443` with the VM's CA, and refused on any other port and without a CA, never tunneled unjudged. A host that a whole allow covers, with no deny that narrows, stays a tunnel, so the cost falls only where the rules need it. No host is spliced by name: devvm already decrypts GitHub, Anthropic's API and the agents' token endpoints for secrets, and git, the GitHub CLI and Claude Code work through it. A client that pins its certificates or ignores the VM's CA fails its handshake, which `devvm network log` shows as `TLS with the VM failed`, so devvm notes that a host is now decrypted when a rule narrows it (`rule_narrows`) rather than refusing the rule. Addresses, CIDRs and `**` can't narrow, because an address has no name to make a certificate for and `**` would decrypt every host.
- **Methods a request names besides its own.** Some frameworks take the method from a header, `X-HTTP-Method-Override` and its kin, which Rack and CGI read with `_` for `-`, or from a `_method` parameter. The proxy reads every override-like header (`overrideLike`) and the query's `_method`, and while a rule narrows a host by method, it refuses a request whose value isn't exactly one method, such as a list, which servers read apart, rather than guess. Judging a `_method` in the query, rather than refusing every request with one, keeps a `GET` that names `GET` working, and an allow still needs every method named to be its own. A form's `_method` in a `POST`'s body isn't read: the proxy forwards bodies unread, so it's judged as the `POST` it is.
- **Every request is judged.** The intercepted tunnel's own HTTP server calls the handler for each request, HTTP/1.1 kept alive or HTTP/2, and so does each absolute-form request, so the rules and the bindings are asked for each one, with the files as they are then. A connection's verdict and whether its requests are judged come from one read of the files (`hostRules`). A WebSocket is judged by its upgrade request, and an upgrade to anything else, such as `h2c`, and a `CONNECT` inside the tunnel are refused, as the bytes after them would pass unread. A tunnel opened before a rule narrowed its host stays a tunnel until it closes, as tunnels do for every new deny, and `rule_narrows` says so. The shared Nix cache's own fetch from cache.nixos.org is judged as a `GET` of the path the VM asked for, so its rules apply there too.
- **A proxy from another binary.** A running proxy is the devvm binary that started it, and one from before this change reads a rule by method and path as a line that isn't a rule: an allow it skips and a deny that denies everything. So devvm network allow, deny and rm warn, naming the VM, when they change such a rule while the VM's proxy runs from another binary than their own (`proxy_other_binary`, by the `devvm_sha256` of the config it started with, and when that config or this binary can't be read, as devvm can't tell), and the VM's next launch starts the proxy again. A change to a host's rule doesn't warn, as every binary reads it alike. The bindings file stays version 1 while every binding has no methods and no path but a prefix longer than `/` that ends with `/` and has no `*`, so devvm secret set and rm, which write every VM's file, don't take an older proxy's bindings away, logins included. Such a file reads alike to a proxy from after bindings gained paths; a 0.1.0 proxy ignores the path, which for the built-in bindings only widens OpenRouter's key to all of openrouter.ai, as 0.1.0 bound it, until the VM starts again. Writing version 2 instead would cut those proxies' logins. It's version 2 only for a binding with methods or a pattern, which such a proxy refuses, so it puts no value in rather than put one in for every method, and devvm warns about each such VM whenever it writes one, from devvm secret set, rm and use or devvm agent login --api-key (`Proxy.SecretsWritten`, `secrets_other_binary`). A path of `/`, which that proxy's prefix check refused with the whole file, is no path, as it's every path. A custom secret's path that devvm writes is marked a pattern (`path_pattern`), so a path saved as a prefix whose `*` was itself is refused rather than read as a wildcard.
@@ -331,7 +331,7 @@ The tier holds as it is: the VM's proxy decides each request the local proxy sen
On macOS, `clipboard_darwin.go` runs `osascript` with a JavaScript for Automation script through `NSPasteboard`. The script takes a PDF (`com.adobe.pdf`) first, as it is, before the picture of it and the temporary file of its own that Preview puts beside it. Then it asks for file URLs alone (`readObjectsForClasses` with `NSPasteboardURLReadingFileURLsOnlyKey`), counts several and reports one's path. Otherwise it writes a PNG, JPEG, GIF or WebP as it is, or a TIFF made a PNG, to a file in a private folder devvm makes and deletes, only when it's within the cap. The copy back is `pbcopy`. Both tools run by their paths in `/usr/bin`, never found on `PATH`.
On Linux, `clipboard_linux.go` runs `wl-paste --list-types` and `--type` on Wayland, and `xclip`'s `TARGETS` and `-t` on X11, taking `application/pdf` before a file reference and the image types. The copy back is `wl-copy` or `xclip -i`. Each comes from the first of `/usr/bin`, `/bin`, `/usr/local/bin` and `/run/current-system/sw/bin` that has it, never from `PATH`, because `PATH` can hold a project's folder, such as direnv's `PATH_add` or `node_modules/.bin`, and the VM writes those.
On Linux, `clipboard_linux.go` runs `wl-paste --list-types` and `--type` on Wayland, and `xclip`'s `TARGETS` and `-t` on X11, taking `application/pdf` before a file reference and the image types. The copy back is `wl-copy` or `xclip -i`. Each comes from the first of `/usr/bin`, `/bin`, `/usr/local/bin` and NixOS's `/run/current-system/sw/bin` that has it, never from `PATH`, because `PATH` can hold a project's folder, such as direnv's `PATH_add` or `node_modules/.bin`, and the VM writes those.
Every clipboard tool runs with `exec.CommandContext` (`clipboard_tool.go`), and devvm reads its output, never through the run log, so the image stays out of it. Each tool is stopped after 30 seconds, as a tool waits on a program that holds the clipboard and doesn't answer: a read gives `paste_tool_slow`, and a copy back gives a warning. Its pipes are closed a second after it ends, as a child of its may keep them.
+1 -1
View File
@@ -148,7 +148,7 @@ Each change that `devvm network allow`, `deny` or `rm` makes rewrites the file w
A rule for a host name or `*.name` can have its methods and then its path after it, each after spaces or tabs, such as `api.github.com GET,HEAD /repos/` ([rules by method and path](../safety/network.md#rules-by-method-and-path)). `proxy.ParsePolicy` reads such a line as one rule, whose text is its canonical form: the host as before, the methods in capitals in `proxy.Methods`' order, and the path as written, joined by one space. That's what `devvm network allow`, `deny` and `rm` write from `--method` and `--path` (`proxy.NarrowRule`), and what they compare a line by, so `HEAD,get` and `GET,HEAD` are the same rule. A method outside `proxy.Methods`, `CONNECT` among them, an address, a CIDR or `**` with methods or a path, and a path that isn't a pattern (`proxy.PathOK`) aren't rules, so a typo in a deny is a broken deny, which denies everything, rather than a deny of nothing.
The proxy judges a host in two steps. For the connection, `CONNECT host:port` or an absolute-form request, a deny that narrows doesn't refuse the host, and an allow that narrows allows it, so a host that only rules by method and path allow is reached. Its requests are then judged one by one (`policy.judge`) when a rule that narrows covers the host and either it's a deny or no rule allows the whole host (`policy.byRequest`). Both come from one read of the policy files (`policy.rulesFor`, a `hostRules`), so a file that changes between the two can't give the connection one rule's verdict and another's way through. Such a host's `CONNECT` on a port the proxy intercepts, `:443`, is intercepted with the VM's CA, as a bound host's is, and on any other port, or without a CA, it's refused with `403`, logged as a refused block, because the proxy can't see the requests in it. An absolute-form request, plain HTTP on any port or `https://`, is judged before it's forwarded.
The proxy judges a host in two steps. For the connection, `CONNECT host:port` or an absolute-form request, a deny that narrows doesn't refuse the host, and an allow that narrows allows it, so a host that only rules by method and path allow is reached. Its requests are then judged one by one (`policy.judge`) when a rule that narrows covers the host and either it's a deny or no rule allows the whole host (`hostRules.byRequest`). Both come from one read of the policy files (`policy.rulesFor`, a `hostRules`), so a file that changes between the two can't give the connection one rule's verdict and another's way through. Such a host's `CONNECT` on a port the proxy intercepts, `:443`, is intercepted with the VM's CA, as a bound host's is, and on any other port, or without a CA, it's refused with `403`, logged as a refused block, because the proxy can't see the requests in it. An absolute-form request, plain HTTP on any port or `https://`, is judged before it's forwarded.
Inside an intercepted tunnel, the proxy's own HTTP server reads each request, HTTP/1.1 kept alive or HTTP/2, and calls one handler for each, which checks that the request names the host (`421` otherwise), then judges it with the rules as they are then (`server.judgeRequest`), then forwards it. So every request on a connection is judged, not just the first, and a rule added or removed applies from the tunnel's next request. A WebSocket is judged by its upgrade request, after which the proxy passes its bytes as they are, so for a host that rules narrow, an `Upgrade` to any other protocol, such as `h2c`, whose requests would pass the same way, is refused, and so is a `CONNECT` inside the tunnel. A refused request gets `403`, and the event log gets a `blocked` event with its method and path. A deny's refusal is marked refused, so neither the VM's prompt nor `devvm network log --blocked` suggests an allow, and a request that no allow covers suggests the allow of the whole host. An allowed request's `forward` event names the rule that allowed it, as its `rule`.
+104 -50
View File
@@ -20,56 +20,6 @@ In the VM the agent sees only your project folder, and your agents' settings fro
Every VM has a guide to devvm for the agents in it, at `/usr/share/doc/devvm/README.md`, and `devvm-help` in the VM prints it. It tells an agent what a devvm VM is, how its network tiers and secrets work, where its installs go, and which commands to ask you to run on this machine, such as `devvm network allow` for a blocked host or `devvm agent login` for a login. The guide is the same in every VM, so it says nothing about the VM's own tier, ports or layers. Each launch installs it again whenever it differs from devvm's, and it belongs to root and is read-only, so nothing that the VM's user runs without `sudo` can change what the agents read, and a change made with `sudo` lasts only until the next launch. Ask your agent to read it, or to run `devvm-help`, when it doesn't know where it's running. devvm adds nothing about it to the agents' instruction files.
## Pasting images
An agent in the VM can't see this machine's clipboard, so an image you copied, such as a screenshot, gets to it through devvm paste, which sends the image into the VM and copies its path there for you to paste:
1. Copy an image on this machine, such as a screenshot, copy pages in a PDF viewer such as Preview, or copy a file in Finder or your file manager.
2. In a terminal on this machine, run `devvm paste` in the project folder. devvm says where the image is in the VM, such as `/tmp/devvm-paste/paste-20261109-153012-7f3a9c01.png`, and puts that path on your clipboard. If putting it there fails, devvm warns you and still says where the image is, so you can paste that path yourself.
3. Paste the path into the agent with your terminal's paste shortcut, which is Cmd+V on macOS and usually Ctrl+Shift+V on Linux. Ctrl+V on its own asks the agent to read the VM's clipboard, and the VM has none.
Claude Code, Codex and opencode attach an image whose path you paste, and pi reads it with its `read` tool. The VM must be running, because devvm paste is for an agent that runs in it, and devvm refuses a stopped one.
devvm reads only an image, a PDF or a copied file's reference from the clipboard, never text, so a password you copied never reaches it. It checks that an image's or a PDF's bytes are the type the clipboard claims. It takes PNG, JPEG, GIF and WebP images, and on macOS it also takes a TIFF, which many Mac apps copy, and sends it as a PNG. An image, a PDF or a file over 64 MiB is refused.
The app you copied from hands over what you copied when devvm asks for it, and devvm waits for it at most 30 seconds. If the app doesn't answer in that time, devvm stops waiting, sends nothing and says so. Copy it again, or wait until the app responds, then run devvm paste again. On macOS, devvm reads the clipboard with `osascript`, which reaches the clipboard of the session you're logged in to, so run devvm paste in a terminal on that Mac, not over ssh.
What devvm gets depends on the app you copied from. A browser's Copy Image hands over a PNG, never the original JPEG, GIF or WebP, and Safari hands over a TIFF, which devvm makes a PNG, so an animated GIF arrives as one still frame. To send the original, save it and copy the saved file instead. Text is never sent, so paste text, such as an error message, into the agent's terminal yourself.
A PDF on the clipboard, such as pages you copied in Preview, is sent as it is, as a `.pdf` file, because most models read PDFs. A PDF viewer puts a picture of what you copied beside the PDF, and devvm sends the PDF, never the picture. When you copy a page's thumbnail in Preview, Preview also puts a temporary file of its own on the clipboard, and devvm sends the PDF without asking about that file.
A copied file is sent the same way, under a name of devvm's that keeps only the file's extension, when it's letters and digits alone and at most 16 of them. So `my shot (1).png` becomes `paste-20261109-153012-7f3a9c01.png`, and `Makefile` becomes `paste-20261109-153012-7f3a9c01`. Nothing else of the file's name reaches the clipboard, so the path you paste into a terminal is devvm's own and can't run anything, even when the VM named the file in the project folder.
devvm sends one file at a time. It refuses several files, a folder, and a symbolic link anywhere in the file's path, your own included. A file you copy may be in the project folder, which the VM can write, and a link planted there could point at a file of yours. The only links devvm follows are the system's own, which root owns, such as macOS's `/tmp`, so copy the file from the folder it's really in.
On macOS, Finder puts the copied file's icon on the clipboard as an image beside the file, and devvm sends the file, not the icon. If the file is gone by the time you run devvm paste, devvm says so and sends nothing, rather than the icon. Text is never taken for a file, even when it's a path, so copy the file itself in Finder.
Before devvm sends a copied file, it shows the file's path on this machine and asks, [y/N], because the clipboard can name any file of yours, such as a key in `~/.ssh` that you didn't mean to copy. Answer no and nothing is sent. An image or a PDF is sent without a question, because it's only what you copied. A photo you copy in Photos comes with a file of the Photos library beside it, so devvm asks about that file, as it does about any copied file.
`devvm paste --send-file` sends a file in the project folder without asking, as a script must, because the VM can read that folder already. A file anywhere else is still asked about with `--send-file`, so only you can send it, at a terminal. So is a file whose path goes through a symbolic link, even one of the system's that devvm follows, because the file may not be where its path says. Where devvm can't ask, such as without a terminal, it sends nothing. It names `--send-file` for a file in the folder, the file and the folder for one outside it, and the file for one reached through a link. So don't bind `devvm paste --send-file` to a hotkey to send files from outside the project, because a hotkey has no terminal to ask in, and devvm refuses those files. A clone VM, made with `--clone`, doesn't mount the folder, so `--send-file` answers for none of its files.
`devvm paste --json` does the same and prints what it sent as one object, with `"version": 1` first. It has whether anything was `sent`, which is `false` when you answered no about a file, the VM, and the file's `path` in it (`""` when nothing was sent). Then its `kind` (`image`, `pdf` or `file`), an image's or a PDF's `type` (`image/png`, `image/jpeg`, `image/gif`, `image/webp` or `application/pdf`, and `""` for a file), and a copied file's `source`, its path on this machine (`""` otherwise). Last come its size in `bytes`, and whether the path was `copied` to the clipboard:
```json
{"version": 1, "sent": true, "vm": "devvm-website-3f9a1c2b4d5e6f", "path": "/tmp/devvm-paste/paste-20261109-153012-7f3a9c01.png", "kind": "image", "type": "image/png", "source": "", "bytes": 48213, "copied": true}
```
### The paste folder and your agent's settings
The files go into the VM's paste folder, `/tmp/devvm-paste` unless `config.toml`'s `paste-dir` names another ([the paste folder](settings.md#the-paste-folder)). Each launch makes the folder in the VM, mode 700 and yours, and leaves an existing one as it is. The folder is a fixed path so that you can allow it once in an agent's settings. Claude Code refuses to read a path outside the project folder when its `permissions.blockReadsOutsideWorkingDirectories` setting is on, until you add the folder with `/add-dir /tmp/devvm-paste` or list it in `permissions.additionalDirectories` in your settings, which [devvm's agent store](#devvms-agent-store) keeps for every VM. The files keep their mode, 600, so only the VM's user reads them.
Anything in the VM can read what you send, as it can read any file in the project folder, so paste nothing you wouldn't put in the folder.
### Deleting pasted files
devvm never deletes a pasted file on its own, because Codex reads the image when you submit your message and pi when the model calls `read`, which may be some time after the paste. `devvm paste rm` deletes the files devvm paste left in the folder, after asking in a terminal, and `devvm paste rm --force` deletes them without asking, as a script must. It deletes only the files devvm paste named, and nothing else in the folder, so a `paste-dir` of your own, such as `/home/USER/pastes` where `USER` is your user in the VM, can hold other files.
The VM's `/tmp` is emptied when the VM boots, so with the default folder the files are gone after a restart anyway. With a `paste-dir` of your own, they stay. A command that starts a stopped VM and opens its shell offers to delete them, [y/N], once the VM is set up. Those commands are `devvm`, `devvm restart`, `devvm tools`, `devvm tools add`, `devvm tools rm` and `devvm tools update`, `devvm layer add` and `devvm layer rm`, `devvm update`, and `devvm clone on` and `devvm clone off`. Without a terminal, devvm keeps the files and says nothing, and if deleting them fails, it warns you and opens the shell anyway. Commands that start a VM without opening its shell, such as `devvm code` and `devvm agent save`, don't ask, so run `devvm paste rm` when you want the files gone.
### On Linux
devvm reads and writes the clipboard with `wl-paste` and `wl-copy` in a Wayland session, which `WAYLAND_DISPLAY` names, and with `xclip` in an X11 session, which `DISPLAY` names. It looks for them only in the system's folders, `/usr/bin`, `/bin`, `/usr/local/bin` and NixOS's `/run/current-system/sw/bin`, and never elsewhere on your `PATH`, where a folder the VM can write, such as a project's `node_modules/.bin`, might come first. It tells you which one is missing, and installs nothing itself, so install `wl-clipboard` or `xclip` with your distribution's package manager. Run devvm paste from a terminal in your desktop session, because without either variable there's no clipboard to read. If `WAYLAND_DISPLAY` or `DISPLAY` names a session that's over, as in a tmux window left from an earlier login, devvm tells you that `wl-paste` or `xclip` failed and what it said, rather than that the clipboard is empty. Copying the path leaves `wl-copy` or `xclip` running until you copy something else, because a Linux clipboard's contents live in the program that copied them.
## Supported agents
A new VM gets an agent when you choose it as you customize the VM, or when you name it with `--agents`. A VM that exists gets one from `devvm tools`, which shows the same list with the VM's agents already chosen, or from `devvm tools add`:
@@ -302,6 +252,110 @@ The placeholder keeps a key out of the VM only from the launch that first gives
With some of these keys, code in the VM can make a credential of its own that works without the proxy. Google Gemini's key gets an ephemeral token for Gemini's Live API, which lasts up to about 20 hours and allows as many uses as the VM asks for. xAI's key gets a realtime client secret that lasts as long as the VM chooses, and OpenAI's key gets one that lasts up to 2 hours. opencode's experimental voice mode asks for these itself, so the proxy allows those requests ([attack vectors](../safety/attack-vectors.md#secrets-and-keys-the-vm-may-use)). Some of these providers' own tools also fetch the URLs that a request names, such as Google Gemini's URL context and Search grounding, xAI's live search, Groq's compound models and Mistral's agents with web search, so code in the VM can reach hosts that the allowlist doesn't have through them, as it can through Anthropic's and OpenAI's.
## Pasting images
An agent in the VM can't see this machine's clipboard, so an image you copied, such as a screenshot, gets to it through devvm paste, which sends the image into the VM and copies its path there for you to paste:
1. Copy an image on this machine, such as a screenshot, copy pages in a PDF viewer such as Preview, or copy a file in Finder or your file manager.
2. In a terminal on this machine, run `devvm paste` in the project folder. devvm says where the image is in the VM, such as `/tmp/devvm-paste/paste-20261109-153012-7f3a9c01.png`, and puts that path on your clipboard. If putting it there fails, devvm warns you and still says where the image is, so you can paste that path yourself.
3. Paste the path into the agent with your terminal's paste shortcut, which is Cmd+V on macOS and usually Ctrl+Shift+V on Linux. Ctrl+V on its own asks the agent to read the VM's clipboard, and the VM has none. Claude Code, Codex and opencode attach an image whose path you paste, and pi reads it with its `read` tool.
The VM must be running, because devvm paste is for an agent that runs in it, and devvm refuses a stopped one.
```sh
devvm paste # send what you copied, asking first about a copied file
devvm paste --send-file # send a file in the project folder without asking, as a script must
devvm paste --json # the same, and print what it sent
devvm paste rm # delete the files devvm paste left in the VM, after asking
```
### What devvm paste sends
devvm reads only an image, a PDF or a copied file's reference from the clipboard, never text, so a password you copied never reaches it:
- **An image**: PNG, JPEG, GIF or WebP, and on macOS also a TIFF, which many Mac apps copy, sent as a PNG.
- **A PDF**, such as pages you copied in Preview, sent as it is, as a `.pdf` file, because most models read PDFs.
- **One copied file**, after devvm asks you about it.
- **Nothing over 64 MiB**, whether it's an image, a PDF or a file.
devvm checks that an image's or a PDF's bytes are the type the clipboard claims ([how](../internals/design.md#pasting-images)). Text is never sent, so paste text, such as an error message, into the agent's terminal yourself. The app you copied from hands over what you copied when devvm asks for it, and devvm waits for it at most 30 seconds, then stops waiting, sends nothing and says so, so copy it again, or wait until the app responds, then run devvm paste again. On macOS, devvm reads the clipboard of the session you're logged in to, so run devvm paste in a terminal on that Mac, not over ssh.
What devvm gets depends on the app you copied from:
- **A browser's Copy Image** hands over a PNG, never the original JPEG, GIF or WebP, and Safari hands over a TIFF, which devvm makes a PNG, so an animated GIF arrives as one still frame. To send the original, save it and copy the saved file instead.
- **A PDF viewer** puts a picture of what you copied beside the PDF, and devvm sends the PDF, never the picture. When you copy a page's thumbnail in Preview, Preview also puts a temporary file of its own on the clipboard, and devvm sends the PDF without asking about that file.
- **Finder**, on macOS, puts the copied file's icon on the clipboard as an image beside the file, and devvm sends the file, not the icon. If the file is gone by the time you run devvm paste, devvm says so and sends nothing, rather than the icon. Text is never taken for a file, even when it's a path, so copy the file itself in Finder.
- **Photos** puts a file of the Photos library beside a photo you copy, so devvm asks about that file, as it does about any copied file.
### Copied files
Before devvm sends a copied file, it shows the file's path on this machine and asks, [y/N], because the clipboard can name any file of yours, such as a key in `~/.ssh` that you didn't mean to copy. Answer no and nothing is sent. An image or a PDF is sent without a question, because it's only what you copied.
devvm sends a copied file under a name of its own that keeps only the file's extension, when it's letters and digits alone and at most 16 of them, so `my shot (1).png` becomes `paste-20261109-153012-7f3a9c01.png`, and `Makefile` becomes `paste-20261109-153012-7f3a9c01` ([why](../internals/design.md#pasting-images)). It sends one file at a time, and it refuses:
- several files;
- a folder;
- a file with a symbolic link anywhere in its path, your own included, because a link the VM planted in the project folder could point at a file of yours. The only links devvm follows are the system's own, which root owns, such as macOS's `/tmp`, so copy the file from the folder it's really in.
`devvm paste --send-file` answers the question for a file in the project folder, which it sends without asking, as a script must, because the VM can read that folder already. It doesn't answer for the rest:
- **A file anywhere else** is still asked about, so only you can send it, at a terminal.
- **A file whose path goes through a symbolic link** is asked about too, even through one of the system's that devvm follows, because the file may not be where its path says.
- **A clone VM's files**, because a clone VM, made with `--clone`, doesn't mount the folder.
Where devvm can't ask, such as without a terminal, it sends nothing, and it names `--send-file` for a file in the folder, the file and the folder for one outside it, and the file for one reached through a link. So don't bind `devvm paste --send-file` to a hotkey to send files from outside the project, because a hotkey has no terminal to ask in, and devvm refuses those files.
### devvm paste --json
`devvm paste --json` does the same and prints what it sent as one object, with `"version": 1` first. It has whether anything was `sent`, which is `false` when you answered no about a file, the VM, and the file's `path` in it (`""` when nothing was sent). Then its `kind` (`image`, `pdf` or `file`), an image's or a PDF's `type` (`image/png`, `image/jpeg`, `image/gif`, `image/webp` or `application/pdf`, and `""` for a file), and a copied file's `source`, its path on this machine (`""` otherwise). Last come its size in `bytes`, and whether the path was `copied` to the clipboard:
```json
{"version": 1, "sent": true, "vm": "devvm-website-3f9a1c2b4d5e6f", "path": "/tmp/devvm-paste/paste-20261109-153012-7f3a9c01.png", "kind": "image", "type": "image/png", "source": "", "bytes": 48213, "copied": true}
```
### The paste folder and your agent's settings
The files go into the VM's paste folder, `/tmp/devvm-paste` unless `config.toml`'s `paste-dir` names another ([the paste folder](settings.md#the-paste-folder)), and they keep their mode, 600, so only the VM's user reads them. The folder is a fixed path so that you can allow it once in an agent's settings. Claude Code refuses to read a path outside the project folder when its `permissions.blockReadsOutsideWorkingDirectories` setting is on, until you add the folder in Claude Code:
```text
/add-dir /tmp/devvm-paste
```
Or list it in `permissions.additionalDirectories` in your settings, which [devvm's agent store](#devvms-agent-store) keeps for every VM, in `~/.config/devvm/agents/claude/.claude/settings.json`:
```json
{ "permissions": { "additionalDirectories": ["/tmp/devvm-paste"] } }
```
Anything in the VM can read what you send, as it can read any file in the project folder, so paste nothing you wouldn't put in the folder.
### Deleting pasted files
```sh
devvm paste rm # delete the files devvm paste left in the folder, after asking in a terminal
devvm paste rm --force # delete them without asking, as a script must
```
devvm never deletes a pasted file on its own, because Codex reads the image when you submit your message and pi when the model calls `read`, which may be some time after the paste. devvm paste rm deletes only the files devvm paste named, and nothing else in the folder, so a `paste-dir` of your own, such as `/home/USER/pastes` where `USER` is your user in the VM, can hold other files. The VM's `/tmp` is emptied when the VM boots, so with the default folder the files are gone after a restart anyway. With a `paste-dir` of your own, they stay, and a command that starts a stopped VM and opens its shell offers to delete them, [y/N], once the VM is set up. Those commands are:
- `devvm` and `devvm restart`;
- `devvm tools`, `devvm tools add`, `devvm tools rm` and `devvm tools update`;
- `devvm layer add` and `devvm layer rm`;
- `devvm update`;
- `devvm clone on` and `devvm clone off`.
Without a terminal, devvm keeps the files and says nothing, and if deleting them fails, it warns you and opens the shell anyway. Commands that start a VM without opening its shell, such as `devvm code` and `devvm agent save`, don't ask, so run `devvm paste rm` when you want the files gone.
### On Linux
devvm reads and writes the clipboard with `wl-paste` and `wl-copy` in a Wayland session, which `WAYLAND_DISPLAY` names, and with `xclip` in an X11 session, which `DISPLAY` names. It tells you which one is missing, and installs nothing itself, so install `wl-clipboard` or `xclip` with your distribution's package manager:
```sh
sudo apt install wl-clipboard # or xclip for X11; dnf, pacman and zypper have both
```
devvm looks for them only in the system's folders, never elsewhere on your `PATH` ([which folders, and why](../internals/design.md#pasting-images)). Run devvm paste from a terminal in your desktop session, because without either variable there's no clipboard to read. If `WAYLAND_DISPLAY` or `DISPLAY` names a session that's over, as in a tmux window left from an earlier login, devvm tells you that `wl-paste` or `xclip` failed and what it said, rather than that the clipboard is empty. Copying the path leaves `wl-copy` or `xclip` running until you copy something else, because a Linux clipboard's contents live in the program that copied them.
## History
Each VM's transcripts and sessions stay in that VM. `devvm history export [FILE]` saves them, and `devvm rm` saves them before it deletes a VM that has an agent. The export is a `.tar.gz` of `~/.claude`, `~/.claude.json`, `~/.codex`, `~/.local/share/opencode`, `~/.local/state/opencode` and pi's sessions, `~/.pi/agent/sessions`, in the VM, written to FILE or to `~/.local/share/devvm/exports/<vm>-<date>-<time>.tar.gz`. An export in that folder gets a `<vm>-<date>-<time>.folder` file beside it, which names the VM's project folder and the VM's [network tier](../safety/network.md#network-tiers) when devvm wrote the export.
+4 -1
View File
@@ -96,7 +96,10 @@ A mirror can't give base a package that Ubuntu didn't publish. apt checks every
### The paste folder
`paste-dir` is the folder in every VM that [devvm paste](coding-agents.md#pasting-images) puts images, PDFs and copied files in, `/tmp/devvm-paste` unless you set it. Each launch makes the folder in the VM when it's missing, mode 700 and the VM's user's own. It leaves a folder that's there as it is, so a folder of your own, such as `/home/USER/pastes` where `USER` is your user in the VM, keeps its mode and its other files. When what's at the path is a symbolic link, isn't a folder or isn't the VM's user's, a launch warns and devvm paste refuses the folder. A launch also warns when it can't make the folder, as under a file, and in each case the launch goes on.
`paste-dir` is the folder in every VM that [devvm paste](coding-agents.md#pasting-images) puts images, PDFs and copied files in, `/tmp/devvm-paste` unless you set it. Each launch makes the folder in the VM when it's missing, mode 700 and the VM's user's own. It leaves a folder that's there as it is, so a folder of your own, such as `/home/USER/pastes` where `USER` is your user in the VM, keeps its mode and its other files. A launch warns, and goes on, when:
- what's at the path is a symbolic link, isn't a folder or isn't the VM's user's, and devvm paste then refuses the folder;
- it can't make the folder, as under a file.
It's one fixed path for every VM so that you can allow it once in an agent's settings. Give it as an absolute path without a trailing slash, made of letters, digits and `.`, `_` and `-`, and devvm refuses anything else (`config.toml` names the line), because the path goes into a shell in the VM and onto your clipboard. A change applies to each VM at its next launch, which makes the new folder, and devvm paste uses the new folder at once. No command saves it, so it's only ever in `config.toml`.
+7 -3
View File
@@ -81,7 +81,7 @@ func buildDevvm(t *testing.T) string {
args = append(args, coverFlags()...)
}
cmd := exec.CommandContext(t.Context(), "go", append(args, "github.com/devvmhq/devvm/cmd/devvm")...) //nolint:gosec // go install, with the test's own flags
cmd.Env = append(os.Environ(), "CGO_ENABLED=0", "GOBIN="+dir)
cmd.Env = append(stubtest.GitEnv(os.Environ()), "CGO_ENABLED=0", "GOBIN="+dir) // go reads the checkout's own repo to stamp the binary
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("building devvm: %v\n%s", err, out)
}
@@ -146,8 +146,9 @@ func stopLinkSessions(root string) {
}
}
// sandbox points every folder devvm uses into a new temporary folder, and puts
// devvm and the stubs first on PATH.
// sandbox points every folder devvm uses into a new temporary folder, puts
// devvm and the stubs first on PATH, and leaves out git's variables that
// pick a repo (stubtest.GitEnv).
func sandbox(env *testscript.Env, bin, stubs string) error {
// /tmp keeps Lima's socket paths short.
root, err := os.MkdirTemp("/tmp", "dvt.")
@@ -255,6 +256,9 @@ func sandbox(env *testscript.Env, bin, stubs string) error {
}
env.Setenv("DEVVM_REPO", repo) // for the repo's own scripts (scripts/, assets/)
env.Setenv("PATH", strings.Join([]string{bin, stubs, env.Getenv("PATH")}, string(os.PathListSeparator)))
// testscript starts from an environment of its own, but a script's git
// never gets git's variables that pick a repo, whatever ran the tests.
env.Vars = stubtest.GitEnv(env.Vars)
return nil
}
+26 -3
View File
@@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"os"
@@ -83,15 +84,37 @@ func TestRetry(t *testing.T) {
}
}
// unanswered is the URL of a server that closes each connection without
// answering. It keeps its port until the test ends, so no other test's
// server can take the port and answer in its place, as one could take a
// closed server's.
func unanswered(t *testing.T) string {
t.Helper()
l, err := new(net.ListenConfig).Listen(t.Context(), "tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = l.Close() })
go func() {
for {
c, err := l.Accept()
if err != nil {
return
}
_ = c.Close()
}
}()
return "http://" + l.Addr().String()
}
// No answer at all is tried again too.
func TestRetryUnanswered(t *testing.T) {
t.Parallel()
srv := httptest.NewServer(http.NotFoundHandler())
srv.Close()
url := unanswered(t)
tries := 0
err := Retry(t.Context(), 2, time.Millisecond, func() (bool, error) {
tries++
_, err := Get(t.Context(), NewClient(time.Minute, HTTPSOnly), srv.URL, 10)
_, err := Get(t.Context(), NewClient(time.Minute, HTTPSOnly), url, 10)
return Transient(err), err
})
if err == nil || tries != 3 {
+3 -2
View File
@@ -14,6 +14,7 @@ import (
"github.com/devvmhq/devvm/internal/paths"
"github.com/devvmhq/devvm/internal/platform"
"github.com/devvmhq/devvm/internal/state"
"github.com/devvmhq/devvm/internal/stubtest"
)
// fixture is a project folder with a protector whose chflags and warnings
@@ -100,7 +101,7 @@ func (f *fixture) path(rel string) string { return filepath.Join(f.dir, rel) }
func (f *fixture) git(dir string, args ...string) string {
f.t.Helper()
cmd := exec.CommandContext(f.t.Context(), "git", append([]string{ //nolint:gosec // the test's own
cmd := stubtest.Git(f.t.Context(), append([]string{
"-c", "user.email=a@b", "-c", "user.name=a",
"-c", "init.defaultBranch=main", "-c", "protocol.file.allow=always",
}, args...)...)
@@ -870,7 +871,7 @@ func (f *fixture) set(mode string) {
func (f *fixture) ignoreSubmodules() string {
f.t.Helper()
out, _ := exec.CommandContext(f.t.Context(), "git", "config", "--file", f.path(".git/config"), "diff.ignoreSubmodules").Output() //nolint:gosec // the test's own
out, _ := stubtest.Git(f.t.Context(), "config", "--file", f.path(".git/config"), "diff.ignoreSubmodules").Output()
return strings.TrimSpace(string(out))
}
+2 -1
View File
@@ -16,6 +16,7 @@ import (
"github.com/devvmhq/devvm/internal/paths"
"github.com/devvmhq/devvm/internal/platform"
"github.com/devvmhq/devvm/internal/state"
"github.com/devvmhq/devvm/internal/stubtest"
)
// walked gives the fixture's protector what the walk finds now, as a
@@ -590,7 +591,7 @@ func BenchmarkNestedCheck(b *testing.B) {
for i := range 50 {
r := filepath.Join(dir, "repo"+strconv.Itoa(i))
for _, args := range [][]string{{"init", "-q", r}, {"-C", r, "-c", "user.email=a@b", "-c", "user.name=a", "commit", "-q", "--allow-empty", "-m", "x"}} {
if out, err := exec.CommandContext(b.Context(), "git", args...).CombinedOutput(); err != nil { //nolint:gosec // the benchmark's own
if out, err := stubtest.Git(b.Context(), args...).CombinedOutput(); err != nil {
b.Fatalf("git %v: %v\n%s", args, err, out)
}
}
+2 -2
View File
@@ -3,12 +3,12 @@ package gitprotect
import (
"context"
"os"
"os/exec"
"slices"
"strings"
"testing"
"github.com/devvmhq/devvm/internal/msg"
"github.com/devvmhq/devvm/internal/stubtest"
)
// strictAsBefore makes the fixture's VM one that an earlier devvm's
@@ -29,7 +29,7 @@ func (f *fixture) strictAsBefore(rels ...string) {
// the repo at rel, one per line.
func (f *fixture) ignoreIn(rel string) string {
f.t.Helper()
out, _ := exec.CommandContext(f.t.Context(), "git", "config", "--file", f.path(rel+"/.git/config"), "--get-all", "diff.ignoreSubmodules").Output() //nolint:gosec // the test's own
out, _ := stubtest.Git(f.t.Context(), "config", "--file", f.path(rel+"/.git/config"), "--get-all", "diff.ignoreSubmodules").Output()
return strings.TrimSpace(string(out))
}
+40 -9
View File
@@ -8,14 +8,15 @@ import (
"strings"
"testing"
"time"
"github.com/devvmhq/devvm/internal/stubtest"
)
// git runs plain git in dir, failing the test if it fails, and returns
// its output, trimmed.
func git(t *testing.T, dir string, args ...string) string {
t.Helper()
cmd := exec.CommandContext(t.Context(), "git", append([]string{"-C", dir}, args...)...) //nolint:gosec // the test's own
out, err := cmd.CombinedOutput()
out, err := stubtest.Git(t.Context(), append([]string{"-C", dir}, args...)...).CombinedOutput()
if err != nil {
t.Fatalf("git %v: %v\n%s", args, err, out)
}
@@ -38,6 +39,31 @@ func repo(t *testing.T) string {
return dir
}
// The tests' git works on their own repos, never on the one that a git
// running the tests names in its environment, as a hook's or git rebase
// --exec's does.
func TestRepoNotTheRunners(t *testing.T) {
decoy := t.TempDir()
if out, err := stubtest.Git(t.Context(), "init", "-q", decoy).CombinedOutput(); err != nil {
t.Fatalf("git init: %v\n%s", err, out)
}
config := filepath.Join(decoy, ".git", "config")
was, err := os.ReadFile(config) //nolint:gosec // the test's own
if err != nil {
t.Fatal(err)
}
t.Setenv("GIT_DIR", filepath.Join(decoy, ".git"))
t.Setenv("GIT_CONFIG_PARAMETERS", "'core.bare'='true'")
dir := repo(t)
git(t, dir, "config", "core.fsmonitor", "/nowhere")
if now, err := os.ReadFile(config); err != nil || string(now) != string(was) { //nolint:gosec // the test's own
t.Errorf("the decoy's config changed:\n%s", now)
}
if got := git(t, dir, "config", "--file", filepath.Join(dir, ".git", "config"), "core.fsmonitor"); got != "/nowhere" {
t.Errorf("the test's repo: core.fsmonitor %q", got)
}
}
// marker is a program that touches a file and passes its input through,
// and that file, which it hasn't touched yet.
func marker(t *testing.T) (prog, ran string) {
@@ -193,7 +219,7 @@ func TestCommandNoLazyFetch(t *testing.T) {
git(t, dir, "config", kv[0], kv[1])
}
missing := "0123456789abcdef0123456789abcdef01234567"
_ = exec.CommandContext(t.Context(), "git", "-C", dir, "cat-file", "-e", missing).Run() //nolint:gosec // the test's own
_ = stubtest.Git(t.Context(), "-C", dir, "cat-file", "-e", missing).Run()
if !ranOnce(ran) {
t.Fatal("plain git didn't fetch lazily with the repo's ssh")
}
@@ -210,10 +236,15 @@ func TestCommandNoLazyFetch(t *testing.T) {
func TestCommandIgnoresGitEnv(t *testing.T) {
dir, other := repo(t), repo(t)
resolved := func(p string) string { r, _ := filepath.EvalSymlinks(p); return r }
t.Setenv("GIT_DIR", filepath.Join(other, ".git"))
t.Setenv("GIT_WORK_TREE", other)
if got := git(t, dir, "rev-parse", "--absolute-git-dir"); resolved(got) != resolved(filepath.Join(other, ".git")) {
t.Fatalf("plain git: %s", got)
vars := []string{"GIT_DIR=" + filepath.Join(other, ".git"), "GIT_WORK_TREE=" + other}
plain := stubtest.Git(t.Context(), "-C", dir, "rev-parse", "--absolute-git-dir")
plain.Env = append(plain.Env, vars...) // stubtest.Git's own environment leaves them out
if out, err := plain.Output(); err != nil || resolved(strings.TrimSpace(string(out))) != resolved(filepath.Join(other, ".git")) {
t.Fatalf("plain git: %s, %v", out, err)
}
for _, kv := range vars {
k, v, _ := strings.Cut(kv, "=")
t.Setenv(k, v)
}
out, err := Output(t.Context(), "-C", dir, "rev-parse", "--absolute-git-dir")
if got := strings.TrimSpace(string(out)); err != nil || resolved(got) != resolved(filepath.Join(dir, ".git")) {
@@ -254,7 +285,7 @@ func TestStatusNoFilters(t *testing.T) {
}
}
touch(1)
_ = exec.CommandContext(t.Context(), "git", "-C", dir, "status", "--porcelain").Run() //nolint:gosec // the test's own
_ = stubtest.Git(t.Context(), "-C", dir, "status", "--porcelain").Run()
if !ranOnce(ran) {
t.Fatal("plain git status didn't run the filter")
}
@@ -294,7 +325,7 @@ func TestStatusNoSubmodules(t *testing.T) {
at = at.Add(time.Second)
}
touch()
_ = exec.CommandContext(t.Context(), "git", "-C", dir, "status", "--porcelain").Run() //nolint:gosec // the test's own
_ = stubtest.Git(t.Context(), "-C", dir, "status", "--porcelain").Run()
if !ranOnce(ran) {
t.Fatal("plain git status didn't run the submodule's filter")
}
+2 -2
View File
@@ -10,6 +10,7 @@ import (
"testing"
"github.com/devvmhq/devvm/internal/platform"
"github.com/devvmhq/devvm/internal/stubtest"
)
func touch(t *testing.T, paths ...string) {
@@ -221,8 +222,7 @@ func TestSSHRemote(t *testing.T) {
}
git := func(args ...string) {
t.Helper()
cmd := exec.CommandContext(t.Context(), "git", append([]string{"-C", d}, args...)...) //nolint:gosec // the test's own
if out, err := cmd.CombinedOutput(); err != nil {
if out, err := stubtest.Git(t.Context(), append([]string{"-C", d}, args...)...).CombinedOutput(); err != nil {
t.Fatalf("git %v: %v\n%s", args, err, out)
}
}
+1 -1
View File
@@ -12,7 +12,7 @@ The VM can reach nothing but this proxy. On macOS its Lima hostagent runs under
- checks `CONNECT host:port` and absolute-form requests (`GET http://host/…`) against the VM's policy, which is devvm's built-in policies, read from the binary, and then the user's policy files, and tunnels or forwards allowed ones untouched;
- resolves names itself, and refuses the host's own addresses and internal ones (loopback, private, link-local, multicast, unspecified, CGNAT `100.64.0.0/10`) unless a rule names the address; through a company proxy (`upstream`), which resolves names itself, it refuses a name when the host's resolver answers with such an address, and a name the host can't resolve when only `**` allows it (unless `upstream_unresolved`, which builds on Lima get), and it reads at most 64 KiB of the company proxy's answer to `CONNECT`;
- requires a TLS ClientHello in a tunnel to name the CONNECT host (SNI), in ASCII, letters' case aside, whole in one record of at most 16 KiB and 256 bytes (`helloRecordMax`) within 10 seconds of its first byte (`helloTimeout`), and passes nothing the VM sends to the far end before it has checked it, while the far end's bytes reach the VM at once, so a server that speaks first, such as SMTP's, sends its greeting before the VM sends anything; a stream whose first byte starts a TLS record is TLS from then on, so a record header that never comes whole, or a ClientHello that doesn't parse in its one record, is refused, never passed on, an address's tunnel's included, which may have no name;
- for a host whose rules narrow it to some methods or paths (`api.github.com GET,HEAD /repos/`), judges each of its requests, every one on a kept-alive or HTTP/2 connection, with one matcher (`match` in `request.go`), decrypting its `:443` tunnels with the VM's CA and refusing them on other ports (`policy.byRequest`, `server.judgeRequest`), and answers `403` to a request the rules refuse, logged with its method and path;
- for a host whose rules narrow it to some methods or paths (`api.github.com GET,HEAD /repos/`), judges each of its requests, every one on a kept-alive or HTTP/2 connection, with one matcher (`match` in `request.go`), decrypting its `:443` tunnels with the VM's CA and refusing them on other ports (`hostRules.byRequest`, `server.judgeRequest`), and answers `403` to a request the rules refuse, logged with its method and path;
- for hosts with a bound secret, swaps the placeholder in one header for the real value: it intercepts their `:443` tunnels, and does the same for absolute-form `https://` requests (everything else passes unread), with certificates from the VM's CA, of which it keeps the 1024 used most recently (`leafCacheMax`);
- for an agent's OAuth token endpoint (`captures`), intercepts its host's `:443` tunnels the same way, and hands a `POST` to its path, at most 64 KiB, and its successful reply, at most 1 MiB, to `IO.Capture`, which saves the login on the host and gives the reply the VM gets, with placeholders and no refresh token, so the endpoint's reply never reaches the VM ([capturing logins](#capturing-logins));
- carries at most 1024 `CONNECT`s at once (`maxConnects`), links' and intercepted ones too, and answers `503` past it, logged as a refused block, and once in its own log until a tunnel ends;
+5 -13
View File
@@ -393,26 +393,18 @@ func loadPolicy(f, b string, deniesOnly bool, l *log.Logger) policyFile {
// openRule is what an open policy logs as the rule that allowed a request.
const openRule = "open"
// decide whether host:port may be reached. host is a name or an address literal. It returns the
// matching rule's text, or why not.
func (p *policy) decide(host string, port int) (bool, string) {
ok, why, _ := p.verdict(host, port)
return ok, why
}
// deniedBy starts the reason of a refusal by a deny rule, which its text follows.
const deniedBy = "denied by "
// verdict is decide, and whether a refusal is one no allow rule would lift: a broken deny's. It
// judges host:port as a whole: a deny that narrows doesn't refuse it, as some of its requests may
// pass, and an allow that narrows allows it, for judge to look at each request.
// verdict is whether host:port may be reached, host a name or an address literal: the matching
// rule's text, or why not, and whether a refusal is one no allow rule would lift: a broken deny's.
// It judges host:port as a whole: a deny that narrows doesn't refuse it, as some of its requests
// may pass, and an allow that narrows allows it, for judge to look at each request. The proxy's
// own connections take the verdict and byRequest from one rulesFor (egress.checkHost).
func (p *policy) verdict(host string, port int) (bool, string, bool) {
return p.rulesFor(host, port).verdict()
}
// byRequest is rulesFor(host, port).byRequest.
func (p *policy) byRequest(host string, port int) bool { return p.rulesFor(host, port).byRequest() }
// judge is rulesFor(host, port).judge(r).
func (p *policy) judge(host string, port int, r *http.Request) (ok bool, why string, refused, narrowed bool) {
return p.rulesFor(host, port).judge(r)
+11
View File
@@ -45,6 +45,17 @@ func writePolicy(t *testing.T, rules string) *policy {
return newPolicy(nil, policyFiles(t, rules), nil, quiet())
}
// decide is p's verdict on host:port without whether a refusal is a broken deny's: the matching
// rule's text, or why not.
func (p *policy) decide(host string, port int) (bool, string) {
ok, why, _ := p.verdict(host, port)
return ok, why
}
// byRequest is rulesFor(host, port).byRequest, which the proxy takes from the same rulesFor as
// its verdict (egress.checkHost).
func (p *policy) byRequest(host string, port int) bool { return p.rulesFor(host, port).byRequest() }
// testServer is a proxy of the test's own, made as Main makes one (newServer), from c with a
// policy of rules (and the VM's name "vm" when c has none): it logs nothing, and nothing of it is
// any other test's.
+9 -1
View File
@@ -115,7 +115,12 @@ func (f *File) ReadAll(limit int64) ([]byte, error) {
// Root is a folder whose files are opened beneath it (os.Root's): no name, and no symbolic link
// on the way, leads out of it.
type Root struct{ root *os.Root }
type Root struct {
root *os.Root
// looked, when a test sets it, runs in Open between its look at name and its open, so the
// test can swap the file there as a VM could.
looked func()
}
// OpenRoot opens the folder dir as a Root, which its caller closes.
func OpenRoot(dir string) (*Root, error) {
@@ -144,6 +149,9 @@ func (r *Root) Open(name string, o Opts) (*File, error) {
return nil, fmt.Errorf("%s: %w", path, ErrNotRegular)
}
was = fi
if r.looked != nil {
r.looked()
}
}
f, err := r.root.OpenFile(name, o.flags(), 0)
file, err := checked(path, f, err, o)
+24
View File
@@ -248,6 +248,30 @@ func TestSwapDuringOpen(t *testing.T) {
}
}
// A Root's Open, without Follow, refuses a file swapped for another between its look at the name
// and its open, and opens the file when nothing changed: TestSwapDuringOpen's swaps land there
// only by chance.
func TestRootOpenSwappedAfterLook(t *testing.T) {
t.Parallel()
dir := t.TempDir()
p, other := filepath.Join(dir, "f"), filepath.Join(dir, "g")
must(t, os.WriteFile(p, []byte("f"), 0o600))
root, err := OpenRoot(dir)
must(t, err)
defer func() { _ = root.Close() }()
root.looked = func() {
must(t, os.WriteFile(other, []byte("g"), 0o600))
must(t, os.Rename(other, p))
}
if b, err := root.Read("f", 64, Opts{}); !errors.Is(err, ErrNotRegular) {
t.Errorf("swapped after the look: %q, %v, want ErrNotRegular", b, err)
}
root.looked = func() {}
if b, err := root.Read("f", 64, Opts{}); err != nil || string(b) != "g" {
t.Errorf("unchanged: %q, %v", b, err)
}
}
// OpenDir opens a folder, never a link to one, in the root or out of it,
// nor a file; and a folder swapped for a link to another while it's
// opened is never the one opened, so a walk from it reads only what's
+4
View File
@@ -30,6 +30,10 @@ type rules struct {
// commands are the host commands one package runs: a command's name,
// then the package folder that runs it.
commands map[string]string
// testCommands are the host commands that tests run only through one
// test-support package, which may run them outside tests too: a
// command's name, then that package's folder.
testCommands map[string]string
// execSites are the files that make host commands, from the module's
// root, each with why; nil checks none.
execSites map[string]string
+4 -4
View File
@@ -67,7 +67,7 @@ func ownerDocs() []ownerDoc {
{
check: "forbidigo, `os.Setenv`, `os.Unsetenv`, `os.Clearenv` and `syscall`'s",
owner: "each command's own environment, its `exec.Cmd`'s `Env`, because every command and background process devvm starts inherits devvm's. A VM's SSH agent is one: the finder's `target` carries its socket, which goes to the backend in `backend.ExecOpts.Agent`, `backend.ShellOpts.Agent` and `Confinement.AgentSocket`, and Lima sets `SSH_AUTH_SOCK` on that VM's `limactl` commands alone, so a run that reaches several VMs never gives one another's",
elsewhere: "`daemon.Ready` in `internal/daemon/status.go`, which takes the status file's name out of a background process's own environment, and tests, which use `t.Setenv`",
elsewhere: "`daemon.Ready` in `internal/daemon/status.go`, which takes the status file's name out of a background process's own environment; `stubtest.NoGitRepo`, which takes git's variables that pick a repo out of a test's environment until the test ends; and tests, which use `t.Setenv`",
},
{
check: "the structure test's `owners`, host commands",
@@ -81,8 +81,8 @@ func ownerDocs() []ownerDoc {
},
{
check: "the structure test's `owners`, git",
owner: "`internal/hostgit`, which runs git without the repo's fsmonitor, hooks or filters, over ssh only, without the environment's `GIT_*` variables and prompts",
elsewhere: "tests, which run git to make their repos",
owner: "`internal/hostgit`, which runs git without the repo's fsmonitor, hooks or filters, over ssh only, without the environment's `GIT_*` variables and prompts. In tests, which run plain git to make their repos, it's `internal/stubtest`'s `Git`, which leaves out git's variables that pick a repo, its files or its config (`GitEnv`), so a git that runs the tests, such as a hook's or `git rebase --exec`'s, never sends a test's git to the checkout itself",
elsewhere: "nothing else",
},
{
check: "forbidigo, `os.UserHomeDir`, and the structure test's `owners`, `HOME`",
@@ -185,7 +185,7 @@ func TestOwnersDoc(t *testing.T) {
func TestOwnersAgree(t *testing.T) {
r := devvm()
owners := []string{r.guardOwner, r.envOwner, r.pathsOwner}
for _, m := range []map[string]string{r.commands, r.envOwners, r.callers} {
for _, m := range []map[string]string{r.commands, r.testCommands, r.envOwners, r.callers} {
for _, o := range m {
owners = append(owners, o)
}
+14 -4
View File
@@ -107,14 +107,16 @@ func calls(f srcFile, fn func(*ast.CallExpr)) {
}
// checkCommands: outside tests, a host command that commands lists runs
// only in its package. An exec.Command or exec.CommandContext naming it,
// as a literal or a constant, runs it.
// only in its package, or in the test-support package testCommands names
// for it; in tests, a command that testCommands lists runs only in that
// package. An exec.Command or exec.CommandContext naming it, as a literal
// or a constant, runs it.
func checkCommands(m *module, r rules) []violation {
var vs []violation
c := stringConsts(m)
for _, f := range m.files {
exec := importName(f, "os/exec")
if f.test || exec == "" {
if exec == "" {
continue
}
at := map[string]int{exec + ".Command": 0, exec + ".CommandContext": 1} // the command's argument
@@ -124,7 +126,15 @@ func checkCommands(m *module, r rules) []violation {
return
}
name, ok := c.value(m, f, call.Args[i])
if owner, guarded := r.commands[name]; ok && guarded && f.dir != owner {
if !ok {
return
}
owner, guarded := r.commands[name]
testOwner, testGuarded := r.testCommands[name]
switch {
case f.test && testGuarded && f.dir != testOwner:
vs = append(vs, violation{ruleOwners, m.pos(call), fmt.Sprintf("a test runs %s: run it through %s, which every test's %s goes through", name, testOwner, name)})
case !f.test && guarded && f.dir != owner && (!testGuarded || f.dir != testOwner):
vs = append(vs, violation{ruleOwners, m.pos(call), fmt.Sprintf("runs %s: run it through %s, the only package that does", name, owner)})
}
})
+36 -3
View File
@@ -447,8 +447,6 @@ func agentCases() []ruleCase {
}
func ownerCases() []ruleCase {
const platform = "package platform\n\nconst TestCPUs = \"DEVVM_TEST_CPUS\"\n"
listed := rules{envSettings: map[string]envSetting{"DEVVM_X": {[]string{"internal/tools/a.go"}, "x"}}}
return []ruleCase{
{
name: "a shell quoter outside shell",
@@ -485,6 +483,12 @@ func ownerCases() []ruleCase {
name: "another hex length",
files: map[string]string{"internal/cli/a.go": "package cli\n\nconst re = `[0-9a-f]{12}`\n"},
},
}
}
// commandCases break and keep commands and testCommands.
func commandCases() []ruleCase {
return []ruleCase{
{
name: "git outside hostgit",
files: map[string]string{"internal/vm/a.go": runs("vm", "exec", `"git"`)},
@@ -508,11 +512,37 @@ func ownerCases() []ruleCase {
{
name: "git in a test",
files: map[string]string{"internal/vm/a_test.go": runs("vm", "exec", `"git"`)},
want: &want{ruleOwners, "a test runs git: run it through internal/stubtest"},
},
{
name: "git in hostgit's test",
files: map[string]string{"internal/hostgit/a_test.go": runs("hostgit", "exec", `"git"`)},
want: &want{ruleOwners, "a test runs git"},
},
{
name: "git in stubtest",
files: map[string]string{"internal/stubtest/a.go": runs("stubtest", "exec", `"git"`)},
},
{
name: "git in stubtest's test",
files: map[string]string{"internal/stubtest/a_test.go": runs("stubtest", "exec", `"git"`)},
},
{
name: "another command in a test",
files: map[string]string{"internal/vm/a_test.go": runs("vm", "exec", `"ssh"`)},
},
{
name: "another command",
files: map[string]string{"internal/vm/a.go": runs("vm", "exec", `"ssh"`)},
},
}
}
// envCases break and keep the owners of the environment's variables.
func envCases() []ruleCase {
const platform = "package platform\n\nconst TestCPUs = \"DEVVM_TEST_CPUS\"\n"
listed := rules{envSettings: map[string]envSetting{"DEVVM_X": {[]string{"internal/tools/a.go"}, "x"}}}
return []ruleCase{
{
name: "a DEVVM_ variable outside the overrides",
files: map[string]string{"internal/tools/a.go": reads("tools", "os.Getenv", `"DEVVM_X"`)},
@@ -677,7 +707,7 @@ func callerCases() []ruleCase {
// what it allows.
func TestRulesFail(t *testing.T) {
var broken []string // the layer violations' texts
for _, tc := range slices.Concat(methodCases(), varCases(), layerCases(), ownerCases(), agentCases(), separatorCases(), runnerCases(), pathCases(), callerCases()) {
for _, tc := range slices.Concat(methodCases(), varCases(), layerCases(), ownerCases(), commandCases(), envCases(), agentCases(), separatorCases(), runnerCases(), pathCases(), callerCases()) {
t.Run(tc.name, func(t *testing.T) {
fsys := fstest.MapFS{"go.mod": {Data: []byte("module example.com/m\n\ngo 1.27\n")}}
for name, src := range tc.files {
@@ -697,6 +727,9 @@ func TestRulesFail(t *testing.T) {
if r.commands == nil {
r.commands = devvm().commands
}
if r.testCommands == nil {
r.testCommands = devvm().testCommands
}
if r.envOwner == "" {
r.envOwner = devvm().envOwner
}
+5 -4
View File
@@ -37,10 +37,10 @@ func devvm() rules {
"internal/ui.UI": {46, "the one terminal: messages and where they go, as text or names, the logo, errors with the caller's exit code, prompts and their refusals, whether the picker shows, status line, tables, run log and how many are kept, cleanups, signals"},
},
allowedVars: devvmVars(),
// hostgit runs git without the repo's fsmonitor, hooks or filters,
// over ssh only, without the environment's GIT_* and prompts.
commands: map[string]string{"git": "internal/hostgit"},
execSites: devvmExecSites(),
// hostgit runs git without fsmonitor, hooks, filters, GIT_* or prompts, ssh only; tests, stubtest.Git (GitEnv).
commands: map[string]string{"git": "internal/hostgit"},
testCommands: map[string]string{"git": "internal/stubtest"},
execSites: devvmExecSites(),
// The registry's backends are behind its guard: only backend.As
// finds their other interfaces.
guardOwner: "internal/backend/guard.go",
@@ -284,6 +284,7 @@ func devvmExecSites() map[string]string {
"internal/daemon/daemon.go": "devvm's background processes, which outlive the run and its context",
"internal/upgrade/upgrade.go": "devvm upgrade: brew upgrade devvm through the UI's LoggedCmd, a new devvm's --version and ps's list, their output read",
"internal/stubtest/build.go": "go build of the test stubs, once for a test process, and their names from the binary",
"internal/stubtest/git.go": "tests' plain git, on their own repos, which they run and read as they like",
"internal/stubtest/stub/process.go": "the stubs' stand-in VM's own commands (git on its files, tar) and the real uname and sw_vers, run in the stub's place",
}
}
+1 -1
View File
@@ -91,7 +91,7 @@ func buildInto(root, dir string) error {
bin := filepath.Join(dir, "stub")
cmd := exec.CommandContext(ctx, "go", "build", "-o", bin, stubPackage) //nolint:gosec // the test's own temporary folder
cmd.Dir = root
cmd.Env = append(os.Environ(), "CGO_ENABLED=0")
cmd.Env = append(GitEnv(os.Environ()), "CGO_ENABLED=0") // go reads the checkout's own repo to stamp the binary
if out, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("building the stubs: %w\n%s", err, out)
}
+57
View File
@@ -0,0 +1,57 @@
package stubtest
import (
"context"
"os"
"os/exec"
"strings"
"testing"
)
// gitRepoVar reports whether k is one of git's variables that pick a repo, its files or its
// config: GIT_DIR, GIT_WORK_TREE, GIT_INDEX_FILE, GIT_COMMON_DIR, GIT_OBJECT_DIRECTORY,
// GIT_ALTERNATE_OBJECT_DIRECTORIES, GIT_NAMESPACE and GIT_CONFIG*. A git that runs the tests sets
// some of them, such as a hook's or git rebase --exec's, and a test's git that kept them would
// work on that repo, the checkout itself, instead of the test's own.
func gitRepoVar(k string) bool {
switch k {
case "GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_COMMON_DIR", "GIT_OBJECT_DIRECTORY",
"GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_NAMESPACE":
return true
}
return strings.HasPrefix(k, "GIT_CONFIG")
}
// GitEnv is env without git's variables that pick a repo, its files or its config, so git run
// with it works on the repo its arguments or its folder name.
func GitEnv(env []string) []string {
var out []string
for _, kv := range env {
if k, _, _ := strings.Cut(kv, "="); !gitRepoVar(k) {
out = append(out, kv)
}
}
return out
}
// Git is plain git, as a test runs it on a repo of its own: in the test's environment without
// GitEnv's variables, whatever git ran the tests, and with no config but the repo's own (no
// global or system file). Every test's git runs through it, which the structure test checks.
func Git(ctx context.Context, args ...string) *exec.Cmd {
cmd := exec.CommandContext(ctx, "git", args...) //nolint:gosec // a test's own git, on its own repo
cmd.Env = append(GitEnv(os.Environ()), "GIT_CONFIG_GLOBAL="+os.DevNull, "GIT_CONFIG_NOSYSTEM=1")
return cmd
}
// NoGitRepo takes GitEnv's variables out of the test's own environment until t ends, for what
// the test runs that runs git itself, such as a stub or a script. New calls it. Like t.Setenv,
// it's not for a parallel test.
func NoGitRepo(t testing.TB) {
t.Helper()
for _, kv := range os.Environ() {
if k, _, _ := strings.Cut(kv, "="); gitRepoVar(k) {
t.Setenv(k, "") // restored when t ends
_ = os.Unsetenv(k) //nolint:forbidigo // a test's own environment, restored by t.Setenv's cleanup
}
}
}
+74
View File
@@ -0,0 +1,74 @@
package stubtest
import (
"os"
"os/exec"
"path/filepath"
"slices"
"testing"
)
// GitEnv takes out git's variables that pick a repo, its files or its
// config, and keeps the rest.
func TestGitEnv(t *testing.T) {
env := []string{
"HOME=/h", "GIT_DIR=/r/.git", "GIT_WORK_TREE=/r", "GIT_INDEX_FILE=/r/.git/index", "GIT_COMMON_DIR=/r/.git",
"GIT_OBJECT_DIRECTORY=/r/.git/objects", "GIT_ALTERNATE_OBJECT_DIRECTORIES=/o", "GIT_NAMESPACE=n",
"GIT_CONFIG=/c", "GIT_CONFIG_PARAMETERS='core.bare'='true'", "GIT_CONFIG_COUNT=1", "GIT_CONFIG_KEY_0=k",
"GIT_CONFIG_VALUE_0=v", "GIT_CONFIG_GLOBAL=/g", "GIT_AUTHOR_NAME=a", "PATH=/bin",
}
if got, want := GitEnv(env), []string{"HOME=/h", "GIT_AUTHOR_NAME=a", "PATH=/bin"}; !slices.Equal(got, want) {
t.Errorf("GitEnv = %q, want %q", got, want)
}
}
// Git works on the repo its arguments name, never the one GIT_DIR names
// for the git that ran the tests, and reads no config but the repo's;
// NoGitRepo takes the same variables out of the test's environment, for
// what it runs, until the test ends.
func TestGit(t *testing.T) {
if _, err := exec.LookPath("git"); err != nil {
t.Skip("no git")
}
decoy, mine := t.TempDir(), t.TempDir()
if out, err := Git(t.Context(), "init", "-q", decoy).CombinedOutput(); err != nil {
t.Fatalf("git init: %v\n%s", err, out)
}
config := filepath.Join(decoy, ".git", "config")
was, err := os.ReadFile(config) //nolint:gosec // the test's own
if err != nil {
t.Fatal(err)
}
t.Setenv("GIT_DIR", filepath.Join(decoy, ".git"))
t.Setenv("GIT_CONFIG_PARAMETERS", "'core.bare'='true'")
global := filepath.Join(decoy, "global")
if err := os.WriteFile(global, []byte("[decoy]\n\tk = global\n"), 0o600); err != nil {
t.Fatal(err)
}
t.Setenv("GIT_CONFIG_GLOBAL", global)
for _, args := range [][]string{{"init", "-q"}, {"config", "core.fsmonitor", "/nowhere"}} {
if out, err := Git(t.Context(), append([]string{"-C", mine}, args...)...).CombinedOutput(); err != nil {
t.Fatalf("git %v: %v\n%s", args, err, out)
}
}
if now, err := os.ReadFile(config); err != nil || string(now) != string(was) { //nolint:gosec // the test's own
t.Errorf("the decoy's config changed:\n%s", now)
}
if out, _ := Git(t.Context(), "-C", mine, "config", "decoy.k").Output(); len(out) != 0 {
t.Errorf("read the global config GIT_CONFIG_GLOBAL named: %q", out)
}
if out, err := Git(t.Context(), "-C", mine, "config", "core.fsmonitor").Output(); err != nil || string(out) != "/nowhere\n" {
t.Errorf("the test's repo: core.fsmonitor %q, %v", out, err)
}
t.Run("NoGitRepo", func(t *testing.T) {
NoGitRepo(t)
for _, k := range []string{"GIT_DIR", "GIT_CONFIG_PARAMETERS", "GIT_CONFIG_GLOBAL"} {
if v, ok := os.LookupEnv(k); ok {
t.Errorf("%s=%s", k, v)
}
}
})
if v := os.Getenv("GIT_DIR"); v != filepath.Join(decoy, ".git") {
t.Errorf("GIT_DIR after NoGitRepo's test: %q", v)
}
}
+3 -1
View File
@@ -15,6 +15,7 @@ import (
"testing"
"time"
"github.com/devvmhq/devvm/internal/stubtest"
"github.com/devvmhq/devvm/internal/stubtest/stubstate"
)
@@ -556,6 +557,7 @@ func TestShellScripts(t *testing.T) {
// A --clone VM's git runs on the guest's files; its worktree list gives
// the guest's paths.
func TestCloneGit(t *testing.T) {
stubtest.NoGitRepo(t) // the stub runs git in this process
s := newSandbox(t)
s.ok("", "limactl", "shell", "vm", "sh", "-c", "cd '/' && exec 'git' '-C' '/w' 'status'")
if got := s.replaced[0]; !slices.Equal(got, []string{"git", "-C", filepath.Join(s.dir, "vmfs/w"), "status"}) {
@@ -571,7 +573,7 @@ func TestCloneGit(t *testing.T) {
t.Skip("no git here")
}
repo := filepath.Join(s.dir, "vmfs", "w")
if out, err := exec.CommandContext(t.Context(), "git", "init", "-q", repo).CombinedOutput(); err != nil { //nolint:gosec // git init in the test's own folder
if out, err := stubtest.Git(t.Context(), "init", "-q", repo).CombinedOutput(); err != nil {
t.Fatalf("git init: %v\n%s", err, out)
}
out := s.ok("", "limactl", "shell", "vm", "cd '/' && exec 'git' '-C' '/w' 'worktree' 'list' '--porcelain' '-z'")
+3 -1
View File
@@ -28,9 +28,11 @@ type Stubs struct {
// New puts every stub first on PATH for t, or only the ones named, with
// a new folder under /tmp (short, for the sockets some stubs make in it)
// that t's end removes.
// that t's end removes. The stubs that run git, on their stand-in VM's
// files, run it without git's variables that pick a repo (NoGitRepo).
func New(t testing.TB, only ...string) *Stubs {
t.Helper()
NoGitRepo(t)
all := Bin(t)
dir, err := os.MkdirTemp("/tmp", "stub.")
if err != nil {
+6 -3
View File
@@ -36,7 +36,7 @@ func gitEnv(t *testing.T) {
// output, trimmed.
func gitIn(t *testing.T, dir string, args ...string) string {
t.Helper()
out, err := exec.CommandContext(t.Context(), "git", append([]string{"-C", dir}, args...)...).CombinedOutput() //nolint:gosec // the test's own
out, err := stubtest.Git(t.Context(), append([]string{"-C", dir}, args...)...).CombinedOutput()
if err != nil {
t.Fatalf("git %v: %v\n%s", args, err, out)
}
@@ -49,10 +49,12 @@ func gitIn(t *testing.T, dir string, args ...string) string {
func cloneEnv(t *testing.T) (e *Env, f *backendtest.Fake, vmfs string) {
t.Helper()
e, f, _ = upEnv(t, allNative())
// The stubs first, as they take git's variables that pick a repo out
// of the test's environment, then the test's own.
vmfs = stubtest.New(t, "ssh").Path("vmfs")
gitEnv(t)
gitIn(t, e.Dir, "init", "-q", "-b", "main")
gitIn(t, e.Dir, "commit", "-q", "--allow-empty", "-m", "one")
vmfs = stubtest.New(t, "ssh").Path("vmfs")
f.Target = backend.SSHTarget{Host: "127.0.0.1", Port: 60022, User: "u", Key: "/k"}
f.ExecFunc = func(_ string, argv []string, o backend.ExecOpts) error {
var cmd *exec.Cmd
@@ -61,7 +63,7 @@ func cloneEnv(t *testing.T) (e *Env, f *backendtest.Fake, vmfs string) {
_, err := io.WriteString(o.Stdout, testHostKey+"\n")
return err
case len(argv) > 3 && argv[0] == "git" && argv[1] == "-C":
cmd = exec.CommandContext(t.Context(), "git", append([]string{"-C", vmfs + argv[2]}, argv[3:]...)...) //nolint:gosec // the test's own
cmd = stubtest.Git(t.Context(), append([]string{"-C", vmfs + argv[2]}, argv[3:]...)...)
case len(argv) >= 5 && argv[0] == "sh" && argv[1] == "-c":
// A clone's script: its first argument the project folder, in
// vmfs, the rest relative to it.
@@ -432,6 +434,7 @@ func TestParseCloneState(t *testing.T) {
// listed, and one outside, listed first, doesn't count towards how many
// it looks at, so it never hides one inside.
func TestCloneStateScript(t *testing.T) {
stubtest.NoGitRepo(t) // the script runs git
gitEnv(t)
outside := t.TempDir()
ws, _ := filepath.EvalSymlinks(t.TempDir())
+2 -2
View File
@@ -29,14 +29,14 @@ internal/ports 91.4
internal/project 98.5
internal/proxy 92.8
internal/redact 97.7
internal/safefile 95.2
internal/safefile 97.7
internal/secrets 93.2
internal/settings 96.3
internal/shell 100.0
internal/sshagent 84.2
internal/sshconfig 95.0
internal/state 94.3
internal/stubtest 81.8
internal/stubtest 83.4
internal/stubtest/stub 92.9
internal/stubtest/stubstate 91.2
internal/testbuild 100.0
+2 -1
View File
@@ -227,7 +227,8 @@ func TestHarnessAnonymous(t *testing.T) {
}
func TestHarnessEnviron(t *testing.T) {
got := environ([]string{"PATH=/bin", "SSH_AUTH_SOCK=/a", "DEVVM_MESSAGES=names", "LIMA_HOME=/mine"}, map[string]string{"LIMA_HOME": "/sandbox", "A": "1"})
got := environ([]string{"PATH=/bin", "SSH_AUTH_SOCK=/a", "DEVVM_MESSAGES=names", "LIMA_HOME=/mine", "GIT_DIR=/repo/.git", "GIT_CONFIG_PARAMETERS=x"},
map[string]string{"LIMA_HOME": "/sandbox", "A": "1"})
if want := []string{"PATH=/bin", "A=1", "LIMA_HOME=/sandbox"}; !slices.Equal(got, want) {
t.Errorf("got %v, want %v", got, want)
}
+4 -1
View File
@@ -813,8 +813,11 @@ func netTokens(n *netRun) {
return nil
})
s.Check("the VM's Codex reads its copy of the login, the fields devvm doesn't know left out", func() error {
// An API-key login whose key is devvm's placeholder: Codex 0.167.0
// shows the key's start ("Logged in using an API key - sk-devvm***…"),
// where earlier releases said "API key configured" alone.
r, err := s.InVM(vm, "codex login status")
if err != nil || !strings.Contains(r.Out, "API key configured") {
if err != nil || !strings.Contains(r.Out, "API key configured") && !Matches(r.Out, `^Logged in using an API key - sk-devvm`) {
return failed("codex login status:\n"+r.Out, err)
}
return nil
+6 -2
View File
@@ -19,6 +19,8 @@ import (
"strconv"
"strings"
"time"
"github.com/devvmhq/devvm/internal/stubtest"
)
// sandbox is a slot's: its Lima home, state folder, Keychain service and
@@ -109,14 +111,16 @@ func newSandbox(o options) (*sandbox, error) {
// environ is env with what e2e never inherits taken out and set's
// variables in their place. Your SSH agent is never reached, devvm's
// output stays plain, and no setting of yours picks its messages, mise,
// Ubuntu's mirror or --from.
// Ubuntu's mirror or --from. Nor does the git that e2e runs on its
// projects get git's variables that pick a repo (stubtest.GitEnv), which a
// git that ran e2e may have set.
func environ(env []string, set map[string]string) []string {
drop := []string{
"DEVVM_MESSAGES", "DEVVM_UBUNTU_URL", "DEVVM_UBUNTU_RELEASE", "DEVVM_HOST_MISE", "CLAUDE_CODE_OAUTH_TOKEN",
"DEVVM_FROM", "SSH_AUTH_SOCK", "FORCE_COLOR", "CLICOLOR_FORCE",
}
var out []string
for _, kv := range env {
for _, kv := range stubtest.GitEnv(env) {
k, _, _ := strings.Cut(kv, "=")
if _, ok := set[k]; ok || slices.Contains(drop, k) {
continue