diff --git a/.golangci.yml b/.golangci.yml index 58372f80..b1fd2746 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -35,7 +35,8 @@ linters: rules: # The proxy, and the background-process helper, the file reader, # the VM names and the secrets' type it uses: the standard library - # alone, and each other; and the leak checks, which their tests use. + # alone, and each other; and the leak checks and the network in + # memory, which their tests use. proxy: list-mode: strict files: @@ -45,6 +46,7 @@ linters: - "**/internal/vmname/**" - "**/internal/leaktest/**" - "**/internal/redact/**" + - "**/internal/memnet/**" allow: - $gostd - github.com/devvmhq/devvm/internal/proxy @@ -53,6 +55,7 @@ linters: - github.com/devvmhq/devvm/internal/vmname - github.com/devvmhq/devvm/internal/leaktest - github.com/devvmhq/devvm/internal/redact + - github.com/devvmhq/devvm/internal/memnet main: list-mode: strict files: @@ -64,6 +67,7 @@ linters: - "!**/internal/vmname/**" - "!**/internal/leaktest/**" - "!**/internal/redact/**" + - "!**/internal/memnet/**" allow: - $gostd - github.com/devvmhq/devvm @@ -91,6 +95,7 @@ linters: - "!**/internal/vmname/**" - "!**/internal/leaktest/**" - "!**/internal/redact/**" + - "!**/internal/memnet/**" allow: - $gostd - github.com/devvmhq/devvm diff --git a/AGENTS.md b/AGENTS.md index cf4151a6..dafc1549 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,7 +39,7 @@ Each package's concerns and identifiers: [The packages](docs/content/docs/contri | `internal/platform/`, `internal/ubuntu/`, `internal/testbuild/` | build-tagged OS code; Ubuntu's cloud image (never downloads); whether this is a test build | | `assets/` | the files devvm ships, embedded (`assets.FS`) | | `internal/structure/` | the structure test | -| `internal/stubtest/`, `internal/leaktest/` | the test stubs; the goroutine leak checks (`Main`, `Check`) | +| `internal/stubtest/`, `internal/leaktest/`, `internal/memnet/` | the test stubs; the goroutine leak checks (`Main`, `Check`); the network in memory for synctest bubbles | | `testdata/` | CLI tests, golden fixtures, coverage baselines, each release's frozen state (`v/`), `lint/` | | `tests/e2e/`, `tests/e2e-mise.lock` | end-to-end tests on real VMs | | `scripts/`, `packaging/`, `.goreleaser.yaml`, `VERSION`, `CHANGELOG.md` | pins, releases, the test tasks' scripts, the Homebrew formula, devvm upgrade's key | @@ -87,7 +87,7 @@ Each package's concerns and identifiers: [The packages](docs/content/docs/contri - **Cleanups:** whatever a failure would leave (a build VM, a temp file) registers with the UI's `AddCleanup` and is removed once done; one only for interrupts checks `Interrupted()` and stays once interrupted, as the cleanups run after the command returns. Cleanups get a fresh context. - **External commands run with the UI's `LoggedCmd(ctx, step, cmd)`**, a failure after one returned as `backend.Logged(m)` ([CLI conventions](docs/content/docs/contributing/cli.md#cli-conventions)). - **OS-specific code goes behind build tags** in `internal/platform` (`*_darwin.go`, `*_linux.go`, `*_other.go`). -- **Dependencies:** the depguard allowlist (cobra, pflag, cobra/doc, go-i18n, BurntSushi/toml, x/text, x/term, x/sys, x/crypto's `blake2b` only (minisign's prehash); go-internal in tests; cobra/doc's own deps never imported directly). `internal/proxy`, `internal/daemon`, `internal/safefile`, `internal/vmname`, `internal/leaktest` and `internal/redact` are stdlib only. Adding one: ask. +- **Dependencies:** the depguard allowlist (cobra, pflag, cobra/doc, go-i18n, BurntSushi/toml, x/text, x/term, x/sys, x/crypto's `blake2b` only (minisign's prehash); go-internal in tests; cobra/doc's own deps never imported directly). `internal/proxy`, `internal/daemon`, `internal/safefile`, `internal/vmname`, `internal/leaktest`, `internal/memnet` and `internal/redact` are stdlib only. Adding one: ask. - **A secret's value is a `redact.Secret`:** each `Reveal` with a `//nolint:forbidigo` saying why, and a file that holds one writes it through its own wire type ([Secrets in the code](docs/content/docs/contributing/structure.md#secrets-in-the-code)). - **External tools are commands, never linked** (`limactl`, `docker`, `security`, `git`, `chflags`…); prefer the standard library to shelling out. Strings into a shell are quoted with `shell.Quote`. - **Test seams are fields** tests set (`Host`, `Exec`, `Runner`, `OS`, `Reporter`…), never package vars (reassign: no package sets another's); `internal/proxy`'s are its `server`'s, which each test makes. @@ -114,6 +114,7 @@ Each package's concerns and identifiers: [The packages](docs/content/docs/contri - **New logic needs a test:** Go table tests next to the code, and CLI tests (testscript against the built binary and the stubs); neither touches the Keychain, real VMs or your folders ([Tests](docs/content/docs/contributing/tests.md)). - **Never touch VMs, images or containers devvm's tests didn't make:** your own stay as they are. Manual runs: `DEVVM_LIMA_HOME=~/.lt LIMA_HOME=~/.lt XDG_DATA_HOME=/tmp/x/data XDG_CONFIG_HOME=/tmp/x/config DEVVM_SECRET_SERVICE=devvm-sandbox-test` (devvm's Lima home is `$XDG_DATA_HOME/devvm/lima` unless `DEVVM_LIMA_HOME`; `LIMA_HOME` is for your `limactl`). Add a `config.toml` with `features = []` and pass `--network TIER` so nothing prompts. Delete test Keychain items. Never use your own tokens or logins: a network-policy VM reads its agent's login file from `HOME`, so give it its own (the Keychain needs the real `HOME`: test it apart). +- **Timeouts and lifecycles** are tested in a `testing/synctest` bubble on fakes in memory (`memnet`, the seams' fields), never by sleeping on the real clock; each kind keeps one real-process test ([Time and lifecycles](docs/content/docs/contributing/tests.md#time-and-lifecycles)). - **Goroutines:** a package that starts them calls `leaktest.Main` in its `TestMain`, and each function that does is in the structure test's `goroutineSites`, with what waits for them or `detached:` and why ([Goroutine leaks](docs/content/docs/contributing/tests.md#goroutine-leaks)). - **End-to-end:** `mise run e2e -- --only SECTIONS` in the background for what changed, `--from` before merging `assets/` or `--from` changes ([End-to-end tests](docs/content/docs/contributing/tests.md#end-to-end-tests)). - **Linux hosts:** `LIMA_HOME=~/.lt-linux-go`, VM `linuxhost`, set up as [Linux hosts](docs/content/docs/contributing/testing.md#linux-hosts) says, apart from any Lima home of your own. diff --git a/docs/content/docs/contributing/_index.md b/docs/content/docs/contributing/_index.md index cf06aede..9ab9e09e 100644 --- a/docs/content/docs/contributing/_index.md +++ b/docs/content/docs/contributing/_index.md @@ -97,7 +97,7 @@ golangci-lint enforces most of the [Go conventions](#go-conventions) in `.golang | Rule | Enforces | | --- | --- | | forbidigo | only `internal/ui` prints (`fmt.Print*`, `os.Stdout`, `os.Stderr`); only `cmd/devvm` calls `os.Exit`; only `internal/ui` and `cmd/devvm` make a context (`context.Background`, `context.TODO`), every other function takes its caller's; only `internal/platform` reads the host's CPUs, memory and free space, which the rest reads through `platform.Host`; only `internal/cli` calls `testbuild.On`; only `internal/daemon` and `internal/platform` signal a process by its pid (`os.FindProcess`, `syscall.Kill`, `unix.Kill`, `os.Process`'s `Kill` and `Signal`); only `internal/fetch` makes an HTTP client or a transport (`http.Client`, `http.DefaultClient`, `http.Transport`, `http.DefaultTransport`, `http.Get` and the like), which the rest names as `fetch.Client`; nothing calls `os.UserHomeDir`, because the home folder is `paths.Dirs.Home`; only `internal/state` calls `os.WriteFile` or `os.Create` or opens a file with `os.O_TRUNC`, and the rest writes a file whole through `state.WriteFile`, or `state.WriteFileMode` for a mode other than 600; nothing but `daemon.Ready` changes devvm's own environment (`os.Setenv`, `os.Unsetenv`, `os.Clearenv` and `syscall`'s), and a command gets its own through its `Env`; only the code that must use a secret's value calls `redact.Secret`'s `Reveal`, each call with a `nolint` saying why ([Secrets in the code](structure.md#secrets-in-the-code)) | -| depguard | the allowed modules, which are cobra, pflag, cobra's `doc` package for the CLI reference, go-i18n, BurntSushi's toml, `golang.org/x/text`, `x/term` and `x/sys`, and only the `blake2b` package of `x/crypto`, for minisign's prehashed signatures; the tests may also use go-internal. Nothing imports a module that cobra's `doc` package uses but isn't on the list. `internal/proxy`, `internal/daemon`, `internal/safefile`, `internal/vmname` and `internal/redact` use only the standard library and each other, and their tests may use `internal/leaktest`, which uses only the standard library too | +| depguard | the allowed modules, which are cobra, pflag, cobra's `doc` package for the CLI reference, go-i18n, BurntSushi's toml, `golang.org/x/text`, `x/term` and `x/sys`, and only the `blake2b` package of `x/crypto`, for minisign's prehashed signatures; the tests may also use go-internal. Nothing imports a module that cobra's `doc` package uses but isn't on the list. `internal/proxy`, `internal/daemon`, `internal/safefile`, `internal/vmname` and `internal/redact` use only the standard library and each other, and their tests may use `internal/leaktest` and `internal/memnet`, which use only the standard library too | | nolintlint | every `//nolint` names its linters and says why, and is still needed | | reassign | no package reassigns another package's variables, tests included | | revive | at most 100 statements or 160 lines a function (`function-length`), and a cognitive complexity of 75 (`cognitive-complexity`) | diff --git a/docs/content/docs/contributing/structure.md b/docs/content/docs/contributing/structure.md index 8bd94f57..905efb02 100644 --- a/docs/content/docs/contributing/structure.md +++ b/docs/content/docs/contributing/structure.md @@ -21,9 +21,9 @@ The layers: - Only `cmd/devvm` and `internal/cli` import `internal/ui`; only `internal/cli` imports `internal/vm`; only `cmd/devvm` imports `internal/cli`. - `internal/backend/...` imports none of `internal/vm`, `build`, `tools`, `netpolicy`, `secrets`, `project`, `gitprotect`, `sshconfig`, `sshagent`, `trust` or `vmssh`, so the port forwarder and the link sessions stay devvm's on every backend. -- Only `internal/backend/registry` and `internal/cli` import a backend (`lima`); only tests import `backendtest`, `internal/leaktest`, and `internal/stubtest` and the packages below it, which import only `internal/msg` and each other. The stubs' binary, `internal/stubtest/stub`, and its state, `internal/stubtest/stubstate`, import nothing else of devvm's, because the binary stands in for the tools devvm runs and is built apart from it. +- Only `internal/backend/registry` and `internal/cli` import a backend (`lima`); only tests import `backendtest`, `internal/leaktest`, `internal/memnet`, and `internal/stubtest` and the packages below it, which import only `internal/msg` and each other. The stubs' binary, `internal/stubtest/stub`, and its state, `internal/stubtest/stubstate`, import nothing else of devvm's, because the binary stands in for the tools devvm runs and is built apart from it. - `internal/proxy` imports no other devvm package but `internal/daemon`, `internal/redact`, `internal/safefile` and `internal/vmname`. -- `assets`, `locales`, `internal/platform`, `internal/msg/gen`, `internal/testbuild`, `internal/hostgit`, `internal/shell`, `internal/vmname`, `internal/daemon`, `internal/fetch`, `internal/jsonc`, `internal/redact`, `internal/agents`, `internal/safefile` and `internal/leaktest` import no devvm package; `internal/agentlogin` only `internal/agents`, `internal/fetch`, `internal/jsonc`, `internal/proxy`, `internal/redact`, `internal/safefile` and `internal/state`, because it holds agents' logins; `internal/msg` only `locales` and `internal/vmname`; `internal/paths` only `internal/msg` and `internal/vmname`; `internal/state` only `internal/msg`, `internal/paths`, `internal/platform` and `internal/vmname`; `internal/image` only `assets`, `internal/agents`, `internal/msg`, `internal/paths` and `internal/shell`; `internal/devcontainer` only `internal/image`, `internal/jsonc`, `internal/msg` and `internal/shell`. +- `assets`, `locales`, `internal/platform`, `internal/msg/gen`, `internal/testbuild`, `internal/hostgit`, `internal/shell`, `internal/vmname`, `internal/daemon`, `internal/fetch`, `internal/jsonc`, `internal/redact`, `internal/agents`, `internal/safefile`, `internal/leaktest` and `internal/memnet` import no devvm package; `internal/agentlogin` only `internal/agents`, `internal/fetch`, `internal/jsonc`, `internal/proxy`, `internal/redact`, `internal/safefile` and `internal/state`, because it holds agents' logins; `internal/msg` only `locales` and `internal/vmname`; `internal/paths` only `internal/msg` and `internal/vmname`; `internal/state` only `internal/msg`, `internal/paths`, `internal/platform` and `internal/vmname`; `internal/image` only `assets`, `internal/agents`, `internal/msg`, `internal/paths` and `internal/shell`; `internal/devcontainer` only `internal/image`, `internal/jsonc`, `internal/msg` and `internal/shell`. Everything it holds the code to is in `devvm()` in `internal/structure/structure_test.go`: @@ -93,6 +93,7 @@ Each package owns these concerns, and a package's `doc.go`, where it has one, ma | `internal/structure` | the [structure test](#the-structure-test), for tests only, and `owners_doc_test.go`, which writes [the checks on owners](#the-checks-on-owners) | | `internal/stubtest` | the test [stubs](tests.md#stubs), for tests only | | `internal/leaktest` | the [goroutine leak checks](tests.md#goroutine-leaks), `Main` for a package's `TestMain` and `Check` for one test, for tests only, and the standard library only, so the proxy's tests use it too | +| `internal/memnet` | the network in memory for [tests in a synctest bubble](tests.md#time-and-lifecycles): connections (`Pipe`) that close their writing side alone, hold a buffer's worth and have deadlines, and listeners by address (`Network`), for tests only, and the standard library only, so the proxy's tests use it too | | `testdata` | the CLI tests (`script/*.txtar`), the [golden fixtures](testing.md#golden-fixtures) (`golden//`), a lock to test with (`mise.lock`), each package's [coverage baseline](tests.md#coverage) on each system (`coverage/.txt`), each release's [state fixture](#released-state) (`v//`), and the lines that break each forbidigo rule (`lint/`, [Go lint rules](_index.md#go-lint-rules)) | | `tests/e2e`, `tests/e2e-mise.lock` | the [end-to-end tests](tests.md#end-to-end-tests) on real VMs, in Go with the tag `e2e` and a file for each section. `TestE2E` is the run, `sandbox_test.go` has the sandbox, its slot's paths and lock and `e2eUbuntuRelease`, and `slots_test.go` runs the slots. The lock file holds the shared tools' versions that every section but `tools` uses (`scripts/bump.sh e2e-tools`) | | `scripts`, `packaging`, `.goreleaser.yaml`, `VERSION`, `CHANGELOG.md` | `bump.sh` updates the pins. `release.sh` runs the signed tag's checks around GoReleaser, then minisign, and `publish.sh` makes the release itself, with its checks, `release.sh`, one yes, then the pushes, `gh release` and the tap. The `test` and `coverage` tasks run `test.sh`, which runs `coverage.sh` to check each package's coverage against its baseline. `packaging/` holds the Homebrew formula and `key.go`, which embeds its folder, so devvm upgrade's key is `minisign.pub`'s, and a build without that file has none. Only the scripts read `VERSION` ([releasing](maintaining.md#releasing)) | diff --git a/docs/content/docs/contributing/tests.md b/docs/content/docs/contributing/tests.md index cda1e71c..6d82cf4a 100644 --- a/docs/content/docs/contributing/tests.md +++ b/docs/content/docs/contributing/tests.md @@ -18,13 +18,30 @@ 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` and `gitprotect`. 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` 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. Anything `Main` or `Check` finds is a leak to fix, with a test that fails without the fix. Only a goroutine the standard library starts, that outlives every test, goes in `allowed`. A new package that starts goroutines gets a `main_test.go` that calls `leaktest.Main`, which the structure test checks, and the structure test lists every goroutine devvm's code starts, with what waits for it to end ([`goroutineSites`](structure.md#the-structure-test)). +## Time and lifecycles + +A test of a timeout, a grace or a close, such as the relay's grace, the forwarder's close or the proxy's ClientHello deadline, runs in a [`testing/synctest`](https://pkg.go.dev/testing/synctest) bubble, `synctest.Test(t, func(t *testing.T) { … })`, rather than sleeping on the real clock. Inside the bubble, time is fake and moves only when every goroutine of the test is blocked, so `time.Sleep(30 * time.Second)` returns at once, and `synctest.Wait()` returns once every other goroutine has done what it can. Such a test takes no time, and a loaded CI machine can't make it fail, so it never needs the margins a real-clock test does. + +A test checks that something happens at the moment it's due and not a nanosecond before: it sleeps to just short of the moment, calls `synctest.Wait()` and checks, then sleeps the last nanosecond and checks again. A goroutine that never ends fails the bubble as a deadlock, and a test of something that starts and stops goroutines calls [`leaktest.Check(t)`](#goroutine-leaks) before the bubble as well. + +Time moves only while each goroutine waits on something inside the bubble: a channel, a timer, `time.Sleep`, a `sync.Cond` or a wait group. A socket's read, a process's wait or any system call that blocks keeps it from moving, so the code under test gets seams, fields that a test sets to stand-ins in memory, as every test seam is a field: + +- **`internal/memnet`** is a network in memory for tests: `memnet.Pipe()` makes a connection, and a `memnet.Network` holds listeners by address, whose `Listen`, `Dial` and `DialContext` stand in for a socket's. Its connections close their writing side alone (`CloseWrite`), as TCP's do and `net.Pipe`'s don't, hold up to 64 KiB that the other end hasn't read before a write waits, as a socket's buffer does, and have deadlines on the bubble's clock, and its listeners have `SetDeadline` too. It uses only the standard library, so the proxy's tests use it. +- **The forwarder and the link sessions** take their listeners from their `Listen` fields, so a test gives them a `memnet.Network`'s. +- **The relays** carry each connection through an `sshRelay`, whose `start` field starts its `ssh -W`. In production it's `execSSH`, and a test's stand-in, `memSSH`, is a VM in memory that sends what the test tells it and ends only when its context does, as `exec.CommandContext` kills ssh. +- **The proxy** connects to the far ends through its egress's `connect` field, which `memServe` points at a `memnet.Network` while it serves the proxy on a listener in memory. +- **A `daemon.Proc`** asks its `Alive`, `Args` and `Signal` fields about its process, so a test of `Stop` gives it a process table of its own (`fakeProc`). +- **A test's own HTTP server**, when the test sends the requests itself, is `httptest.NewTestServer`'s, which serves in memory, and the test sends through its `Client()`, which reaches it whatever the request's host. + +A stand-in can't show what the real thing does with a kernel's buffers, a real ssh or a real process, so each kind of lifecycle keeps one test that runs the real one, on the real clock: `TestPipeSSHGrace`, `TestPipeSSHGraceSlowClient` and `TestPipeSSHGraceWriteError` run the relay with an ssh stand-in on `PATH`, `TestForwarderEndsStuckRelay` closes a forward whose relay's ssh never ends, `TestLinksBurst` fills a link's real Unix socket, `TestSpliceKeepsAnEarlyAnswer` splices over TCP and `TestProcStop` stops real processes. A new seam keeps the real test of its kind. + ## CLI tests CLI tests are [testscript](https://pkg.go.dev/github.com/rogpeppe/go-internal/testscript) scripts in `testdata/script/*.txtar`, run by `internal/cli/script_test.go` against a freshly built `devvm`. Call it with `exec devvm …`: diff --git a/docs/content/docs/internals/design.md b/docs/content/docs/internals/design.md index e8c64a4b..f461ef71 100644 --- a/docs/content/docs/internals/design.md +++ b/docs/content/docs/internals/design.md @@ -81,7 +81,7 @@ These settings guard against the host's ssh asking for a forward that devvm's en - **A tier's confinement:** ruled out. Listed ports take fewer ports than every port, never more, and every connection still starts on the host. - **Another VM takes a stopped or restarting VM's listed port:** mitigated. Only a running VM holds a port, so while VM V is stopped, another VM E may forward V's listed port, and a hostile E could then try to keep it, such as by forwarding every port and holding its ssh session open without reporting again. Three things stop that. First, the host decides when a port is given up: every forwarder closes each forward whose port is now reserved within 10 s on its own clock, whatever its VM reports, so E gives V's port up once V runs and lists it. Closing a forward also closes every connection it accepted that's still open, so a browser's keep-alive connection to `localhost:5173`, opened while E had the port, ends then too, and the browser's later requests, with V's cookies, never reach E over it. Second, V's start, a change of its ports and `devvm ports` warn with `ports_held` and name E in `held_by`, whether E lists the port or forwards every port, so V never waits silently. Third, V's listed ports stay reserved while devvm holds V's `ports.lock`, from stopping V's old forwarder until its new one runs, so no other VM takes them in that window. A stale `ports.forwarded` can't hold a port either: devvm removes it under that lock before each start, each forwarder writes an empty one when it starts, and a record counts only while its pid is the VM's running forwarder. - **A relay the VM holds open:** confirmed, fixed. Closing a forward closed the connections it had accepted, but each connection's ssh (`-W`) waits for the VM's sshd to end its channel, so a hostile VM that ignored the EOF kept that ssh process, and one of the forwarder's 256 relays, until the forwarder ended. Up to 256 such ssh processes could pile up on the host for each VM, and the VM's forwards would then refuse every new connection. Each relay now runs with a context of its own, which closing its forward cancels, under the forwarder's lock as the close already runs, so the ssh is killed (`exec.CommandContext`), and a relay that ends by itself releases its context. Unit-tested with an ssh stand-in that never exits on its own: the relay ends, its process is gone and its slot is free once the forward closes (`TestForwarderEndsStuckRelay`), with no goroutine or file descriptor left under `-race`. -- **A relay the VM holds open after its client has gone:** mitigated. While a forward lasts, a VM that ignores EOF would keep each relay whose client on the host had closed, its ssh process and one of the 256, so a hostile VM could fill the forwarder's relays with connections a browser had already closed. Each relay's ssh is killed once its client has closed and the VM has sent nothing for 30 seconds, or 30 seconds after the client can take nothing more, so a VM keeps such a relay only by sending to it, and only for as long as the client keeps its side open for reading. The grace doesn't run while a write waits for a slow client, so a client that stops reading holds the relay and its ssh itself, as it could by staying open, until it reads again, closes, or the relay's forward or link goes. Unit-tested with an ssh stand-in that never exits: a closed client's relay and a half-closed one's both end after the grace when the stand-in is silent, and one the stand-in keeps talking to goes on past it, while a fully closed client's relay, and one whose writes to its client fail, end within the grace however much the stand-in sends. A half-closed client that doesn't read for many graces still gets all of the stand-in's answer after and a relay whose write waits on a client that stopped reading ends when its context does (`TestPipeSSHGrace`, `TestPipeSSHGraceWriteError`, `TestPipeSSHGraceSlowClient`, `TestPipeSSHCancelEndsBlockedWrite`, `TestGraceTimer`). The price is a client that half-closes and waits more than 30 seconds for an answer's first byte, which is cut. +- **A relay the VM holds open after its client has gone:** mitigated. While a forward lasts, a VM that ignores EOF would keep each relay whose client on the host had closed, its ssh process and one of the 256, so a hostile VM could fill the forwarder's relays with connections a browser had already closed. Each relay's ssh is killed once its client has closed and the VM has sent nothing for 30 seconds, or 30 seconds after the client can take nothing more, so a VM keeps such a relay only by sending to it, and only for as long as the client keeps its side open for reading. The grace doesn't run while a write waits for a slow client, so a client that stops reading holds the relay and its ssh itself, as it could by staying open, until it reads again, closes, or the relay's forward or link goes. Unit-tested with an ssh stand-in that never exits: a closed client's relay and a half-closed one's both end after the grace when the stand-in is silent, and one the stand-in keeps talking to goes on past it, while a fully closed client's relay, and one whose writes to its client fail, end within the grace however much the stand-in sends. A half-closed client that doesn't read for many graces still gets all of the stand-in's answer after and a relay whose write waits on a client that stopped reading ends when its context does (`TestPipeSSHGrace`, `TestPipeSSHGraceWriteError`, `TestPipeSSHGraceSlowClient`, `TestRelayGrace`, `TestRelayGraceWriteError`, `TestRelayGraceSlowClient`, `TestRelayCancelEndsBlockedWrite`, `TestGraceTimer`). The price is a client that half-closes and waits more than 30 seconds for an answer's first byte, which is cut. - **A forward on IPv4 alone:** ruled out but for a host without IPv6 or one that denies it. A bind on `::1` that fails with an error that says nothing of the port, such as `EMFILE` or `ENOBUFS`, closes the port's `127.0.0.1` listener, is logged, and has the port tried again at the next report, so `localhost` never reaches the VM on one address and another program, or nothing, on the other. Only `EADDRNOTAVAIL`, `EAFNOSUPPORT` and `EPROTONOSUPPORT`, a host without IPv6, give IPv4 alone, and so do `EACCES` and `EPERM` on `::1` alone, logged, as a security module that denies IPv6 sockets would otherwise stop every forward. On such a host, a program that the module lets use IPv6 could still take `::1` on a forwarded port, and `localhost` would then reach it there, which is listed rather than refused because the alternative is no forwarding at all. Unit-tested with each error on `::1` (`TestForwarderIPv6Failures`). - **Channels the VM never closes in the master:** listed. A hostile VM that never sends CLOSE for a killed relay's channel can leave small channel entries, with no file descriptor, in the forwarder's ssh master. At most 256 relays run at once, which bounds them, and no code change is needed. diff --git a/internal/daemon/daemon_test.go b/internal/daemon/daemon_test.go index 28542a59..360b18ef 100644 --- a/internal/daemon/daemon_test.go +++ b/internal/daemon/daemon_test.go @@ -7,8 +7,10 @@ import ( "slices" "strconv" "strings" + "sync" "syscall" "testing" + "testing/synctest" "time" ) @@ -290,80 +292,134 @@ func TestProcStop(t *testing.T) { // fails first): Stop waits until it's gone, so its port is free when Stop // returns. func TestProcStopWaitsForTheEnd(t *testing.T) { - p, start, ours := proc(t) - ending := map[int]bool{} - args := p.Args - p.Args = func(pid int) ([]string, error) { - if ending[pid] { - return nil, errors.New("ending") + synctest.Test(t, func(t *testing.T) { + const wait = 2 * time.Second + f := &fakeProc{onTerm: 450 * time.Millisecond, unreadable: true} + p := f.proc(t) + start := time.Now() + if !p.Stop(wait) { + t.Fatal("not stopped") } - return args(pid) - } - p.Signal = func(pid int, sig syscall.Signal) error { - ending[pid] = true - return Signal(pid, sig) - } - out := filepath.Join(t.TempDir(), "out") - f, err := os.Create(out) //nolint:gosec // the test's own file - if err != nil { - t.Fatal(err) - } - defer func() { _ = f.Close() }() - pid, err := p.Start(start, Cmd{Path: "/bin/sh", Args: []string{"-c", `trap "sleep 0.5; exit 0" TERM; echo ready; while :; do sleep 0.05; done`}, Out: f}) - if err != nil { - t.Fatal(err) - } - output(t, out, "ready") - if !ours[pid] { - t.Fatal("not the test's") - } - if !p.Stop(2 * time.Second) { - t.Fatal("not stopped") - } - if Alive(pid) { - t.Error("Stop returned while the process was still ending") - } + if f.alive { + t.Error("Stop returned while the process was still ending") + } + // At its first look after the end: Stop looks every twentieth of + // wait. + if took := time.Since(start); took != 500*time.Millisecond { + t.Errorf("Stop took %s for one that ended %s after SIGTERM, want 500ms", took, f.onTerm) + } + if !slices.Equal(f.signalled, []string{"terminated"}) { + t.Errorf("signalled %v", f.signalled) + } + }) } // SIGKILL goes only to a process whose arguments still say it's the one: // one whose arguments can't be read after SIGTERM (still ending, or -// another given the pid) is waited for, never killed. +// another given the pid) is waited for, never killed, and Stop gives up +// after twice wait, to the moment on the bubble's clock. func TestProcStopKillsOnlyItsOwn(t *testing.T) { - p, start, _ := proc(t) - unreadable := map[int]bool{} - args := p.Args - p.Args = func(pid int) ([]string, error) { - if unreadable[pid] { - return nil, errors.New("unreadable") + synctest.Test(t, func(t *testing.T) { + const wait = 200 * time.Millisecond + f := &fakeProc{unreadable: true} + p := f.proc(t) + start := time.Now() + if p.Stop(wait) { + t.Error("stopped, though it ignores SIGTERM") } - return args(pid) + if took := time.Since(start); took != 2*wait { + t.Errorf("Stop gave up after %s, want %s", took, 2*wait) + } + if !slices.Equal(f.signalled, []string{"terminated"}) { + t.Errorf("signalled %v, want only SIGTERM", f.signalled) + } + if !f.alive { + t.Error("killed") + } + }) +} + +// Stop's steps on the bubble's clock: SIGTERM at once, SIGKILL wait later +// to one that ignores it, and its pid file gone once it has ended. +func TestProcStopKillsAfterWait(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + const wait = time.Second + f := &fakeProc{} + p := f.proc(t) + start := time.Now() + if !p.Stop(wait) { + t.Fatal("not stopped") + } + if !slices.Equal(f.signalled, []string{"terminated", "killed"}) || !f.killedAt.Equal(start.Add(wait)) { + t.Errorf("signalled %v, SIGKILL after %s; want SIGTERM, then SIGKILL after %s", f.signalled, f.killedAt.Sub(start), wait) + } + if _, err := os.Stat(p.PIDFile); !errors.Is(err, os.ErrNotExist) { + t.Errorf("its pid file stayed: %v", err) + } + }) +} + +// fakeProc is one process, in a test's process table: it ends onTerm +// after SIGTERM (never, when 0) and at once on SIGKILL, and while it +// ends after SIGTERM its arguments can't be read when unreadable (macOS's +// kern.procargs2 fails first). +type fakeProc struct { + onTerm time.Duration + unreadable bool + + mu sync.Mutex + alive bool + termed bool + signalled []string + killedAt time.Time +} + +// fakePID is the fake process's pid, which no test process has. +const fakePID = 1 << 30 + +// proc is a Proc for f, which runs, its pid in its pid file. +func (f *fakeProc) proc(t *testing.T) Proc { + t.Helper() + f.alive = true + p := Proc{ + PIDFile: filepath.Join(t.TempDir(), "v.pid"), + Is: func(args []string) bool { return HasFlag(args, "_x", "-vm", "v") }, + Args: func(pid int) ([]string, error) { + f.mu.Lock() + defer f.mu.Unlock() + if pid != fakePID || !f.alive { + return nil, errors.New("no such process") + } + if f.termed && f.unreadable { + return nil, errors.New("ending") + } + return []string{"/devvm", "_x", "-vm", "v"}, nil + }, + Alive: func(pid int) bool { + f.mu.Lock() + defer f.mu.Unlock() + return pid == fakePID && f.alive + }, + Signal: func(_ int, sig syscall.Signal) error { + f.mu.Lock() + defer f.mu.Unlock() + f.signalled = append(f.signalled, sig.String()) + switch { + case sig == syscall.SIGKILL: + f.alive, f.killedAt = false, time.Now() + case sig == syscall.SIGTERM && f.onTerm > 0: + f.termed = true + time.AfterFunc(f.onTerm, func() { f.mu.Lock(); f.alive = false; f.mu.Unlock() }) + case sig == syscall.SIGTERM: + f.termed = true + } + return nil + }, } - var signalled []string - p.Signal = func(pid int, sig syscall.Signal) error { - signalled = append(signalled, sig.String()) - unreadable[pid] = true - return Signal(pid, sig) - } - out := filepath.Join(t.TempDir(), "out") - f, err := os.Create(out) //nolint:gosec // the test's own file - if err != nil { + if err := os.WriteFile(p.PIDFile, []byte(strconv.Itoa(fakePID)+"\n"), 0o600); err != nil { t.Fatal(err) } - defer func() { _ = f.Close() }() - pid, err := p.Start(start, Cmd{Path: "/bin/sh", Args: []string{"-c", `trap "" TERM; echo ready; while :; do sleep 0.05; done`}, Out: f}) - if err != nil { - t.Fatal(err) - } - output(t, out, "ready") - if p.Stop(200 * time.Millisecond) { - t.Error("stopped, though it ignores SIGTERM") - } - if !slices.Equal(signalled, []string{"terminated"}) { - t.Errorf("signalled %v, want only SIGTERM", signalled) - } - if !Alive(pid) { - t.Error("killed") - } + return p } // A start removes the status file an earlier start left, so readiness is diff --git a/internal/daemon/lifeline_test.go b/internal/daemon/lifeline_test.go index a0e74e73..d0786a2e 100644 --- a/internal/daemon/lifeline_test.go +++ b/internal/daemon/lifeline_test.go @@ -5,6 +5,7 @@ import ( "path/filepath" "strconv" "testing" + "testing/synctest" "time" ) @@ -70,68 +71,91 @@ func TestLifelineHolds(t *testing.T) { // that runs, as a proxy started before its VM does: past what the file // held when it first looked (an earlier start's), but not past a new // start's whose process is already gone (a VM that stopped between two -// looks). With no wait it looks once. +// looks). With no wait it looks once. Each look is a tick apart on the +// bubble's clock, so each step ends at the look it's due: the test's own +// process stands for one that runs, and ended ones' pids, from before the +// bubble, for those gone. func TestFollowLifeline(t *testing.T) { - dir := t.TempDir() - path := filepath.Join(dir, "ha.pid") - if _, ok := FollowLifeline(path, 0, time.Millisecond); ok { - t.Error("none: followed") - } - start := time.Now() - if _, ok := FollowLifeline(path, 100*time.Millisecond, 10*time.Millisecond); ok || time.Since(start) < 80*time.Millisecond { - t.Errorf("none: followed %v, after %v", ok, time.Since(start)) - } - // An earlier start's, then this one's. - write(t, path, strconv.Itoa(gone(t))+"\n") - got := make(chan Lifeline, 1) - go func() { - l, _ := FollowLifeline(path, 10*time.Second, 10*time.Millisecond) - got <- l - }() - time.Sleep(50 * time.Millisecond) - select { - case l := <-got: - t.Fatalf("followed an earlier start's: %+v", l) - default: - } - h, err := Spawn(Cmd{Path: "sleep", Args: []string{"30"}}) - if err != nil { - t.Fatal(err) - } - defer h.Stop(time.Second) - write(t, path, strconv.Itoa(h.PID())+"\n") - select { - case l := <-got: - if l.Life != strconv.Itoa(h.PID()) || !l.Holds() { - t.Errorf("followed %+v", l) + path := filepath.Join(t.TempDir(), "ha.pid") + earlier, stopped, again := gone(t), gone(t), gone(t) + me := strconv.Itoa(os.Getpid()) + const tick = 10 * time.Millisecond + synctest.Test(t, func(t *testing.T) { + start := time.Now() + if _, ok := FollowLifeline(path, 0, tick); ok || time.Since(start) != 0 { + t.Errorf("none, no wait: followed %v, after %v", ok, time.Since(start)) } - // It holds until its process ends. - done := make(chan struct{}) - go func() { l.Wait(10 * time.Millisecond); close(done) }() - h.Stop(time.Second) + // Its last look is the last a tick before the wait ends. + if _, ok := FollowLifeline(path, 100*time.Millisecond, tick); ok || time.Since(start) != 90*time.Millisecond { + t.Errorf("none: followed %v, after %v", ok, time.Since(start)) + } + // An earlier start's, then this one's. + write(t, path, strconv.Itoa(earlier)+"\n") + got := make(chan Lifeline, 1) + go func() { + l, _ := FollowLifeline(path, 10*time.Second, tick) + got <- l + }() + time.Sleep(time.Second) + synctest.Wait() select { - case <-done: - case <-time.After(5 * time.Second): - t.Error("Wait: still waiting with its process gone") + case l := <-got: + t.Fatalf("followed an earlier start's: %+v", l) + default: } - case <-time.After(5 * time.Second): - t.Fatal("never followed") - } - // A new start's, already gone, ends the wait at once. - write(t, path, strconv.Itoa(gone(t))+"\n") - ended := make(chan bool, 1) - go func() { - _, ok := FollowLifeline(path, 10*time.Second, 10*time.Millisecond) - ended <- ok - }() - time.Sleep(50 * time.Millisecond) - write(t, path, strconv.Itoa(gone(t))+"\n") + write(t, path, me+"\n") + time.Sleep(tick) + synctest.Wait() + select { + case l := <-got: + if l.Life != me || !l.Holds() { + t.Errorf("followed %+v", l) + } + // It holds until a new start rewrites it: Wait ends at its next + // look. + done := make(chan struct{}) + go func() { l.Wait(tick); close(done) }() + time.Sleep(time.Second) + synctest.Wait() + if isClosed(done) { + t.Fatal("Wait: ended while it held") + } + write(t, path, strconv.Itoa(stopped)+"\n") + time.Sleep(tick) + synctest.Wait() + if !isClosed(done) { + t.Error("Wait: still waiting a tick after it no longer held") + } + default: + t.Fatal("not followed a tick after it named a process that runs") + } + // A new start's, already gone, ends the wait at its next look. + ended := make(chan bool, 1) + go func() { + _, ok := FollowLifeline(path, 10*time.Second, tick) + ended <- ok + }() + time.Sleep(time.Second) + write(t, path, strconv.Itoa(again)+"\n") + time.Sleep(tick) + synctest.Wait() + select { + case ok := <-ended: + if ok { + t.Error("followed a lifeline whose process is gone") + } + default: + t.Error("still waiting a tick past a new start's lifeline whose process is gone") + } + }) +} + +// isClosed reports whether ch is closed. +func isClosed(ch chan struct{}) bool { select { - case ok := <-ended: - if ok { - t.Error("followed a lifeline whose process is gone") - } - case <-time.After(5 * time.Second): - t.Error("still waiting past a new start's lifeline whose process is gone") + case <-ch: + return true + default: + return false } } diff --git a/internal/daemon/proc.go b/internal/daemon/proc.go index 93c7cfd0..3fe1f60f 100644 --- a/internal/daemon/proc.go +++ b/internal/daemon/proc.go @@ -23,6 +23,16 @@ type Proc struct { Args func(pid int) ([]string, error) // Signal sends it a signal: Signal, or a test's. Signal func(pid int, sig syscall.Signal) error + // Alive reports whether a process has pid: Alive, or a test's. + Alive func(pid int) bool +} + +// alive reports whether a process has pid (Alive). +func (p Proc) alive(pid int) bool { + if p.Alive == nil { + return Alive(pid) + } + return p.Alive(pid) } // HasFlag reports whether args, its program first, run devvm's command @@ -38,7 +48,7 @@ func HasFlag(args []string, cmd, flag, val string) bool { // PID returns the process's pid while it runs. func (p Proc) PID() (int, bool) { pid, ok := readLine(p.PIDFile) - if !ok || !Alive(pid) { + if !ok || !p.alive(pid) { return 0, false } args, err := p.Args(pid) @@ -115,7 +125,7 @@ func (p Proc) Stop(wait time.Duration) bool { // port it listens on is still its own a moment after (macOS's // kern.procargs2 fails first). func (p Proc) ended(pid int) bool { - if !Alive(pid) { + if !p.alive(pid) { return true } args, err := p.Args(pid) @@ -138,7 +148,7 @@ func (p Proc) Ready(status string, pid int, tick time.Duration, tries int) (stri // once it's gone. func (p Proc) starting(pid int) bool { cur, ok := readLine(p.PIDFile) - if !ok || cur != pid || !Alive(pid) { + if !ok || cur != pid || !p.alive(pid) { return false } args, err := p.Args(pid) diff --git a/internal/memnet/memnet.go b/internal/memnet/memnet.go new file mode 100644 index 00000000..98b14f83 --- /dev/null +++ b/internal/memnet/memnet.go @@ -0,0 +1,370 @@ +// Package memnet is a network in memory for tests: connections (Pipe) +// and listeners (Network) whose every wait is one a testing/synctest +// bubble counts as durably blocked, so a test of a timeout or of what +// ends what runs on the bubble's own clock, where a socket's wait would +// keep the bubble's time from moving. A connection closes its writing +// side alone (CloseWrite), as TCP's does and net.Pipe's can't, holds +// what it's sent up to a buffer's worth, so a writer to a reader that +// stops waits as it would on a socket, and has deadlines. Its errors are +// a Unix socket's: once the other end has closed, the first write fails +// with EPIPE, and a read gets EOF, never a reset. +// +// It's for tests only, and standard library only, so internal/proxy's +// tests use it too. +package memnet + +import ( + "context" + "io" + "net" + "os" + "sync" + "syscall" + "time" +) + +// bufMax is how much one direction of a connection holds before a write +// waits for its reader. +const bufMax = 64 << 10 + +// addr is an address in memory: a listener's, as its test named it. +type addr string + +func (a addr) Network() string { return "mem" } +func (a addr) String() string { return string(a) } + +// way is one direction of a connection: what's sent and not yet read, +// whether its writer has closed it (EOF once read), and whether its +// reader has (its writes fail). +type way struct { + buf []byte + eof bool + readGone bool +} + +// pipe is a connection's two directions and what its two ends wait on. +type pipe struct { + mu sync.Mutex + cond *sync.Cond + ways [2]way +} + +// A Conn is one end of a connection in memory. It reads ways[side] and +// writes the other. +type Conn struct { + p *pipe + side int + local, remote addr + + // Under p.mu. + closed bool + rdline, wrline time.Time + rtimer, wtimer *time.Timer +} + +// Pipe is a connection in memory: a's writes are b's reads, and b's a's. +func Pipe() (a, b *Conn) { return pipeAt("a", "b") } + +func pipeAt(local, remote string) (a, b *Conn) { + p := &pipe{} + p.cond = sync.NewCond(&p.mu) + return &Conn{p: p, side: 0, local: addr(local), remote: addr(remote)}, + &Conn{p: p, side: 1, local: addr(remote), remote: addr(local)} +} + +func (c *Conn) in() *way { return &c.p.ways[c.side] } +func (c *Conn) out() *way { return &c.p.ways[1-c.side] } + +// opError is err as a socket's would be, for op. +func (c *Conn) opError(op string, err error) error { + return &net.OpError{Op: op, Net: "mem", Source: c.local, Addr: c.remote, Err: err} +} + +// passed is whether deadline d has passed; its caller holds p.mu. +func passed(d time.Time) bool { return !d.IsZero() && !time.Now().Before(d) } + +// Read reads what the other end sent: io.EOF once it has closed its +// writing side and all it sent is read. +func (c *Conn) Read(b []byte) (int, error) { + if len(b) == 0 { + return 0, nil + } + c.p.mu.Lock() + defer c.p.mu.Unlock() + w := c.in() + for { + switch { + case c.closed: + return 0, c.opError("read", net.ErrClosed) + case passed(c.rdline): + return 0, c.opError("read", os.ErrDeadlineExceeded) + case len(w.buf) > 0: + n := copy(b, w.buf) + w.buf = w.buf[n:] + c.p.cond.Broadcast() + return n, nil + case w.eof: + return 0, io.EOF + } + c.p.cond.Wait() + } +} + +// Write sends b to the other end, waiting while what it holds is full: +// EPIPE once the other end has closed. +func (c *Conn) Write(b []byte) (int, error) { + c.p.mu.Lock() + defer c.p.mu.Unlock() + w := c.out() + n := 0 + for { + switch { + case c.closed: + return n, c.opError("write", net.ErrClosed) + case w.eof: + return n, c.opError("write", syscall.EPIPE) + case w.readGone: + return n, c.opError("write", syscall.EPIPE) + case passed(c.wrline) && (n < len(b) || n == 0): + return n, c.opError("write", os.ErrDeadlineExceeded) + case n == len(b): + return n, nil + case len(w.buf) < bufMax: + k := min(len(b)-n, bufMax-len(w.buf)) + w.buf = append(w.buf, b[n:n+k]...) + n += k + c.p.cond.Broadcast() + continue + } + c.p.cond.Wait() + } +} + +// CloseWrite closes the writing side alone: the other end reads EOF once +// it has read what was sent, and can still send. +func (c *Conn) CloseWrite() error { + c.p.mu.Lock() + defer c.p.mu.Unlock() + c.out().eof = true + c.p.cond.Broadcast() + return nil +} + +// Close closes both sides: the other end reads EOF, and its writes fail. +func (c *Conn) Close() error { + c.p.mu.Lock() + defer c.p.mu.Unlock() + if c.closed { + return c.opError("close", net.ErrClosed) + } + c.closed = true + c.out().eof = true + in := c.in() + in.readGone, in.buf = true, nil + for _, t := range []*time.Timer{c.rtimer, c.wtimer} { + if t != nil { + t.Stop() + } + } + c.p.cond.Broadcast() + return nil +} + +// LocalAddr is this end's address: its listener's for an accepted one. +func (c *Conn) LocalAddr() net.Addr { return c.local } + +// RemoteAddr is the other end's address. +func (c *Conn) RemoteAddr() net.Addr { return c.remote } + +// SetDeadline sets when a waiting read or write gives up. +func (c *Conn) SetDeadline(t time.Time) error { + _ = c.SetReadDeadline(t) + return c.SetWriteDeadline(t) +} + +// SetReadDeadline sets when a waiting read gives up. +func (c *Conn) SetReadDeadline(t time.Time) error { + c.p.mu.Lock() + defer c.p.mu.Unlock() + c.rdline, c.rtimer = t, c.wake(c.rtimer, t) + return nil +} + +// SetWriteDeadline sets when a waiting write gives up. +func (c *Conn) SetWriteDeadline(t time.Time) error { + c.p.mu.Lock() + defer c.p.mu.Unlock() + c.wrline, c.wtimer = t, c.wake(c.wtimer, t) + return nil +} + +// wake stops old and returns a timer that wakes the waiting ends at t, +// none for no deadline. Its caller holds p.mu. +func (c *Conn) wake(old *time.Timer, t time.Time) *time.Timer { + if old != nil { + old.Stop() + } + c.p.cond.Broadcast() + if t.IsZero() { + return nil + } + return time.AfterFunc(time.Until(t), func() { + c.p.mu.Lock() + defer c.p.mu.Unlock() + c.p.cond.Broadcast() + }) +} + +// A Network is listeners by address, which its dials reach. Its zero +// value has none. +type Network struct { + mu sync.Mutex + ls map[string]*Listener +} + +// Listen listens at address: EADDRINUSE while another listener has it. +func (n *Network) Listen(address string) (*Listener, error) { + n.mu.Lock() + defer n.mu.Unlock() + if n.ls[address] != nil { + return nil, &net.OpError{Op: "listen", Net: "mem", Addr: addr(address), Err: syscall.EADDRINUSE} + } + if n.ls == nil { + n.ls = map[string]*Listener{} + } + l := &Listener{n: n, addr: addr(address)} + l.cond = sync.NewCond(&l.mu) + n.ls[address] = l + return l, nil +} + +// Dial connects to the listener at address: ECONNREFUSED for none. +func (n *Network) Dial(address string) (*Conn, error) { + n.mu.Lock() + l := n.ls[address] + n.mu.Unlock() + if l == nil { + return nil, refused(address) + } + return l.Dial() +} + +// DialContext is Dial, as net.Dialer's: network is the test's to pick. +func (n *Network) DialContext(_ context.Context, _, address string) (net.Conn, error) { + c, err := n.Dial(address) + if err != nil { + return nil, err + } + return c, nil +} + +// Listening reports whether a listener has address. +func (n *Network) Listening(address string) bool { + n.mu.Lock() + defer n.mu.Unlock() + return n.ls[address] != nil +} + +func refused(address string) error { + return &net.OpError{Op: "dial", Net: "mem", Addr: addr(address), Err: syscall.ECONNREFUSED} +} + +// A Listener is a Network's listener at an address, whose dials wait to +// be accepted. +type Listener struct { + n *Network + addr addr + + mu sync.Mutex + cond *sync.Cond + queue []*Conn + closed bool + line time.Time + timer *time.Timer +} + +// Dial connects to l: the other end waits for Accept. ECONNREFUSED once +// l is closed. +func (l *Listener) Dial() (*Conn, error) { + l.mu.Lock() + defer l.mu.Unlock() + if l.closed { + return nil, refused(string(l.addr)) + } + client, server := pipeAt("client", string(l.addr)) + l.queue = append(l.queue, server) + l.cond.Broadcast() + return client, nil +} + +// Accept waits for a dial: net.ErrClosed once l is closed, +// os.ErrDeadlineExceeded past its deadline. +func (l *Listener) Accept() (net.Conn, error) { + l.mu.Lock() + defer l.mu.Unlock() + for { + switch { + case l.closed: + return nil, &net.OpError{Op: "accept", Net: "mem", Addr: l.addr, Err: net.ErrClosed} + case len(l.queue) > 0: + c := l.queue[0] + l.queue = l.queue[1:] + return c, nil + case passed(l.line): + return nil, &net.OpError{Op: "accept", Net: "mem", Addr: l.addr, Err: os.ErrDeadlineExceeded} + } + l.cond.Wait() + } +} + +// Close stops listening, and closes each dial not yet accepted. +func (l *Listener) Close() error { + l.mu.Lock() + if l.closed { + l.mu.Unlock() + return &net.OpError{Op: "close", Net: "mem", Addr: l.addr, Err: net.ErrClosed} + } + l.closed = true + queued := l.queue + l.queue = nil + if l.timer != nil { + l.timer.Stop() + } + l.cond.Broadcast() + l.mu.Unlock() + for _, c := range queued { + _ = c.Close() + } + if l.n != nil { + l.n.mu.Lock() + if l.n.ls[string(l.addr)] == l { + delete(l.n.ls, string(l.addr)) + } + l.n.mu.Unlock() + } + return nil +} + +// Addr is the address it listens at. +func (l *Listener) Addr() net.Addr { return l.addr } + +// SetDeadline sets when a waiting Accept gives up, as a TCP or Unix +// listener's does. +func (l *Listener) SetDeadline(t time.Time) error { + l.mu.Lock() + defer l.mu.Unlock() + if l.timer != nil { + l.timer.Stop() + l.timer = nil + } + l.line = t + l.cond.Broadcast() + if !t.IsZero() { + l.timer = time.AfterFunc(time.Until(t), func() { + l.mu.Lock() + defer l.mu.Unlock() + l.cond.Broadcast() + }) + } + return nil +} diff --git a/internal/memnet/memnet_test.go b/internal/memnet/memnet_test.go new file mode 100644 index 00000000..cbb4ccd1 --- /dev/null +++ b/internal/memnet/memnet_test.go @@ -0,0 +1,254 @@ +package memnet + +import ( + "bytes" + "errors" + "io" + "net" + "os" + "syscall" + "testing" + "testing/synctest" + "time" + + "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) } + +// A connection carries each end's bytes to the other, in order; one end +// closing its writing side alone gives the other EOF once it has read +// what was sent, and it can still answer; closing gives the other end +// EOF and fails its writes; a closed end can't be used. +func TestPipe(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + a, b := Pipe() + go func() { + _, _ = a.Write([]byte("hello")) + _ = a.CloseWrite() + }() + if got, err := io.ReadAll(b); string(got) != "hello" || err != nil { + t.Errorf("read %q, %v", got, err) + } + if _, err := a.Write([]byte("x")); !errors.Is(err, syscall.EPIPE) { + t.Errorf("a write after CloseWrite: %v", err) + } + go func() { _, _ = b.Write([]byte("answer")) }() + buf := make([]byte, 6) + if _, err := io.ReadFull(a, buf); string(buf) != "answer" || err != nil { + t.Errorf("the answer after a half close: %q, %v", buf, err) + } + _ = b.Close() + if _, err := a.Read(buf); !errors.Is(err, io.EOF) { + t.Errorf("a read once the other end closed: %v", err) + } + if _, err := a.Write([]byte("x")); !errors.Is(err, syscall.EPIPE) { + t.Errorf("a write once the other end closed: %v", err) + } + if _, err := b.Read(buf); !errors.Is(err, net.ErrClosed) { + t.Errorf("a read on a closed end: %v", err) + } + if err := b.Close(); !errors.Is(err, net.ErrClosed) { + t.Errorf("closed twice: %v", err) + } + if a.LocalAddr().String() != "a" || a.RemoteAddr().String() != "b" || b.LocalAddr().Network() != "mem" { + t.Errorf("addresses %s, %s, %s", a.LocalAddr(), a.RemoteAddr(), b.LocalAddr().Network()) + } + }) +} + +// A writer waits once what the other end hasn't read fills its buffer, +// and goes on as it reads; a write that waits on a closed reader fails. +func TestPipeFull(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + a, b := Pipe() + done := make(chan int) + go func() { + n, _ := a.Write(make([]byte, bufMax+10)) + done <- n + }() + synctest.Wait() + select { + case n := <-done: + t.Fatalf("a write past the buffer returned %d without a read", n) + default: + } + if _, err := io.ReadFull(b, make([]byte, 10)); err != nil { + t.Fatal(err) + } + if n := <-done; n != bufMax+10 { + t.Errorf("wrote %d", n) + } + errc := make(chan error) + go func() { + _, err := a.Write(make([]byte, 2*bufMax)) + errc <- err + }() + synctest.Wait() + _ = b.Close() + if err := <-errc; !errors.Is(err, syscall.EPIPE) { + t.Errorf("a waiting write once the reader closed: %v", err) + } + }) +} + +// A read or a write waits until its deadline, to the moment, and a +// deadline moved or cleared while it waits holds from then on. +func TestPipeDeadlines(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + a, b := Pipe() + start := time.Now() + _ = a.SetReadDeadline(start.Add(time.Second)) + if _, err := a.Read(make([]byte, 1)); !errors.Is(err, os.ErrDeadlineExceeded) || time.Since(start) != time.Second { + t.Errorf("read: %v after %s", err, time.Since(start)) + } + _ = a.SetDeadline(time.Time{}) + got := make(chan error) + go func() { + _, err := a.Read(make([]byte, 1)) + got <- err + }() + time.Sleep(time.Hour) + synctest.Wait() + select { + case err := <-got: + t.Fatalf("a read without a deadline ended: %v", err) + default: + } + _ = a.SetReadDeadline(time.Now().Add(time.Minute)) + start = time.Now() + if err := <-got; !errors.Is(err, os.ErrDeadlineExceeded) || time.Since(start) != time.Minute { + t.Errorf("a deadline set while it waits: %v after %s", err, time.Since(start)) + } + _ = a.SetWriteDeadline(time.Now().Add(time.Second)) + start = time.Now() + n, err := a.Write(make([]byte, bufMax+1)) + if n != bufMax || !errors.Is(err, os.ErrDeadlineExceeded) || time.Since(start) != time.Second { + t.Errorf("write: %d, %v after %s", n, err, time.Since(start)) + } + _ = b.Close() + _ = a.Close() + }) +} + +// A deadline that has passed fails a read or a write at once, as TCP's +// does, though there's data to read or room to write; a read of no bytes +// returns at once, whatever waits. +func TestPipePastDeadline(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + a, b := Pipe() + if _, err := b.Write([]byte("x")); err != nil { + t.Fatal(err) + } + if n, err := a.Read(nil); n != 0 || err != nil { + t.Errorf("a read of no bytes: %d, %v", n, err) + } + _ = a.SetDeadline(time.Now()) + if n, err := a.Read(make([]byte, 1)); n != 0 || !errors.Is(err, os.ErrDeadlineExceeded) { + t.Errorf("a read with data, past its deadline: %d, %v", n, err) + } + if n, err := a.Write([]byte("y")); n != 0 || !errors.Is(err, os.ErrDeadlineExceeded) { + t.Errorf("a write with room, past its deadline: %d, %v", n, err) + } + _ = a.SetDeadline(time.Time{}) + got := make([]byte, 1) + if n, err := a.Read(got); n != 1 || err != nil || got[0] != 'x' { + t.Errorf("the data, once the deadline is cleared: %q, %v", got[:n], err) + } + _ = a.Close() + _ = b.Close() + }) +} + +// A network's listeners take the dials to their address, in order, one +// address one listener; a dial to none, or to a closed one, is refused, +// and a closed listener's waiting dials are closed. +func TestNetwork(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + var n Network + l, err := n.Listen("127.0.0.1:80") + if err != nil { + t.Fatal(err) + } + if _, err := n.Listen("127.0.0.1:80"); !errors.Is(err, syscall.EADDRINUSE) { + t.Errorf("a second listener: %v", err) + } + if _, err := n.Dial("127.0.0.1:81"); !errors.Is(err, syscall.ECONNREFUSED) { + t.Errorf("a dial to none: %v", err) + } + if !n.Listening("127.0.0.1:80") || l.Addr().String() != "127.0.0.1:80" { + t.Error("not listening") + } + go func() { + for _, s := range []string{"one", "two"} { + c, err := n.DialContext(t.Context(), "tcp", "127.0.0.1:80") + if err != nil { + t.Error(err) + return + } + _, _ = io.WriteString(c, s) + _ = c.Close() + } + }() + for _, want := range []string{"one", "two"} { + c, err := l.Accept() + if err != nil { + t.Fatal(err) + } + if got, _ := io.ReadAll(c); string(got) != want { + t.Errorf("accepted %q, want %q", got, want) + } + _ = c.Close() + } + waiting, err := n.Dial("127.0.0.1:80") + if err != nil { + t.Fatal(err) + } + _ = l.Close() + if _, err := waiting.Read(make([]byte, 1)); !errors.Is(err, io.EOF) { + t.Errorf("a dial not accepted, once its listener closed: %v", err) + } + if _, err := l.Accept(); !errors.Is(err, net.ErrClosed) { + t.Errorf("accept once closed: %v", err) + } + if _, err := l.Dial(); !errors.Is(err, syscall.ECONNREFUSED) { + t.Errorf("a dial once closed: %v", err) + } + if n.Listening("127.0.0.1:80") { + t.Error("closed, still listening") + } + if _, err := n.Listen("127.0.0.1:80"); err != nil { + t.Errorf("listening again once closed: %v", err) + } + }) +} + +// Accept waits until its deadline, to the moment; a deadline cleared +// waits for a dial. +func TestListenerDeadline(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + var n Network + l, _ := n.Listen("s") + start := time.Now() + _ = l.SetDeadline(start.Add(5 * time.Millisecond)) + if _, err := l.Accept(); !errors.Is(err, os.ErrDeadlineExceeded) || time.Since(start) != 5*time.Millisecond { + t.Errorf("accept: %v after %s", err, time.Since(start)) + } + _ = l.SetDeadline(time.Time{}) + go func() { + time.Sleep(time.Hour) + c, _ := l.Dial() + _, _ = c.Write([]byte("late")) + _ = c.Close() + }() + c, err := l.Accept() + if err != nil || time.Since(start) != time.Hour+5*time.Millisecond { + t.Fatalf("accept without a deadline: %v after %s", err, time.Since(start)) + } + if got, _ := io.ReadAll(c); !bytes.Equal(got, []byte("late")) { + t.Errorf("read %q", got) + } + _ = l.Close() + }) +} diff --git a/internal/proxy/cursor_test.go b/internal/proxy/cursor_test.go index d812c67e..d77f9df5 100644 --- a/internal/proxy/cursor_test.go +++ b/internal/proxy/cursor_test.go @@ -147,7 +147,8 @@ func TestCursorReplyScans(t *testing.T) { s := &server{captures: newCaptures(nil, nil)} before := strings.Repeat("x", 5000) + "eyJ" var gotAE string - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // In memory: its client's transport reaches it whatever the host. + srv := httptest.NewTestServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gotAE = r.Header.Get("Accept-Encoding") w.Header().Set("Content-Type", "application/proto") body := before + strings.TrimPrefix(cursorJWT, "\x0a\x40eyJ") @@ -166,12 +167,12 @@ func TestCursorReplyScans(t *testing.T) { _, _ = io.WriteString(w, "\x0a\x03abc") } })) - t.Cleanup(srv.Close) + tr := srv.Client().Transport for _, p := range []string{"/gzip", "/chunked"} { - req, _ := http.NewRequestWithContext(t.Context(), http.MethodPost, srv.URL+p, nil) + req, _ := http.NewRequestWithContext(t.Context(), http.MethodPost, "http://cursor.test"+p, nil) req.Header.Set("Accept-Encoding", "br") // the VM's cursorUnencoded(req.Header) - resp, err := http.DefaultTransport.RoundTrip(req) + resp, err := tr.RoundTrip(req) if err != nil { t.Fatal(err) } @@ -191,8 +192,8 @@ func TestCursorReplyScans(t *testing.T) { t.Errorf("%s: the server was asked for br", p) } } - req, _ := http.NewRequestWithContext(t.Context(), http.MethodPost, srv.URL+"/plain", nil) - resp, err := http.DefaultTransport.RoundTrip(req) + req, _ := http.NewRequestWithContext(t.Context(), http.MethodPost, "http://cursor.test/plain", nil) + resp, err := tr.RoundTrip(req) if err != nil { t.Fatal(err) } diff --git a/internal/proxy/proxy.go b/internal/proxy/proxy.go index 678e14ac..982e30a4 100644 --- a/internal/proxy/proxy.go +++ b/internal/proxy/proxy.go @@ -177,7 +177,10 @@ func newServer(c Config, std IO, l *log.Logger, out io.Writer) (*server, error) if c.Open { l.Printf("open: every host and address, no rules") } - s.egress = &egress{pol: pol, own: own, up: up, log: l, lookup: net.DefaultResolver.LookupNetIP} + s.egress = &egress{ + pol: pol, own: own, up: up, log: l, lookup: net.DefaultResolver.LookupNetIP, + connect: (&net.Dialer{Timeout: 15 * time.Second}).DialContext, + } s.egress.pol.all() maxSize := c.NixCacheMax if maxSize == 0 { @@ -477,6 +480,9 @@ type egress struct { log *log.Logger // the proxy's own log: why a name didn't resolve // lookup resolves a name: net.DefaultResolver.LookupNetIP, which tests replace. lookup func(ctx context.Context, network, host string) ([]netip.Addr, error) + // connect connects to an address the policy allowed (dial): a net.Dialer's, which tests + // replace with one in memory. + connect func(ctx context.Context, network, address string) (net.Conn, error) abandonMu sync.Mutex abandonAt time.Time // when the minute that abandonN counts began @@ -580,9 +586,8 @@ func (e *egress) dial(ctx context.Context, host string, port int) (net.Conn, err if port < 1 || port > 65535 { // the policy allows none of these; never dial one wrapped around return nil, fmt.Errorf("port %d", port) } - d := net.Dialer{Timeout: 15 * time.Second} for _, a := range addrs { - c, err2 := d.DialContext(ctx, "tcp", netip.AddrPortFrom(a, uint16(port)).String()) + c, err2 := e.connect(ctx, "tcp", netip.AddrPortFrom(a, uint16(port)).String()) if err2 == nil { return c, nil } @@ -1109,6 +1114,12 @@ type IO struct { Capture Capturer } +// httpServer is the HTTP server that serves s, its handlers counted by its conns, as run serves it +// and the tests do. +func httpServer(s *server) *http.Server { + return &http.Server{Handler: s.conns.handle(s.handler), ReadHeaderTimeout: 30 * time.Second, MaxHeaderBytes: maxHeaderBytes} +} + // Main runs devvm _proxy with args (its flags): the proxy itself, with -config's file, until the // VM's hostagent is gone. -help prints the flags to std.Stdout. Errors are returned, not printed. func Main(args []string, std IO) error { return run(args, std, lifelineTick) } @@ -1174,7 +1185,7 @@ func serve(c Config, std IO, tick time.Duration) error { if err != nil { return err } - srv := &http.Server{Handler: s.conns.handle(s.handler), ReadHeaderTimeout: 30 * time.Second, MaxHeaderBytes: maxHeaderBytes} + srv := httpServer(s) l.Printf("listening on %s for %s", ln.Addr(), s.vm) // What devvm waits for as it starts the proxy: the address it listens on. if err := daemon.Ready(ln.Addr().String()); err != nil { diff --git a/internal/proxy/proxy_test.go b/internal/proxy/proxy_test.go index 2deac481..ac9bf570 100644 --- a/internal/proxy/proxy_test.go +++ b/internal/proxy/proxy_test.go @@ -28,6 +28,7 @@ import ( "time" "unicode/utf8" + "github.com/devvmhq/devvm/internal/memnet" "github.com/devvmhq/devvm/internal/redact" ) @@ -87,6 +88,94 @@ func listen(t *testing.T, s *server) string { return p.Listener.Addr().String() } +// memProxy is a proxy served in memory, for a test in a synctest bubble (memServe), and the far +// ends it connects to, in far. +type memProxy struct { + t *testing.T + l *memnet.Listener + far *memnet.Network +} + +// memServe serves s in memory, as listen serves it on a port, its connections to the far ends +// going to the returned proxy's far. Once the test ends, s closes as the proxy does. +func memServe(t *testing.T, s *server) memProxy { + t.Helper() + var n memnet.Network + l, err := n.Listen("proxy") + must(t, err) + far := &memnet.Network{} + s.egress.connect = far.DialContext + srv := httpServer(s) + served := make(chan struct{}) + go func() { + defer close(served) + _ = srv.Serve(s.conns.track(l)) + }() + t.Cleanup(func() { + _ = srv.Close() + s.closeConns() + <-served + }) + return memProxy{t: t, l: l, far: far} +} + +// farSink listens at addr among p's far ends, keeping what each connection sends in got, until the +// test ends. +func (p memProxy) farSink(addr string, got io.Writer) { + p.t.Helper() + ln, err := p.far.Listen(addr) + must(p.t, err) + p.t.Cleanup(func() { _ = ln.Close() }) + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + go func() { + defer func() { _ = c.Close() }() + _, _ = io.Copy(got, c) + }() + } + }() +} + +// dial is a connection to the proxy, closed once the test ends. +func (p memProxy) dial() *memnet.Conn { + p.t.Helper() + c, err := p.l.Dial() + must(p.t, err) + p.t.Cleanup(func() { _ = c.Close() }) + return c +} + +// connect sends a CONNECT for hostPort and returns the connection, what reads it after the +// proxy's answer, and the answer's status; refused reads a refusal's body. +func (p memProxy) connect(hostPort string) (*memnet.Conn, *bufio.Reader, int) { + p.t.Helper() + c, r, resp := p.send(hostPort) + _ = resp.Body.Close() + return c, r, resp.StatusCode +} + +func (p memProxy) refused(hostPort string) (int, string) { + p.t.Helper() + _, _, resp := p.send(hostPort) + defer func() { _ = resp.Body.Close() }() + body, _ := io.ReadAll(resp.Body) + return resp.StatusCode, string(body) +} + +func (p memProxy) send(hostPort string) (*memnet.Conn, *bufio.Reader, *http.Response) { + p.t.Helper() + c := p.dial() + _, _ = io.WriteString(c, "CONNECT "+hostPort+" HTTP/1.1\r\nHost: "+hostPort+"\r\n\r\n") + r := bufio.NewReader(c) + resp, err := http.ReadResponse(r, &http.Request{Method: http.MethodConnect}) + must(p.t, err) + return c, r, resp +} + // logs captures s's event log and its own log lines. func logs(s *server) *syncBuffer { b := &syncBuffer{} diff --git a/internal/proxy/secrets_test.go b/internal/proxy/secrets_test.go index 25ea1b0e..d73c98aa 100644 --- a/internal/proxy/secrets_test.go +++ b/internal/proxy/secrets_test.go @@ -25,6 +25,7 @@ import ( "strconv" "strings" "testing" + "testing/synctest" "time" "github.com/devvmhq/devvm/internal/redact" @@ -669,6 +670,70 @@ func TestSecretValueLooksUpInProcess(t *testing.T) { } } +// A lookup that fails is never cached, however it fails: one that hangs is cut at lookupTimeout, +// to the moment on the bubble's clock, one cancelled or failed gives its error, and the next +// request looks up again each time. The request's own end doesn't cancel a lookup under way, and a +// value that's looked up is cached until its time is up, to the moment, then looked up again. +func TestSecretLookupFailuresNeverCached(t *testing.T) { + t.Parallel() + synctest.Test(t, func(t *testing.T) { + s := newSecrets("", nil, quiet()) + b := Binding{Name: "codex", Kind: KindLogin, Agent: "codex"} + var lookups int + var answer func(ctx context.Context) (string, error) + s.lookup = func(ctx context.Context, _ Binding) (redact.Secret, error) { + lookups++ + v, err := answer(ctx) + return redact.NewSecret(v), err + } + hang := func(ctx context.Context) (string, error) { <-ctx.Done(); return "", ctx.Err() } + for _, tc := range []struct { + name string + answer func(ctx context.Context) (string, error) + took time.Duration + }{ + {"hung", hang, lookupTimeout}, + {"cancelled", func(context.Context) (string, error) { return "", context.Canceled }, 0}, + {"failed", func(context.Context) (string, error) { return "", errors.New("locked") }, 0}, + {"empty", func(context.Context) (string, error) { return " \n", nil }, 0}, + } { + answer = tc.answer + before, start := lookups, time.Now() + if v, err := s.value(t.Context(), b); err == nil || !v.Empty() { + t.Errorf("%s: %q, %v", tc.name, v.Reveal(), err) + } + if took := time.Since(start); took != tc.took { + t.Errorf("%s: took %v, want %v", tc.name, took, tc.took) + } + if _, ok := s.values[valueKeyOf(b)]; ok || lookups != before+1 { + t.Errorf("%s: cached %v, %d lookups", tc.name, ok, lookups-before) + } + } + // A request that ends while its lookup is under way: the lookup goes on, and its value is + // cached for the requests after it. + ctx, cancel := context.WithCancel(t.Context()) + answer = func(ctx context.Context) (string, error) { + cancel() + time.Sleep(time.Second) + return "real", ctx.Err() + } + if v, err := s.value(ctx, b); v.Reveal() != "real" || err != nil { + t.Errorf("a lookup whose request ended: %q, %v", v.Reveal(), err) + } + answer = hang + before := lookups + time.Sleep(loginTTL - time.Nanosecond) + if v, err := s.value(t.Context(), b); v.Reveal() != "real" || err != nil || lookups != before { + t.Errorf("within its time: %q, %v, %d lookups", v.Reveal(), err, lookups-before) + } + time.Sleep(time.Nanosecond) + answer = func(context.Context) (string, error) { return "new", nil } + if v, err := s.value(t.Context(), b); v.Reveal() != "new" || err != nil || lookups != before+1 { + t.Errorf("once its time is up: %q, %v, %d lookups", v.Reveal(), err, lookups-before) + } + }) +} + // A secret of yours and an agent's login that share a name are cached apart: neither binding's // host ever gets the other's value. func TestValuesCachedByBinding(t *testing.T) { diff --git a/internal/proxy/splice_test.go b/internal/proxy/splice_test.go index b71e3dcb..8bfc86e4 100644 --- a/internal/proxy/splice_test.go +++ b/internal/proxy/splice_test.go @@ -16,9 +16,11 @@ import ( "sync" "syscall" "testing" + "testing/synctest" "time" "github.com/devvmhq/devvm/internal/leaktest" + "github.com/devvmhq/devvm/internal/memnet" ) // farEnd is the other end of a tunnel in a test. Each connection's first byte says what it does: @@ -182,59 +184,45 @@ func TestConnectLimit(t *testing.T) { if s := testServer(t, Config{}, ""); cap(s.connects) != maxConnects { t.Errorf("a proxy carries %d CONNECTs at once, want %d", cap(s.connects), maxConnects) } - s, _, events, addr := linkProxy(t) - own := &syncBuffer{} - s.log.SetOutput(own) - s.connects = make(chan struct{}, 2) - ln, err := new(net.ListenConfig).Listen(t.Context(), "tcp", "127.0.0.1:0") - must(t, err) - serveFarEnd(t, ln) - target := "127.0.0.1:" + strconv.Itoa(ln.Addr().(*net.TCPAddr).Port) - s.egress.pol = writePolicy(t, target+"\n") - var open []net.Conn - for range 2 { - c, _ := connectTo(t, addr, target) - _, _ = c.Write([]byte("e")) // the far end holds it until the client's end - open = append(open, c) - } - for range 2 { - code, body := roundTrip(t, addr, "CONNECT "+target+" HTTP/1.1\r\nHost: "+target+"\r\n\r\n") - if code != http.StatusServiceUnavailable || !strings.Contains(body, "2 tunnels open already") { - t.Errorf("past the limit: %d %q", code, body) - } - } - if l := events.String(); strings.Count(l, `"event":"blocked"`) != 2 || !strings.Contains(l, `"reason":"2 tunnels open already","refused":true`) { - t.Errorf("the event log: %s", l) - } - if l := own.String(); strings.Count(l, "tunnels open at once") != 1 { - t.Errorf("the proxy's log: %q", l) - } - _ = open[0].Close() - status := func() int { - c, err := new(net.Dialer).DialContext(t.Context(), "tcp", addr) + synctest.Test(t, func(t *testing.T) { + const target = "127.0.0.1:5000" + s := testServer(t, Config{}, target+"\n") + events, own := &syncBuffer{}, &syncBuffer{} + s.events.out = events + s.log.SetOutput(own) + s.connects = make(chan struct{}, 2) + p := memServe(t, s) + ln, err := p.far.Listen(target) must(t, err) - defer func() { _ = c.Close() }() - _ = c.SetDeadline(time.Now().Add(10 * time.Second)) - fmt.Fprintf(c, "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", target, target) - resp, err := http.ReadResponse(bufio.NewReader(c), &http.Request{Method: http.MethodConnect}) - if err != nil { - return 0 + serveFarEnd(t, ln) + var open []net.Conn + for range 2 { + c, _, code := p.connect(target) + if code != http.StatusOK { + t.Fatalf("within the limit: %d", code) + } + _, _ = c.Write([]byte("e")) // the far end holds it until the client's end + open = append(open, c) } - _ = resp.Body.Close() - return resp.StatusCode - } - deadline := time.Now().Add(10 * time.Second) - for { - code := status() - if code == http.StatusOK { - break + for range 2 { + code, body := p.refused(target) + if code != http.StatusServiceUnavailable || !strings.Contains(body, "2 tunnels open already") { + t.Errorf("past the limit: %d %q", code, body) + } } - if time.Now().After(deadline) { - t.Fatalf("a tunnel ended, and a new one still gets %d", code) + if l := events.String(); strings.Count(l, `"event":"blocked"`) != 2 || !strings.Contains(l, `"reason":"2 tunnels open already","refused":true`) { + t.Errorf("the event log: %s", l) } - time.Sleep(20 * time.Millisecond) - } - _ = open[1].Close() + if l := own.String(); strings.Count(l, "tunnels open at once") != 1 { + t.Errorf("the proxy's log: %q", l) + } + // A tunnel that ends makes room at once. + _ = open[0].Close() + synctest.Wait() + if _, _, code := p.connect(target); code != http.StatusOK { + t.Errorf("a tunnel ended, and a new one still gets %d", code) + } + }) } // A tunnel to one of the VM's links. @@ -253,24 +241,26 @@ func TestLinkTunnelSplices(t *testing.T) { // client sent, and returns once the server's bytes end, both connections closed. func TestSpliceEnds(t *testing.T) { t.Parallel() - client, vm := net.Pipe() - server, far := net.Pipe() - done := make(chan struct{}) - go func() { splice(client, server, nil); close(done) }() - go func() { _, _ = vm.Write([]byte("hi")); _ = vm.Close() }() - _ = far.SetDeadline(time.Now().Add(10 * time.Second)) - if b, err := io.ReadAll(far); string(b) != "hi" || err != nil { - t.Errorf("the server read %q, %v", b, err) - } - _ = far.Close() - select { - case <-done: - case <-time.After(10 * time.Second): - t.Fatal("splice goes on after the server's end") - } - if _, err := client.Write([]byte("x")); err == nil { - t.Error("the client's connection is open") - } + synctest.Test(t, func(t *testing.T) { + client, vm := net.Pipe() + server, far := net.Pipe() + done := make(chan struct{}) + go func() { splice(client, server, nil); close(done) }() + go func() { _, _ = vm.Write([]byte("hi")); _ = vm.Close() }() + if b, err := io.ReadAll(far); string(b) != "hi" || err != nil { + t.Errorf("the server read %q, %v", b, err) + } + _ = far.Close() + synctest.Wait() + select { + case <-done: + default: + t.Fatal("splice goes on after the server's end") + } + if _, err := client.Write([]byte("x")); err == nil { + t.Error("the client's connection is open") + } + }) } // hijack answers that the tunnel is open, and the bytes the client sent along with its request @@ -316,7 +306,12 @@ func TestHijack(t *testing.T) { func TestCloseConns(t *testing.T) { t.Parallel() leaktest.Check(t) - ln, err := new(net.ListenConfig).Listen(t.Context(), "tcp", "127.0.0.1:0") + synctest.Test(t, testCloseConns) +} + +func testCloseConns(t *testing.T) { + var n memnet.Network + ln, err := n.Listen("proxy") must(t, err) var cs conns returned := make(chan string, 2) @@ -341,10 +336,9 @@ func TestCloseConns(t *testing.T) { })} go func() { _ = srv.Serve(cs.track(ln)) }() open := func(req string) (net.Conn, *bufio.Reader) { - c, err := new(net.Dialer).DialContext(t.Context(), "tcp", ln.Addr().String()) + c, err := ln.Dial() must(t, err) t.Cleanup(func() { _ = c.Close() }) - _ = c.SetDeadline(time.Now().Add(10 * time.Second)) _, _ = io.WriteString(c, req) r := bufio.NewReader(c) if line, _ := r.ReadString('\n'); !strings.HasPrefix(line, "HTTP/1.1 200") && !strings.HasPrefix(line, "HTTP/1.1 101") { @@ -360,16 +354,20 @@ func TestCloseConns(t *testing.T) { t.Fatalf("a connection ended with the HTTP server: %v", err) } } - if !cs.close(5 * time.Second) { + start := time.Now() + if !cs.close(closeWait) { t.Fatal("close: a handler is still running") } + if took := time.Since(start); took != 0 { + t.Errorf("close took %s with every handler ending at once", took) + } if len(returned) != 2 { t.Errorf("close returned before the handlers: %d of 2 had", len(returned)) } - // Each one's end, or a reset for the byte it hadn't read yet: not the deadline. + // Each one's end. for _, r := range []*bufio.Reader{tr, ur} { - if _, err := io.ReadAll(r); errors.Is(err, os.ErrDeadlineExceeded) { - t.Errorf("a connection goes on after the close: %v", err) + if _, err := io.ReadAll(r); err != nil { + t.Errorf("a connection after the close: %v", err) } } // A request after the close is refused. @@ -381,40 +379,54 @@ func TestCloseConns(t *testing.T) { } } +// A handler that doesn't end with its connection, such as one still dialing, is waited for, but +// for closeWait at most, to the moment on the bubble's clock: close then reports it. +func TestCloseConnsWaitsBounded(t *testing.T) { + t.Parallel() + synctest.Test(t, func(t *testing.T) { + var cs conns + release := make(chan struct{}) + h := cs.handle(func(http.ResponseWriter, *http.Request) { <-release }) + go h(httptest.NewRecorder(), httptest.NewRequestWithContext(t.Context(), http.MethodGet, "http://x.test/", nil)) + synctest.Wait() + start := time.Now() + if cs.close(closeWait) { + t.Error("close: no handler running, though one is") + } + if took := time.Since(start); took != closeWait { + t.Errorf("close waited %s, want %s", took, closeWait) + } + close(release) + }) +} + // A tunnel whose far end says nothing still ends once its client's connection is closed, as the // proxy's close closes it: the far end's connection closes too. func TestSpliceEndsWhenItsClientCloses(t *testing.T) { t.Parallel() leaktest.Check(t) - // TCP's, which close their writing side alone: a pipe's would close whole. - pair := func() (net.Conn, net.Conn) { - ln, err := new(net.ListenConfig).Listen(t.Context(), "tcp", "127.0.0.1:0") - must(t, err) - defer func() { _ = ln.Close() }() - a, err := new(net.Dialer).DialContext(t.Context(), "tcp", ln.Addr().String()) - must(t, err) - b, err := ln.Accept() - must(t, err) - return a, b - } - client, vm := pair() - server, far := pair() - defer func() { _ = vm.Close(); _ = far.Close() }() - done := make(chan struct{}) - go func() { - defer close(done) - splice(client, server, nil) - }() - _ = client.Close() - select { - case <-done: - case <-time.After(10 * time.Second): - t.Fatal("splice goes on after its client's connection closed") - } - _ = far.SetDeadline(time.Now().Add(10 * time.Second)) - if _, err := io.ReadAll(far); errors.Is(err, os.ErrDeadlineExceeded) { - t.Error("the far end's connection is open") - } + synctest.Test(t, func(t *testing.T) { + // memnet's, which close their writing side alone, as TCP's do: a net.Pipe's would close + // whole. + client, vm := memnet.Pipe() + server, far := memnet.Pipe() + defer func() { _ = vm.Close(); _ = far.Close() }() + done := make(chan struct{}) + go func() { + defer close(done) + splice(client, server, nil) + }() + _ = client.Close() + synctest.Wait() + select { + case <-done: + default: + t.Fatal("splice goes on after its client's connection closed") + } + if _, err := io.ReadAll(far); err != nil { + t.Errorf("the far end's connection: %v", err) + } + }) } // earlyServer is a tunnel's far end that has answered and closed while its client still sends: diff --git a/internal/proxy/transparent_test.go b/internal/proxy/transparent_test.go index 4f44722b..faef2b6b 100644 --- a/internal/proxy/transparent_test.go +++ b/internal/proxy/transparent_test.go @@ -19,8 +19,8 @@ import ( "slices" "strconv" "strings" - "syscall" "testing" + "testing/synctest" "time" "github.com/devvmhq/devvm/internal/redact" @@ -507,47 +507,54 @@ func TestHostsNotASCII(t *testing.T) { } } -// A CONNECT tunnel's ClientHello, once it starts, must arrive whole within the deadline, in a record -// no longer than TLS's: one that stops, or claims 64 KiB, is refused and closed. +// helloTunnel is a proxy in memory whose policy allows its one far end, 127.0.0.1:5000, which +// keeps what it gets in got, and its event log: for a tunnel's ClientHello, in a synctest bubble. +func helloTunnel(t *testing.T) (p memProxy, ev, got *syncBuffer) { + t.Helper() + const far = "127.0.0.1:5000" + s := testServer(t, Config{}, far+"\n") + ev, got = logs(s), &syncBuffer{} + p = memServe(t, s) + p.farSink(far, got) + return p, ev, got +} + +// refusals is how many tunnels ev refused for a broken ClientHello. +func refusals(ev *syncBuffer) int { + return len(slices.DeleteFunc(eventsOf(ev), func(e Event) bool { return e.Reason != reasonHelloBroken })) +} + +// A CONNECT tunnel's ClientHello, once it starts, must arrive whole within helloTimeout, to the +// moment on the bubble's clock, in a record no longer than TLS's: one that stops is refused and +// closed at the deadline, and one that claims 64 KiB at once. func TestTunnelHelloDeadline(t *testing.T) { t.Parallel() - ln, err := new(net.ListenConfig).Listen(t.Context(), "tcp", "127.0.0.1:0") - must(t, err) - t.Cleanup(func() { _ = ln.Close() }) - go func() { - for { - c, err := ln.Accept() - if err != nil { - return + synctest.Test(t, func(t *testing.T) { + p, ev, got := helloTunnel(t) + for _, tc := range []struct { + first []byte + took time.Duration + }{ + {[]byte{0x16, 3, 1, 0, 0xff}, helloTimeout}, + {[]byte{0x16, 3, 1, 0xff, 0xff}, 0}, + } { + c, r, code := p.connect("127.0.0.1:5000") + if code != http.StatusOK { + t.Fatalf("CONNECT: %d", code) + } + _, _ = c.Write(tc.first) + start := time.Now() + if _, err := r.ReadByte(); !errors.Is(err, io.EOF) || time.Since(start) != tc.took { + t.Errorf("% x: %v after %s, want EOF after %s", tc.first, err, time.Since(start), tc.took) } - go func() { _, _ = io.Copy(io.Discard, c) }() } - }() - port := portOf(t, ln.Addr()) - s, addr, ev := transparentServer(t, Config{}, fmt.Sprintf("localhost:%d\n127.0.0.1:%d\n", port, port)) - s.helloWait = 300 * time.Millisecond - for _, first := range [][]byte{{0x16, 3, 1, 0, 0xff}, {0x16, 3, 1, 0xff, 0xff}} { - c, err := new(net.Dialer).DialContext(t.Context(), "tcp", addr) - must(t, err) - fmt.Fprintf(c, "CONNECT localhost:%d HTTP/1.1\r\nHost: localhost:%d\r\n\r\n", port, port) - r := bufio.NewReader(c) - resp, err := http.ReadResponse(r, &http.Request{Method: http.MethodConnect}) - must(t, err) - _ = resp.Body.Close() - if resp.StatusCode != http.StatusOK { - t.Fatalf("CONNECT: %d", resp.StatusCode) + if n := refusals(ev); n != 2 { + t.Errorf("%d refusals: %s", n, ev.String()) } - _, _ = c.Write(first) - start := time.Now() - _ = c.SetReadDeadline(time.Now().Add(5 * time.Second)) - if _, err := r.ReadByte(); !errors.Is(err, io.EOF) || time.Since(start) > 3*time.Second { - t.Errorf("% x: %v after %s", first, err, time.Since(start)) + if got.String() != "" { + t.Errorf("the far end got %q", got.String()) } - _ = c.Close() - } - if n := len(slices.DeleteFunc(eventsOf(ev), func(e Event) bool { return e.Reason != reasonHelloBroken })); n != 2 { - t.Errorf("%d refusals: %s", n, ev.String()) - } + }) } // A tunnel whose first byte starts a TLS record is TLS from then on: one that sends that byte alone @@ -555,54 +562,42 @@ func TestTunnelHelloDeadline(t *testing.T) { // whose record header isn't TLS's version, and the far end gets none of their bytes. func TestTunnelHelloStall(t *testing.T) { t.Parallel() - ln, err := new(net.ListenConfig).Listen(t.Context(), "tcp", "127.0.0.1:0") - must(t, err) - t.Cleanup(func() { _ = ln.Close() }) - got := &syncBuffer{} - go func() { - for { - c, err := ln.Accept() - if err != nil { - return + synctest.Test(t, func(t *testing.T) { + p, ev, got := helloTunnel(t) + for _, c := range []struct { + first, then []byte + wait time.Duration + }{ + {[]byte{0x16}, rawHello("other.test")[1:], helloTimeout + time.Nanosecond}, + {[]byte{0x16, 2, 1, 0, 5}, []byte("hello"), 0}, + } { + conn, r, _ := p.connect("127.0.0.1:5000") + _, _ = conn.Write(c.first) + time.Sleep(c.wait) + _, _ = conn.Write(c.then) + if _, err := r.ReadByte(); !errors.Is(err, io.EOF) { + t.Errorf("% x: not closed: %v", c.first, err) } - go func() { _, _ = io.Copy(got, c) }() } - }() - port := portOf(t, ln.Addr()) - s, addr, ev := transparentServer(t, Config{}, fmt.Sprintf("localhost:%d\n127.0.0.1:%d\n", port, port)) - s.helloWait = 200 * time.Millisecond - for _, c := range []struct { - first, then []byte - wait time.Duration - }{ - {[]byte{0x16}, rawHello("other.test")[1:], 500 * time.Millisecond}, - {[]byte{0x16, 2, 1, 0, 5}, []byte("hello"), 0}, - } { - conn, err := new(net.Dialer).DialContext(t.Context(), "tcp", addr) - must(t, err) - fmt.Fprintf(conn, "CONNECT localhost:%d HTTP/1.1\r\nHost: localhost:%d\r\n\r\n", port, port) - r := bufio.NewReader(conn) - resp, err := http.ReadResponse(r, &http.Request{Method: http.MethodConnect}) - must(t, err) - _ = resp.Body.Close() - _, _ = conn.Write(c.first) - time.Sleep(c.wait) - _, _ = conn.Write(c.then) - _ = conn.SetReadDeadline(time.Now().Add(3 * time.Second)) - // Closed either way: Linux resets a connection closed with bytes - // unread, as the proxy leaves what follows a broken hello. - if _, err := r.ReadByte(); !errors.Is(err, io.EOF) && !errors.Is(err, syscall.ECONNRESET) { - t.Errorf("% x: not closed: %v", c.first, err) + synctest.Wait() + if got.String() != "" { + t.Errorf("the far end got %q", got.String()) } - _ = conn.Close() - } - time.Sleep(100 * time.Millisecond) - if got.String() != "" { - t.Errorf("the far end got %q", got.String()) - } - if n := len(slices.DeleteFunc(eventsOf(ev), func(e Event) bool { return e.Reason != reasonHelloBroken })); n != 2 { - t.Errorf("%d refusals: %s", n, ev.String()) - } + if n := refusals(ev); n != 2 { + t.Errorf("%d refusals: %s", n, ev.String()) + } + // A ClientHello whose first byte comes alone and the rest a moment before the deadline + // goes on, whole. + conn, _, _ := p.connect("127.0.0.1:5000") + whole := rawHello("") + _, _ = conn.Write(whole[:1]) + time.Sleep(helloTimeout - time.Nanosecond) + _, _ = conn.Write(whole[1:]) + synctest.Wait() + if got.String() != string(whole) { + t.Errorf("a ClientHello whole a moment before the deadline: the far end got %d bytes of %d", len(got.String()), len(whole)) + } + }) } // An address's tunnel may have no server name, but only in a ClientHello that parsed: one split @@ -610,60 +605,31 @@ func TestTunnelHelloStall(t *testing.T) { // while a whole one without a name goes on. func TestTunnelAddressSplitHello(t *testing.T) { t.Parallel() - ln, err := new(net.ListenConfig).Listen(t.Context(), "tcp", "127.0.0.1:0") - must(t, err) - t.Cleanup(func() { _ = ln.Close() }) - got := &syncBuffer{} - go func() { - for { - c, err := ln.Accept() - if err != nil { - return - } - go func() { _, _ = io.Copy(got, c) }() + synctest.Test(t, func(t *testing.T) { + p, ev, got := helloTunnel(t) + hs := rawHello("other.test")[5:] // the handshake message, without its record header + record := func(b []byte) []byte { return append([]byte{0x16, 3, 1, byte(len(b) >> 8), byte(len(b))}, b...) } //nolint:gosec // G115: a test's few bytes + tunnelWith := func(first []byte) { + t.Helper() + c, r, _ := p.connect("127.0.0.1:5000") + _, _ = c.Write(first) + _ = c.CloseWrite() + _, _ = io.ReadAll(r) + synctest.Wait() } - }() - port := portOf(t, ln.Addr()) - _, addr, ev := transparentServer(t, Config{}, fmt.Sprintf("127.0.0.1:%d\n", port)) - hs := rawHello("other.test")[5:] // the handshake message, without its record header - record := func(b []byte) []byte { return append([]byte{0x16, 3, 1, byte(len(b) >> 8), byte(len(b))}, b...) } //nolint:gosec // G115: a test's few bytes - tunnelWith := func(first []byte) { - t.Helper() - c, err := new(net.Dialer).DialContext(t.Context(), "tcp", addr) - must(t, err) - defer func() { _ = c.Close() }() - fmt.Fprintf(c, "CONNECT 127.0.0.1:%d HTTP/1.1\r\nHost: 127.0.0.1:%d\r\n\r\n", port, port) - r := bufio.NewReader(c) - resp, err := http.ReadResponse(r, &http.Request{Method: http.MethodConnect}) - must(t, err) - _ = resp.Body.Close() - _, _ = c.Write(first) - if cw, ok := c.(interface{ CloseWrite() error }); ok { - _ = cw.CloseWrite() - } - _ = c.SetReadDeadline(time.Now().Add(3 * time.Second)) - _, _ = io.ReadAll(r) - } - tunnelWith(append(record(hs[:10]), record(hs[10:])...)) - time.Sleep(100 * time.Millisecond) - if got.String() != "" { - t.Errorf("a split ClientHello reached the far end: % x", got.String()) - } - e := waitEvent(t, ev, func(e Event) bool { return e.Reason == reasonHelloBroken }) - if !e.Refused || e.Host != "127.0.0.1" { - t.Errorf("event %+v", e) - } - whole := rawHello("") - tunnelWith(whole) - for range 50 { + tunnelWith(append(record(hs[:10]), record(hs[10:])...)) if got.String() != "" { - break + t.Errorf("a split ClientHello reached the far end: % x", got.String()) } - time.Sleep(20 * time.Millisecond) - } - if got.String() != string(whole) { - t.Errorf("a whole ClientHello without a name didn't reach the far end: %d bytes", len(got.String())) - } + if es := slices.DeleteFunc(eventsOf(ev), func(e Event) bool { return e.Reason != reasonHelloBroken }); len(es) != 1 || !es[0].Refused || es[0].Host != "127.0.0.1" { + t.Errorf("events %+v", es) + } + whole := rawHello("") + tunnelWith(whole) + if got.String() != string(whole) { + t.Errorf("a whole ClientHello without a name didn't reach the far end: %d bytes", len(got.String())) + } + }) } // A record header that claims more than a TLS record holds is never read past. diff --git a/internal/structure/rules_test.go b/internal/structure/rules_test.go index ca81f33e..60759f9a 100644 --- a/internal/structure/rules_test.go +++ b/internal/structure/rules_test.go @@ -205,16 +205,30 @@ func layerCases() []ruleCase { { name: "leaktest outside tests", files: map[string]string{"internal/vm/a.go": imports("vm", "internal/leaktest")}, - want: &want{ruleLayers, "stubtest and leaktest are for tests"}, + want: &want{ruleLayers, "stubtest, leaktest and memnet are for tests"}, }, { name: "leaktest in a test", files: map[string]string{"internal/proxy/a_test.go": imports("proxy", "internal/leaktest")}, }, + { + name: "memnet outside tests", + files: map[string]string{"internal/vmssh/a.go": imports("vmssh", "internal/memnet")}, + want: &want{ruleLayers, "stubtest, leaktest and memnet are for tests"}, + }, + { + name: "memnet in a test", + files: map[string]string{"internal/proxy/a_test.go": imports("proxy", "internal/memnet")}, + }, + { + name: "memnet importing devvm's", + files: map[string]string{"internal/memnet/a.go": imports("memnet", "internal/leaktest")}, + want: &want{ruleLayers, "leaves import nothing of devvm's"}, + }, { name: "stubtest outside tests", files: map[string]string{"internal/vm/a.go": imports("vm", "internal/stubtest")}, - want: &want{ruleLayers, "stubtest and leaktest are for tests"}, + want: &want{ruleLayers, "stubtest, leaktest and memnet are for tests"}, }, { name: "stubtest in a test", diff --git a/internal/structure/structure_test.go b/internal/structure/structure_test.go index acadb3f6..5f844505 100644 --- a/internal/structure/structure_test.go +++ b/internal/structure/structure_test.go @@ -123,9 +123,9 @@ func devvm() rules { to: []string{"internal/upgrade/upgradetest"}, }, { - name: "stubtest and leaktest are for tests", - from: []string{"..."}, exceptFrom: []string{"internal/stubtest/...", "internal/leaktest"}, - to: []string{"internal/stubtest/...", "internal/leaktest"}, + name: "stubtest, leaktest and memnet are for tests", + from: []string{"..."}, exceptFrom: []string{"internal/stubtest/...", "internal/leaktest", "internal/memnet"}, + to: []string{"internal/stubtest/...", "internal/leaktest", "internal/memnet"}, }, { name: "internal/stubtest imports only internal/msg and its own", @@ -149,7 +149,7 @@ func devvm() rules { from: []string{ "assets", "locales", "packaging", "internal/platform", "internal/msg/gen", "internal/testbuild", "internal/hostgit", "internal/shell", "internal/vmname", "internal/daemon", "internal/fetch", "internal/jsonc", - "internal/redact", "internal/agents", "internal/safefile", "internal/leaktest", + "internal/redact", "internal/agents", "internal/safefile", "internal/leaktest", "internal/memnet", }, to: []string{"..."}, }, @@ -340,6 +340,8 @@ func devvmGoroutineSites() map[string]string { "internal/desktop/relay.go: Relay.dialVM": detached + "the VM's handshake, which ends once dialVM closes the VM's connection at a timeout or ctx's end, its result in a buffered channel", "internal/desktop/relay.go: Relay.carry": detached + "the closer, which carry's deferred cancel ends, and the copy to the viewer, which ends once the closer closes both connections", "internal/gitprotect/repos.go: scanAll": "scanAll's wg.Wait", + "internal/memnet/memnet.go: Conn.wake": detached + "a deadline's AfterFunc, which only wakes the connection's waiting ends, and which a later deadline or its close stops", + "internal/memnet/memnet.go: Listener.SetDeadline": detached + "a deadline's AfterFunc, which only wakes a waiting Accept, and which a later deadline or the listener's close stops", "internal/platform/pin_linux.go: WaitExit": "the process's end, or WaitExit's stop, which closes the pidfd its wait in Go's poller is on", "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", @@ -367,7 +369,7 @@ func devvmGoroutineSites() map[string]string { "internal/vmssh/links.go: Links.newTargetMaster": "the master's ready, closed once it's up or has failed", "internal/vmssh/loopback.go: SSH.forwardLoopback": "LoopbackForward.Close, through its wg; the listeners' closer ends with the forward's cancel", "internal/vmssh/loopback.go: LoopbackForward.serve": "serve's conns.Wait", - "internal/vmssh/relay.go: pipeSSHFor": detached + "the client's copy to the VM, which ends once the relay closes the client's connection; the AfterFunc that closes it at ctx's end, which the relay's deferred stop ends", + "internal/vmssh/relay.go: sshRelay.carry": detached + "the client's copy to the VM, which ends once the relay closes the client's connection; the AfterFunc that closes it at ctx's end, which the relay's deferred stop ends", "internal/vmssh/relay.go: newGraceTimer": detached + "the grace's AfterFunc, which cancels the relay once the grace runs out; stopped as the relay ends, it never runs after it", } } diff --git a/internal/vmssh/forward_test.go b/internal/vmssh/forward_test.go index 9d801453..727dde91 100644 --- a/internal/vmssh/forward_test.go +++ b/internal/vmssh/forward_test.go @@ -19,11 +19,13 @@ import ( "sync/atomic" "syscall" "testing" + "testing/synctest" "time" "github.com/devvmhq/devvm/internal/backend" "github.com/devvmhq/devvm/internal/daemon" "github.com/devvmhq/devvm/internal/leaktest" + "github.com/devvmhq/devvm/internal/memnet" "github.com/devvmhq/devvm/internal/paths" "github.com/devvmhq/devvm/internal/platform" "github.com/devvmhq/devvm/internal/state" @@ -139,17 +141,29 @@ func reach(t *testing.T, addr string) string { return strings.TrimSpace(line) } -// eventually waits for addr to answer want. -func eventually(t *testing.T, addr, want string) { - t.Helper() - var got string - for range 100 { - if got = reach(t, addr); got == want { - return - } - time.Sleep(20 * time.Millisecond) +// memLoopback is the host's loopback in memory, for a forwarder in a +// synctest bubble: its Listen (listen), and connections to it (reach). +type memLoopback struct{ memnet.Network } + +func (m *memLoopback) listen(_ context.Context, addr string) (net.Listener, error) { + l, err := m.Listen(addr) + if err != nil { + return nil, err } - t.Errorf("%s: %q, want %q", addr, got, want) + return l, nil +} + +// reach connects to addr once the bubble's goroutines have done what +// they can, and returns what comes back, "refused" for nothing there. +func (m *memLoopback) reach(addr string) string { + synctest.Wait() + c, err := m.Dial(addr) + if err != nil { + return "refused" + } + defer func() { _ = c.Close() }() + line, _ := bufio.NewReader(c).ReadString('\n') + return strings.TrimSpace(line) } type lockedWriter struct { @@ -176,74 +190,90 @@ func echo(_ context.Context, conn net.Conn, h string, p int) { // longer runs as it did. func TestForwarder(t *testing.T) { leaktest.Check(t) // nothing of the forwarder's runs on once it has ended - ports := freePorts(t, 5) - open, v6only, reserved, hosts, gone := ports[0], ports[1], ports[2], ports[3], ports[4] - // The host's own program, on every address. - host, err := net.Listen("tcp", ":"+strconv.Itoa(hosts)) //nolint:noctx // the test's - if err != nil { - t.Fatal(err) - } - defer func() { _ = host.Close() }() - var alive atomic.Bool - alive.Store(true) - vm := &fakeVM{ready: make(chan struct{}, 4)} - var log bytes.Buffer - var logMu sync.Mutex - f := &Forwarder{ - VM: "devvm-f", Tick: 10 * time.Millisecond, Every: 10 * time.Millisecond, Log: lockedWriter{&logMu, &log}, - Alive: func(context.Context) bool { return alive.Load() }, - Reserved: func() (map[int]bool, error) { return map[int]bool{reserved: true}, nil }, - Watch: vm.watch, Relay: echo, Listen: platform.ListenLoopback, - } - ctx, cancel := context.WithCancel(t.Context()) - done := make(chan error, 1) - go func() { done <- f.Run(ctx) }() - <-vm.ready - vm.report(t, - procLine("0100007F", open), procLine("00000000000000000000000001000000", v6only), - procLine("00000000", reserved), procLine("00000000", hosts), procLine("00000000", gone), - procLine("00000000", 80), procLine("0100A8C0", 9999), - ) - at := func(p int) string { return net.JoinHostPort("127.0.0.1", strconv.Itoa(p)) } - eventually(t, at(open), "to "+at(open)) - eventually(t, net.JoinHostPort("::1", strconv.Itoa(open)), "to "+at(open)) - eventually(t, at(v6only), "to "+net.JoinHostPort("::1", strconv.Itoa(v6only))) - eventually(t, at(gone), "to "+at(gone)) - if got := reach(t, at(reserved)); got != "refused" { - t.Errorf("reserved port: %q", got) - } - if got := reach(t, at(hosts)); strings.HasPrefix(got, "to ") { - t.Errorf("the host's port taken: %q", got) - } - // The VM's listener goes: so does its forward. - vm.report(t, procLine("0100007F", open)) - eventually(t, at(gone), "refused") - eventually(t, at(open), "to "+at(open)) - // The connection ends: every forward goes, then it's made again. - vm.drop() - <-vm.ready - eventually(t, at(open), "refused") - vm.report(t, procLine("00000000", open)) - eventually(t, at(open), "to "+at(open)) - // The VM no longer runs as it did (started again): it ends. - alive.Store(false) - select { - case err := <-done: - if err != nil { - t.Error(err) + synctest.Test(t, func(t *testing.T) { + const open, v6only, reserved, hosts, gone = 5000, 5001, 5002, 5003, 5004 + const every, tick = 10 * time.Second, 2 * time.Second + lo := &memLoopback{} + // The host's own program, on both addresses, which accepts nothing. + for _, a := range []string{"127.0.0.1", "::1"} { + if _, err := lo.Listen(net.JoinHostPort(a, strconv.Itoa(hosts))); err != nil { + t.Fatal(err) + } } - case <-time.After(5 * time.Second): - t.Error("still running with its VM gone") - } - cancel() - eventually(t, at(open), "refused") - logMu.Lock() - defer logMu.Unlock() - for _, want := range []string{"forwarding devvm-f's ports", fmt.Sprintf("port %d: not forwarded", hosts), fmt.Sprintf("port %d: forwarded", open), "devvm-f stopped"} { - if !strings.Contains(log.String(), want) { - t.Errorf("log lacks %q:\n%s", want, log.String()) + var alive atomic.Bool + alive.Store(true) + vm := &fakeVM{ready: make(chan struct{}, 4)} + var log bytes.Buffer + var logMu sync.Mutex + f := &Forwarder{ + VM: "devvm-f", Tick: tick, Every: every, Log: lockedWriter{&logMu, &log}, + Alive: func(context.Context) bool { return alive.Load() }, + Reserved: func() (map[int]bool, error) { return map[int]bool{reserved: true}, nil }, + Watch: vm.watch, Relay: echo, Listen: lo.listen, } - } + ctx, cancel := context.WithCancel(t.Context()) + done := make(chan error, 1) + go func() { done <- f.Run(ctx) }() + <-vm.ready + vm.report(t, + procLine("0100007F", open), procLine("00000000000000000000000001000000", v6only), + procLine("00000000", reserved), procLine("00000000", hosts), procLine("00000000", gone), + procLine("00000000", 80), procLine("0100A8C0", 9999), + ) + at := func(p int) string { return net.JoinHostPort("127.0.0.1", strconv.Itoa(p)) } + reach := func(addr, want string) { + t.Helper() + if got := lo.reach(addr); got != want { + t.Errorf("%s: %q, want %q", addr, got, want) + } + } + reach(at(open), "to "+at(open)) + reach(net.JoinHostPort("::1", strconv.Itoa(open)), "to "+at(open)) + reach(at(v6only), "to "+net.JoinHostPort("::1", strconv.Itoa(v6only))) + reach(at(gone), "to "+at(gone)) + reach(at(reserved), "refused") + reach(at(80), "refused") + // The VM's listener goes: so does its forward. + vm.report(t, procLine("0100007F", open)) + reach(at(gone), "refused") + reach(at(open), "to "+at(open)) + // The connection ends: every forward goes, then, a tick later, + // it's made again. + vm.drop() + reach(at(open), "refused") + time.Sleep(tick) + <-vm.ready + vm.report(t, procLine("00000000", open)) + reach(at(open), "to "+at(open)) + // The VM no longer runs as it did (started again): it ends within + // Every. + alive.Store(false) + time.Sleep(every) + synctest.Wait() + select { + case err := <-done: + if err != nil { + t.Error(err) + } + default: + t.Error("still running with its VM gone") + } + cancel() + reach(at(open), "refused") + logMu.Lock() + defer logMu.Unlock() + for _, want := range []string{"forwarding devvm-f's ports", fmt.Sprintf("port %d: not forwarded", hosts), fmt.Sprintf("port %d: forwarded", open), "devvm-f stopped"} { + if !strings.Contains(log.String(), want) { + t.Errorf("log lacks %q:\n%s", want, log.String()) + } + } + // Only the host's program is left listening. + for _, l := range []int{open, v6only, gone} { + if lo.Listening(at(l)) || lo.Listening(net.JoinHostPort("::1", strconv.Itoa(l))) { + t.Errorf("port %d: still listened on", l) + } + } + }) } // A VM that isn't running gets no forwarder; one whose connection ends @@ -253,95 +283,105 @@ func TestForwarderAliveOnEnd(t *testing.T) { if err := f.Run(t.Context()); err == nil { t.Error("ran for a VM that isn't running") } - var calls atomic.Int32 - vm := &fakeVM{ready: make(chan struct{}, 4)} - f = &Forwarder{ - VM: "devvm-f", Tick: time.Hour, Every: time.Hour, Log: io.Discard, - Alive: func(context.Context) bool { return calls.Add(1) <= 2 }, - Reserved: func() (map[int]bool, error) { return nil, nil }, - Watch: vm.watch, Listen: platform.ListenLoopback, - } - done := make(chan error, 1) - go func() { done <- f.Run(t.Context()) }() - <-vm.ready - vm.drop() - select { - case err := <-done: - if err != nil { - t.Error(err) + synctest.Test(t, func(t *testing.T) { + var calls atomic.Int32 + vm := &fakeVM{ready: make(chan struct{}, 4)} + f := &Forwarder{ + VM: "devvm-f", Tick: time.Hour, Every: time.Hour, Log: io.Discard, + Alive: func(context.Context) bool { return calls.Add(1) <= 2 }, + Reserved: func() (map[int]bool, error) { return nil, nil }, + Watch: vm.watch, Listen: (&memLoopback{}).listen, } - case <-time.After(5 * time.Second): - t.Error("still running with its connection ended and its VM gone") - } + done := make(chan error, 1) + go func() { done <- f.Run(t.Context()) }() + <-vm.ready + vm.drop() + synctest.Wait() + select { + case err := <-done: + if err != nil { + t.Error(err) + } + default: + t.Error("still running with its connection ended and its VM gone") + } + }) } // With Only (listed ports), the forwarder forwards those alone, below // 1024 too, and nothing else the VM listens on. func TestForwarderOnly(t *testing.T) { - ports := freePorts(t, 3) - listed, other, reserved := ports[0], ports[1], ports[2] - vm := &fakeVM{ready: make(chan struct{}, 4)} - f := &Forwarder{ - VM: "devvm-f", Tick: 10 * time.Millisecond, Every: time.Hour, Log: io.Discard, - Only: []backend.PortRange{{From: listed, To: listed}, {From: reserved, To: reserved}, {From: 80, To: 80}}, - Alive: func(context.Context) bool { return true }, - Reserved: func() (map[int]bool, error) { return map[int]bool{reserved: true}, nil }, - Watch: vm.watch, Relay: echo, Listen: platform.ListenLoopback, - ports: map[int]*forward{}, skipped: map[int]failure{}, - } - if !f.wanted(80) || f.wanted(other) || !f.wanted(listed) { - t.Error("wanted: not the listed ports alone") - } - ctx, cancel := context.WithCancel(t.Context()) - defer cancel() - go func() { _ = f.Run(ctx) }() - <-vm.ready - vm.report(t, procLine("00000000", listed), procLine("00000000", other), procLine("00000000", reserved)) - at := func(p int) string { return net.JoinHostPort("127.0.0.1", strconv.Itoa(p)) } - eventually(t, at(listed), "to "+at(listed)) - if got := reach(t, at(other)); got != "refused" { - t.Errorf("an unlisted port: %q", got) - } - if got := reach(t, at(reserved)); got != "refused" { - t.Errorf("a listed port devvm reserves: %q", got) - } + synctest.Test(t, func(t *testing.T) { + const listed, other, reserved = 5000, 5001, 5002 + lo := &memLoopback{} + vm := &fakeVM{ready: make(chan struct{}, 4)} + f := &Forwarder{ + VM: "devvm-f", Tick: time.Second, Every: time.Hour, Log: io.Discard, + Only: []backend.PortRange{{From: listed, To: listed}, {From: reserved, To: reserved}, {From: 80, To: 80}}, + Alive: func(context.Context) bool { return true }, + Reserved: func() (map[int]bool, error) { return map[int]bool{reserved: true}, nil }, + Watch: vm.watch, Relay: echo, Listen: lo.listen, + ports: map[int]*forward{}, skipped: map[int]failure{}, + } + if !f.wanted(80) || f.wanted(other) || !f.wanted(listed) { + t.Error("wanted: not the listed ports alone") + } + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + go func() { _ = f.Run(ctx) }() + <-vm.ready + vm.report(t, procLine("00000000", listed), procLine("00000000", other), procLine("00000000", reserved), procLine("00000000", 80)) + at := func(p int) string { return net.JoinHostPort("127.0.0.1", strconv.Itoa(p)) } + for p, want := range map[int]string{listed: "to " + at(listed), 80: "to " + at(80), other: "refused", reserved: "refused"} { + if got := lo.reach(at(p)); got != want { + t.Errorf("port %d: %q, want %q", p, got, want) + } + } + }) } -// A VM that reports faster than Gap waits: reports are applied Gap apart. +// A VM that reports faster than Gap waits: reports are applied Gap apart, +// to the moment, on the bubble's clock. func TestForwarderGap(t *testing.T) { - vm := &fakeVM{ready: make(chan struct{}, 4)} - var mu sync.Mutex - var applied []time.Time - gap := 100 * time.Millisecond - f := &Forwarder{ - VM: "devvm-f", Tick: 10 * time.Millisecond, Every: time.Hour, Gap: gap, Log: io.Discard, - Alive: func(context.Context) bool { return true }, - Reserved: func() (map[int]bool, error) { - mu.Lock() - defer mu.Unlock() - applied = append(applied, time.Now()) - return nil, nil - }, - Watch: vm.watch, Listen: platform.ListenLoopback, - } - ctx, cancel := context.WithCancel(t.Context()) - defer cancel() - go func() { _ = f.Run(ctx) }() - <-vm.ready - for range 5 { - vm.report(t) - } - time.Sleep(gap) - mu.Lock() - defer mu.Unlock() - if len(applied) < 4 { - t.Fatalf("%d reports applied", len(applied)) - } - for i := 1; i < len(applied); i++ { - if d := applied[i].Sub(applied[i-1]); d < gap-10*time.Millisecond { - t.Errorf("reports %d and %d applied %v apart", i-1, i, d) + synctest.Test(t, func(t *testing.T) { + vm := &fakeVM{ready: make(chan struct{}, 4)} + var mu sync.Mutex + var applied []time.Time + const gap = 500 * time.Millisecond + f := &Forwarder{ + VM: "devvm-f", Tick: time.Second, Every: time.Hour, Gap: gap, Log: io.Discard, + Alive: func(context.Context) bool { return true }, + Reserved: func() (map[int]bool, error) { + mu.Lock() + defer mu.Unlock() + applied = append(applied, time.Now()) + return nil, nil + }, + Watch: vm.watch, Listen: (&memLoopback{}).listen, } - } + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + go func() { _ = f.Run(ctx) }() + <-vm.ready + start := time.Now() + for range 5 { + vm.report(t) + } + time.Sleep(gap) + synctest.Wait() + mu.Lock() + defer mu.Unlock() + if len(applied) != 5 { + t.Fatalf("%d reports applied", len(applied)) + } + for i, at := range applied { + // The first at once; each after it, as the VM sent them all at + // once, Gap after the one before. + if want := start.Add(time.Duration(i) * gap); !at.Equal(want) { + t.Errorf("report %d applied at %v, want %v", i, at.Sub(start), want.Sub(start)) + } + } + }) } // What the VM makes the forwarder log is limited: a burst, then one write @@ -426,77 +466,95 @@ func TestForwarderReservedLater(t *testing.T) { // quiet. The forwarder notes it forwards nothing when it starts, then each // change. func TestForwarderGivesUpSilently(t *testing.T) { - p := freePorts(t, 1)[0] - vm := &fakeVM{ready: make(chan struct{}, 4)} - var mu sync.Mutex - reserved := map[int]bool{} - var notes [][]int - f := &Forwarder{ - VM: "devvm-f", Tick: 10 * time.Millisecond, Every: 20 * time.Millisecond, Log: io.Discard, - Alive: func(context.Context) bool { return true }, - Reserved: func() (map[int]bool, error) { - mu.Lock() - defer mu.Unlock() - return maps.Clone(reserved), nil - }, - Note: func(ports []int, _ failedPorts) { - mu.Lock() - defer mu.Unlock() - notes = append(notes, ports) - }, - Watch: vm.watch, Relay: echo, Listen: platform.ListenLoopback, - } - ctx, cancel := context.WithCancel(t.Context()) - defer cancel() - go func() { _ = f.Run(ctx) }() - <-vm.ready - vm.report(t, procLine("00000000", p)) - at := net.JoinHostPort("127.0.0.1", strconv.Itoa(p)) - eventually(t, at, "to "+at) - // Another VM now lists it; the VM says nothing more. - mu.Lock() - reserved[p] = true - mu.Unlock() - eventually(t, at, "refused") - mu.Lock() - defer mu.Unlock() - if !slices.EqualFunc(notes, [][]int{nil, {p}, {}}, slices.Equal) { - t.Errorf("noted %v", notes) - } + synctest.Test(t, func(t *testing.T) { + const p, every = 5000, 10 * time.Second + lo := &memLoopback{} + vm := &fakeVM{ready: make(chan struct{}, 4)} + var mu sync.Mutex + reserved := map[int]bool{} + var notes [][]int + f := &Forwarder{ + VM: "devvm-f", Tick: time.Second, Every: every, Log: io.Discard, + Alive: func(context.Context) bool { return true }, + Reserved: func() (map[int]bool, error) { + mu.Lock() + defer mu.Unlock() + return maps.Clone(reserved), nil + }, + Note: func(ports []int, _ failedPorts) { + mu.Lock() + defer mu.Unlock() + notes = append(notes, ports) + }, + Watch: vm.watch, Relay: echo, Listen: lo.listen, + } + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + go func() { _ = f.Run(ctx) }() + <-vm.ready + vm.report(t, procLine("00000000", p)) + at := net.JoinHostPort("127.0.0.1", strconv.Itoa(p)) + if got := lo.reach(at); got != "to "+at { + t.Fatalf("forwarded: %q", got) + } + // Another VM now lists it; the VM says nothing more. It goes at the + // next recheck, Every at most. + mu.Lock() + reserved[p] = true + mu.Unlock() + time.Sleep(every) + if got := lo.reach(at); got != "refused" { + t.Errorf("a reserved port a recheck on: %q", got) + } + mu.Lock() + defer mu.Unlock() + if !slices.EqualFunc(notes, [][]int{nil, {p}, {}}, slices.Equal) { + t.Errorf("noted %v", notes) + } + }) } // A forward that goes takes its connections with it: a browser's // keep-alive connection, opened while the forward was up, ends when the -// port is given up, so its later requests never reach this VM. +// port is given up, so its later requests never reach this VM. Its relay +// ends with it, though the VM never ends its channel: its ssh is killed, +// and its slot is free again. func TestForwarderClosesConnections(t *testing.T) { - p := freePorts(t, 1)[0] - var reserved map[int]bool - accepted := make(chan struct{}, 1) - f := &Forwarder{ - VM: "devvm-f", Log: io.Discard, ports: map[int]*forward{}, skipped: map[int]failure{}, relays: make(chan struct{}, maxRelays), - Reserved: func() (map[int]bool, error) { return reserved, nil }, - Relay: func(_ context.Context, conn net.Conn, _ string, _ int) { - accepted <- struct{}{} - _, _ = io.Copy(io.Discard, conn) // until it's closed - _ = conn.Close() - }, - Listen: platform.ListenLoopback, - } - defer f.closeAll() - f.apply(t.Context(), map[int]string{p: "127.0.0.1"}) - d := net.Dialer{Timeout: time.Second} - c, err := d.DialContext(t.Context(), "tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(p))) - if err != nil { - t.Fatal(err) - } - defer func() { _ = c.Close() }() - <-accepted - reserved = map[int]bool{p: true} - f.release() - _ = c.SetReadDeadline(time.Now().Add(2 * time.Second)) - if _, err := c.Read(make([]byte, 1)); !errors.Is(err, io.EOF) && !errors.Is(err, syscall.ECONNRESET) { - t.Errorf("a connection accepted before the forward went: %v", err) - } + leaktest.Check(t) + synctest.Test(t, func(t *testing.T) { + const p = 5000 + lo := &memLoopback{} + ssh := &memSSH{vm: vmSilent} + var reserved map[int]bool + f := &Forwarder{ + VM: "devvm-f", Log: io.Discard, ports: map[int]*forward{}, skipped: map[int]failure{}, relays: make(chan struct{}, maxRelays), + Reserved: func() (map[int]bool, error) { return reserved, nil }, + Relay: func(ctx context.Context, conn net.Conn, _ string, _ int) { + sshRelay{grace: relayGrace, start: ssh.start}.carry(ctx, conn, nil) + }, + Listen: lo.listen, + } + defer f.closeAll() + f.apply(t.Context(), map[int]string{p: "127.0.0.1"}) + c, err := lo.Dial(net.JoinHostPort("127.0.0.1", strconv.Itoa(p))) + if err != nil { + t.Fatal(err) + } + defer func() { _ = c.Close() }() + synctest.Wait() + if ssh.running() != 1 || len(f.relays) != 1 { + t.Fatalf("relayed: %d ssh, %d slots", ssh.running(), len(f.relays)) + } + reserved = map[int]bool{p: true} + f.release() + if _, err := c.Read(make([]byte, 1)); !errors.Is(err, io.EOF) { + t.Errorf("a connection accepted before the forward went: %v", err) + } + synctest.Wait() + if ssh.running() != 0 || len(f.relays) != 0 { + t.Errorf("once the forward went: %d ssh, %d slots", ssh.running(), len(f.relays)) + } + }) } // The forwarder records why it couldn't take each port: a program's diff --git a/internal/vmssh/links.go b/internal/vmssh/links.go index 08a3b406..ec182be7 100644 --- a/internal/vmssh/links.go +++ b/internal/vmssh/links.go @@ -130,6 +130,9 @@ type Links struct { Start func(ctx context.Context, args []string) (func() error, error) Command func(ctx context.Context, args []string) error Relay func(ctx context.Context, conn net.Conn, args []string) + // Listen listens on a link's socket (listenSocket). Tests set it; Run + // sets it unset. + Listen func(ctx context.Context, path string) (net.Listener, error) mu sync.Mutex open map[linkKey]*linkEnd @@ -238,6 +241,9 @@ func (l *Links) defaults() { if l.Relay == nil { l.Relay = pipeSSH } + if l.Listen == nil { + l.Listen = listenSocket + } l.Wait = cmp.Or(l.Wait, 15*time.Second) } @@ -477,7 +483,7 @@ func (l *Links) add(ctx context.Context, ctl string, w Link) { l.logf("%s: %v", w.listen()+line, err) } sock := l.Socket(w) - ln, err := listenSocket(ctx, sock) + ln, err := l.Listen(ctx, sock) if err != nil { fail(lineNotCarried, err) return diff --git a/internal/vmssh/links_test.go b/internal/vmssh/links_test.go index 53e9b2b2..f384e282 100644 --- a/internal/vmssh/links_test.go +++ b/internal/vmssh/links_test.go @@ -13,14 +13,14 @@ import ( "path/filepath" "reflect" "slices" - "strconv" "strings" "sync" + "sync/atomic" "syscall" "testing" + "testing/synctest" "time" - "github.com/devvmhq/devvm/internal/daemon" "github.com/devvmhq/devvm/internal/leaktest" "github.com/devvmhq/devvm/internal/proxy" "github.com/devvmhq/devvm/internal/state" @@ -270,27 +270,36 @@ func (f *fakeLinks) newLinks(t *testing.T) *Links { } } +// memLinks is newLinks with its links' sockets in memory (lo), for a +// session in a synctest bubble. +func (f *fakeLinks) memLinks(t *testing.T) (*Links, *memLoopback) { + l := f.newLinks(t) + lo := &memLoopback{} + l.Listen = lo.listen + return l, lo +} + +// within waits, in a synctest bubble, for cond, for at most d of the +// bubble's time, then fails the test. +func within(t *testing.T, d time.Duration, what string, cond func() bool) { + t.Helper() + for end := time.Now().Add(d); ; time.Sleep(time.Millisecond) { + synctest.Wait() + if cond() { + return + } + if !time.Now().Before(end) { + t.Fatalf("waited %s for %s", d, what) + } + } +} + func (f *fakeLinks) setWant(ls ...Link) { f.mu.Lock() defer f.mu.Unlock() f.want = ls } -// dial connects to a link's socket and returns what comes back: "" for a -// connection closed without a word, "refused" for none. -func dial(t *testing.T, sock string) string { - t.Helper() - d := net.Dialer{Timeout: time.Second} - c, err := d.DialContext(t.Context(), "unix", sock) - if err != nil { - return "refused" - } - defer func() { _ = c.Close() }() - _ = c.SetDeadline(time.Now().Add(2 * time.Second)) - line, _ := bufio.NewReader(c).ReadString('\n') - return strings.TrimSpace(line) -} - // dialMany makes n connections to a link's socket, one after another, // closed once the test ends. One the socket's backlog refuses is tried // again for up to five seconds: a busy host can keep the session's loop @@ -352,12 +361,17 @@ func (f *fakeLinks) snap(of *[][]string) [][]string { // alone; refusals carry nothing; a link that's gone is cancelled and its // socket removed; with no links left, the session ends. func TestLinks(t *testing.T) { + leaktest.Check(t) + synctest.Test(t, testLinks) +} + +func testLinks(t *testing.T) { a := netip.MustParseAddr db := Link{Name: "db", Target: "devvm-db-0123456789abcd", Addr: a("127.77.0.1"), Port: 5432} cache := Link{Name: "db", Target: db.Target, Addr: a("127.77.0.1"), Port: 6379} api := Link{Name: "api", Target: "devvm-api-0123456789abcd", Addr: a("127.77.0.2"), Port: 80} f := &fakeLinks{} - l := f.newLinks(t) + l, lo := f.memLinks(t) f.taken = map[string]bool{"127.77.0.2:80": true} start := "s1" why := map[int]string{} @@ -376,7 +390,7 @@ func TestLinks(t *testing.T) { f.setWant(db, cache, api) done := make(chan error, 1) go func() { done <- l.Run(t.Context()) }() - waitFor(t, "the links", func() bool { return f.count(&f.commands) == 3 }) + within(t, time.Second, "the links", func() bool { return f.count(&f.commands) == 3 }) session := l.Control("", "") if s := f.snap(&f.starts)[0]; s[slices.Index(s, "-S")+1] != session || !slices.Contains(s, "ClearAllForwardings=yes") { t.Errorf("the session's master: %q", s) @@ -386,45 +400,34 @@ func TestLinks(t *testing.T) { t.Errorf("a forward: %q", c) } } - // A link is marked failed after its forward command returns, so wait for it. - waitFor(t, "api failed", func() bool { - f.mu.Lock() - defer f.mu.Unlock() - return len(f.failed) > 0 - }) f.mu.Lock() if !slices.Equal(f.failed, []string{"api"}) { t.Errorf("failed: %q", f.failed) } f.mu.Unlock() - if got := dial(t, l.Socket(api)); got != "refused" { + if got := lo.reach(l.Socket(api)); got != "refused" { t.Errorf("api's socket: %q", got) } ctl := filepath.Base(l.Control(db.Target, "s1")) - if got := dial(t, l.Socket(db)); got != "127.0.0.1:5432 via "+ctl { + if got := lo.reach(l.Socket(db)); got != "127.0.0.1:5432 via "+ctl { t.Errorf("db: %q", got) } - if got := dial(t, l.Socket(cache)); got != "127.0.0.1:6379 via "+ctl { + if got := lo.reach(l.Socket(cache)); got != "127.0.0.1:6379 via "+ctl { t.Errorf("cache: %q", got) } if n := f.count(&f.starts); n != 2 { t.Errorf("%d masters for one target's start", n-1) } - for _, s := range []string{l.Socket(db), l.Socket(cache)} { - if fi, err := os.Lstat(s); err != nil || fi.Mode().Perm() != 0o600 { - t.Errorf("%s: %v, %v", s, fi, err) - } - } // Refused: each with why, nothing carried. f.mu.Lock() why[5432], why[6379] = "unpublished", "stopped" f.mu.Unlock() relays := f.count(&f.relays) - if got := dial(t, l.Socket(db)); got != "" { + if got := lo.reach(l.Socket(db)); got != "" { t.Errorf("unpublished: %q", got) } - if got := dial(t, l.Socket(cache)); got != "" { + if got := lo.reach(l.Socket(cache)); got != "" { t.Errorf("stopped: %q", got) } if n := f.count(&f.relays); n != relays { @@ -437,46 +440,58 @@ func TestLinks(t *testing.T) { why, start = map[int]string{}, "s2" f.mu.Unlock() ctl2 := filepath.Base(l.Control(db.Target, "s2")) - if got := dial(t, l.Socket(db)); got != "127.0.0.1:5432 via "+ctl2 { + if got := lo.reach(l.Socket(db)); got != "127.0.0.1:5432 via "+ctl2 { t.Errorf("after a restart: %q", got) } f.mu.Lock() close(f.drop[l.Control(db.Target, "s2")]) f.mu.Unlock() - waitFor(t, "the master's end", func() bool { - l.mu.Lock() - defer l.mu.Unlock() - return l.masters[db.Target].dead() - }) - if got := dial(t, l.Socket(db)); got != "127.0.0.1:5432 via "+ctl2 { + synctest.Wait() + l.mu.Lock() + if !l.masters[db.Target].dead() { + t.Error("a master whose ssh ended isn't dead") + } + l.mu.Unlock() + if got := lo.reach(l.Socket(db)); got != "127.0.0.1:5432 via "+ctl2 { t.Errorf("after its master ended: %q", got) } if n := f.count(&f.starts); n != 4 { t.Errorf("%d masters, want 4", n) } - // cache goes: cancelled through the session, its socket removed. + // cache goes, at the next sync: cancelled through the session, its + // socket removed. f.setWant(db, api) - waitFor(t, "the cancel", func() bool { return f.count(&f.commands) == 4 }) + time.Sleep(l.Sync) + synctest.Wait() + if n := f.count(&f.commands); n != 4 { + t.Fatalf("%d commands a sync on, want 4", n) + } if c := f.snap(&f.commands)[3]; c[slices.Index(c, "-O")+1] != "cancel" || !slices.Contains(c, "127.77.0.1:6379:"+l.Socket(cache)) { t.Errorf("the cancel: %q", c) } - waitFor(t, "the socket's removal", func() bool { _, err := os.Lstat(l.Socket(cache)); return err != nil }) + if lo.Listening(l.Socket(cache)) { + t.Error("cache's socket stays") + } + time.Sleep(10 * l.Sync) + synctest.Wait() if n := f.count(&f.commands); n != 4 { t.Errorf("api tried again: %d commands", n) } f.setWant() + time.Sleep(l.Sync) + synctest.Wait() select { case err := <-done: if err != nil { t.Errorf("Run: %v", err) } - case <-time.After(2 * time.Second): - t.Fatal("no links, yet it runs") + default: + t.Fatal("no links a sync on, yet it runs") } - if _, err := os.Lstat(l.Socket(db)); !errors.Is(err, os.ErrNotExist) { - t.Errorf("db's socket stays: %v", err) + if lo.Listening(l.Socket(db)) { + t.Error("db's socket stays") } wantEvents := []string{"link db", "link db", "link_refused db unpublished", "link_target_stopped db stopped", "link db", "link db"} f.mu.Lock() @@ -489,77 +504,94 @@ func TestLinks(t *testing.T) { // The session's connection made again once it's lost, its links with it; // once the client no longer runs as it did, the session ends. func TestLinksSessionLost(t *testing.T) { - db := Link{Name: "db", Target: "devvm-db-0123456789abcd", Addr: netip.MustParseAddr("127.77.0.1"), Port: 5432} - f := &fakeLinks{} - l := f.newLinks(t) - var alive sync.Mutex - up := true - l.Alive = func(context.Context) bool { alive.Lock(); defer alive.Unlock(); return up } - f.target = func(Link) (LinkTarget, string, string) { return LinkTarget{}, EventLinkRefused, "x" } - f.setWant(db) - done := make(chan error, 1) - go func() { done <- l.Run(t.Context()) }() - waitFor(t, "the link", func() bool { return f.count(&f.commands) == 1 }) - f.mu.Lock() - close(f.drop[l.Control("", "")]) - f.mu.Unlock() - waitFor(t, "the link again", func() bool { return f.count(&f.commands) == 2 }) - alive.Lock() - up = false - alive.Unlock() - f.mu.Lock() - close(f.drop[l.Control("", "")]) - f.mu.Unlock() - select { - case err := <-done: - if err != nil { - t.Errorf("Run: %v", err) + synctest.Test(t, func(t *testing.T) { + db := Link{Name: "db", Target: "devvm-db-0123456789abcd", Addr: netip.MustParseAddr("127.77.0.1"), Port: 5432} + f := &fakeLinks{} + l, lo := f.memLinks(t) + var alive atomic.Bool + alive.Store(true) + l.Alive = func(context.Context) bool { return alive.Load() } + f.target = func(Link) (LinkTarget, string, string) { return LinkTarget{}, EventLinkRefused, "x" } + f.setWant(db) + done := make(chan error, 1) + go func() { done <- l.Run(t.Context()) }() + within(t, time.Second, "the link", func() bool { return f.count(&f.commands) == 1 }) + f.mu.Lock() + close(f.drop[l.Control("", "")]) + f.mu.Unlock() + // Made again a tick later. + synctest.Wait() + if lo.Listening(l.Socket(db)) { + t.Error("the link's socket stays with its session gone") } - case <-time.After(2 * time.Second): - t.Fatal("the client stopped, yet it runs") - } - if _, err := os.Lstat(l.Socket(db)); !errors.Is(err, os.ErrNotExist) { - t.Errorf("the socket stays: %v", err) - } - l.Alive = func(context.Context) bool { return false } - if err := l.Run(t.Context()); err == nil { - t.Error("a client that doesn't run: no error") - } + within(t, l.Tick+time.Second, "the link again", func() bool { return f.count(&f.commands) == 2 }) + alive.Store(false) + f.mu.Lock() + close(f.drop[l.Control("", "")]) + f.mu.Unlock() + synctest.Wait() + select { + case err := <-done: + if err != nil { + t.Errorf("Run: %v", err) + } + default: + t.Fatal("the client stopped, yet it runs") + } + if lo.Listening(l.Socket(db)) { + t.Error("the socket stays") + } + l.Alive = func(context.Context) bool { return false } + if err := l.Run(t.Context()); err == nil { + t.Error("a client that doesn't run: no error") + } + }) } // At most maxLinkConns connections at once: the next is refused and // logged, and one goes once another ends. func TestLinksCap(t *testing.T) { - db := Link{Name: "db", Target: "devvm-db-0123456789abcd", Addr: netip.MustParseAddr("127.77.0.1"), Port: 5432} - f := &fakeLinks{hold: make(chan struct{})} - l := f.newLinks(t) - f.target = func(lk Link) (LinkTarget, string, string) { - return LinkTarget{SSH: SSH{VM: lk.Target, User: "u", Key: "/k2", KnownHosts: "/kh", Port: 62022}, Start: "s"}, "", "" - } - f.setWant(db) - ctx, cancel := context.WithCancel(t.Context()) - done := make(chan error, 1) - go func() { done <- l.Run(ctx) }() - defer func() { - cancel() - if err := <-done; err != nil { - t.Errorf("Run: %v", err) + leaktest.Check(t) + synctest.Test(t, func(t *testing.T) { + db := Link{Name: "db", Target: "devvm-db-0123456789abcd", Addr: netip.MustParseAddr("127.77.0.1"), Port: 5432} + f := &fakeLinks{hold: make(chan struct{})} + l, lo := f.memLinks(t) + f.target = func(lk Link) (LinkTarget, string, string) { + return LinkTarget{SSH: SSH{VM: lk.Target, User: "u", Key: "/k2", KnownHosts: "/kh", Port: 62022}, Start: "s"}, "", "" } - }() - waitFor(t, "the link", func() bool { _, err := os.Lstat(l.Socket(db)); return err == nil }) - dialMany(t, l.Socket(db), maxLinkConns) - waitFor(t, "every relay", func() bool { return f.count(&f.relays) == maxLinkConns }) - if got := dial(t, l.Socket(db)); got != "" { - t.Errorf("one past the cap: %q", got) - } - f.mu.Lock() - limit := slices.Contains(f.events, "link_limit db 256") - f.mu.Unlock() - if !limit { - t.Error("the refusal isn't logged") - } - close(f.hold) - waitFor(t, "a free slot", func() bool { return dial(t, l.Socket(db)) != "" }) + f.setWant(db) + ctx, cancel := context.WithCancel(t.Context()) + done := make(chan error, 1) + go func() { done <- l.Run(ctx) }() + defer func() { + cancel() + if err := <-done; err != nil { + t.Errorf("Run: %v", err) + } + }() + within(t, time.Second, "the link", func() bool { return lo.Listening(l.Socket(db)) }) + for i := range maxLinkConns { + c, err := lo.Dial(l.Socket(db)) + if err != nil { + t.Fatalf("connection %d: %v", i+1, err) + } + defer func() { _ = c.Close() }() + } + within(t, time.Second, "every relay", func() bool { return f.count(&f.relays) == maxLinkConns }) + if got := lo.reach(l.Socket(db)); got != "" { + t.Errorf("one past the cap: %q", got) + } + f.mu.Lock() + limit := slices.Contains(f.events, "link_limit db 256") + f.mu.Unlock() + if !limit { + t.Error("the refusal isn't logged") + } + close(f.hold) + if got := lo.reach(l.Socket(db)); got == "" { + t.Error("no slot once the relays ended") + } + }) } // A burst of connections, made one after another as fast as the client's @@ -619,47 +651,27 @@ func TestLinksBurst(t *testing.T) { } } -// stuckSSH puts an ssh stand-in first on PATH that never exits on its -// own, as a relay's ssh whose channel the target never ends, and returns -// how to read the pids of those that started, in order. Any still running -// when the test ends are killed. -func stuckSSH(t *testing.T) func() []int { - t.Helper() - pids := filepath.Join(t.TempDir(), "pids") - fakeSSH(t, "echo $$ >> "+pids+"\nexec sleep 600") - read := func() []int { - b, _ := os.ReadFile(pids) //nolint:gosec // gosec G304: the test's own temp file - var started []int - for f := range strings.FieldsSeq(string(b)) { - if pid, err := strconv.Atoi(f); err == nil { - started = append(started, pid) - } - } - return started - } - t.Cleanup(func() { - for _, pid := range read() { - if daemon.Alive(pid) { - _ = daemon.Signal(pid, syscall.SIGKILL) - } - } - }) - return read -} - // A relay whose target never ends its channel (a VM whose sshd ignores // EOF) still ends when its link is removed, or when its target's master // is replaced (the target started again): its ssh is killed and its slot // is free again, so a target can't keep the session's relays by holding -// them open. +// them open. Each step's end is checked at the moment it happens, on the +// bubble's clock. func TestLinksEndStuckRelays(t *testing.T) { + // Nothing of the session's is left once it ends: every relay's + // goroutines, and the stand-in's pipes, are gone. + leaktest.Check(t) + synctest.Test(t, testLinksEndStuckRelays) +} + +func testLinksEndStuckRelays(t *testing.T) { a := netip.MustParseAddr db := Link{Name: "db", Target: "devvm-db-0123456789abcd", Addr: a("127.77.0.1"), Port: 5432} api := Link{Name: "api", Target: "devvm-api-0123456789abcd", Addr: a("127.77.0.2"), Port: 80} - pids := stuckSSH(t) + ssh := &memSSH{vm: vmSilent} f := &fakeLinks{} - l := f.newLinks(t) - l.Relay = pipeSSH + l, lo := f.memLinks(t) + l.Relay = sshRelay{grace: relayGrace, start: ssh.start}.carry start := "s1" f.target = func(lk Link) (LinkTarget, string, string) { f.mu.Lock() @@ -667,9 +679,6 @@ func TestLinksEndStuckRelays(t *testing.T) { return LinkTarget{SSH: SSH{VM: lk.Target, User: "u", Key: "/k2", KnownHosts: "/kh", Port: 62022}, Start: start}, "", "" } f.setWant(db, api) - // Nothing of the session's is left once it ends: every relay's - // goroutines, and the stand-in's pipes, are gone. - leaktest.Check(t) ctx, cancel := context.WithCancel(t.Context()) done := make(chan error, 1) go func() { done <- l.Run(ctx) }() @@ -680,31 +689,45 @@ func TestLinksEndStuckRelays(t *testing.T) { } }() for _, lk := range []Link{db, api} { - waitFor(t, lk.Name+"'s socket", func() bool { _, err := os.Lstat(l.Socket(lk)); return err == nil }) + within(t, time.Second, lk.Name+"'s socket", func() bool { return lo.Listening(l.Socket(lk)) }) + } + // connect leaves a connection to sock open, carried once the bubble + // has done what it can, until the test ends. + connect := func(sock string) { + t.Helper() + n := ssh.count() + c, err := lo.Dial(sock) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = c.Close() }) + within(t, time.Second, "the relay", func() bool { return ssh.count() == n+1 }) + } + check := func(what string, started, running, slots int) { + t.Helper() + synctest.Wait() + if ssh.count() != started || ssh.running() != running || len(l.conns) != slots { + t.Errorf("%s: %d ssh started, %d running, %d slots; want %d, %d, %d", what, ssh.count(), ssh.running(), len(l.conns), started, running, slots) + } } - // l.conns was made before the first Check, which the test follows - // through f.mu. - slots := func() int { return len(l.conns) } - // db's link removed: its relay ends, though api's link stays. - dialMany(t, l.Socket(db), 1) - waitFor(t, "db's ssh", func() bool { return len(pids()) == 1 }) + // db's link removed: its relay ends at the next sync, though api's + // link stays. + connect(l.Socket(db)) + check("db's relay", 1, 1, 1) f.setWant(api) - waitFor(t, "db's ssh to end", func() bool { return !daemon.Alive(pids()[0]) }) - waitFor(t, "db's slot", func() bool { return slots() == 0 }) + time.Sleep(l.Sync) + check("db's link removed", 1, 0, 0) // api's target started again: the next connection gets a master of // its own, and the old master's relay ends with it. - dialMany(t, l.Socket(api), 1) - waitFor(t, "api's ssh", func() bool { return len(pids()) == 2 }) + connect(l.Socket(api)) f.mu.Lock() start = "s2" f.mu.Unlock() - dialMany(t, l.Socket(api), 1) - waitFor(t, "api's second ssh", func() bool { return len(pids()) == 3 }) - waitFor(t, "api's first ssh to end", func() bool { return !daemon.Alive(pids()[1]) }) - waitFor(t, "api's first slot", func() bool { return slots() == 1 }) - if !daemon.Alive(pids()[2]) { + connect(l.Socket(api)) + check("api's target started again", 3, 1, 1) + if !ssh.alive(2) { t.Error("the new master's relay ended too") } @@ -714,10 +737,10 @@ func TestLinksEndStuckRelays(t *testing.T) { other := api other.Target = "devvm-web-0123456789abcd" f.setWant(other) - waitFor(t, "the old target's ssh to end", func() bool { return !daemon.Alive(pids()[2]) }) - waitFor(t, "its slot", func() bool { return slots() == 0 }) - dialMany(t, l.Socket(other), 1) - waitFor(t, "the new target's ssh", func() bool { return len(pids()) == 4 }) + time.Sleep(l.Sync) + check("api's target changed", 3, 0, 0) + connect(l.Socket(other)) + check("the new target", 4, 1, 1) if args := f.snap(&f.starts); !slices.ContainsFunc(args, func(a []string) bool { return slices.Contains(a, l.Control(other.Target, "s2")) }) { @@ -784,12 +807,14 @@ func TestLinksCarryCut(t *testing.T) { // not: each with its names, address, port, target and socket, mode 600, // written again when they change or the file goes, and empty once the // client has none; a list an earlier session left is replaced. -func TestLinksList(t *testing.T) { +func TestLinksList(t *testing.T) { synctest.Test(t, testLinksList) } + +func testLinksList(t *testing.T) { a := netip.MustParseAddr db := Link{Name: "db", Target: "devvm-db-0123456789abcd", Addr: a("127.77.0.1"), Port: 5432, Hosts: []string{"db", "db.devvm.internal"}} api := Link{Name: "api", Target: "devvm-api-0123456789abcd", Addr: a("127.77.0.2"), Port: 80, Hosts: []string{"api", "api.devvm.internal"}} f := &fakeLinks{} - l := f.newLinks(t) + l, lo := f.memLinks(t) l.List = filepath.Join(l.Dir, l.VM.String()+".links.json") f.taken["127.77.0.2:80"] = true f.target = func(lk Link) (LinkTarget, string, string) { @@ -814,15 +839,15 @@ func TestLinksList(t *testing.T) { ctx, cancel := context.WithCancel(t.Context()) done := make(chan error, 1) go func() { done <- l.Run(ctx) }() - waitFor(t, "the links listed", func() bool { list, _ := read(); return len(list.Links) == 2 }) - waitFor(t, "db carried", func() bool { return dial(t, l.Socket(db)) != "refused" }) + within(t, time.Second, "the links listed", func() bool { list, _ := read(); return len(list.Links) == 2 }) + within(t, time.Second, "db carried", func() bool { return lo.reach(l.Socket(db)) != "refused" }) // api listens on its socket before the client refuses it, and closes // it after: its refusal is told once the socket is gone. - waitFor(t, "api refused", func() bool { - f.mu.Lock() - defer f.mu.Unlock() - return slices.Contains(f.failed, "api") - }) + f.mu.Lock() + if !slices.Contains(f.failed, "api") { + t.Error("api not refused") + } + f.mu.Unlock() list, mode := read() want := []proxy.LinkEntry{ {Hosts: db.Hosts, Addr: "127.77.0.1", Port: 5432, Target: db.Target, Socket: l.Socket(db)}, @@ -833,29 +858,32 @@ func TestLinksList(t *testing.T) { if list.Version != proxy.LinkListVersion || !reflect.DeepEqual(list.Links, want) || mode != 0o600 { t.Errorf("the list: %+v, mode %v; want %+v", list, mode, want) } - if _, err := os.Lstat(l.Socket(api)); !errors.Is(err, os.ErrNotExist) { - t.Errorf("api's socket: %v", err) + if lo.Listening(l.Socket(api)) { + t.Error("api's socket stays") } if want[0].Socket != proxy.LinkSocket(l.Dir, l.VM, db.Addr, db.Port) { t.Errorf("the socket isn't the one the proxy expects: %s", want[0].Socket) } - // Removed by something else, it's written again. + // Removed by something else, it's written again at the next sync. if err := os.Remove(l.List); err != nil { t.Fatal(err) } - waitFor(t, "the list again", func() bool { list, _ := read(); return len(list.Links) == 2 }) + time.Sleep(l.Sync) + synctest.Wait() + if list, _ := read(); len(list.Links) != 2 { + t.Errorf("a sync after its removal, the list: %+v", list) + } f.setWant() - waitFor(t, "the session's end", func() bool { - select { - case err := <-done: - if err != nil { - t.Errorf("Run: %v", err) - } - return true - default: - return false + time.Sleep(l.Sync) + synctest.Wait() + select { + case err := <-done: + if err != nil { + t.Errorf("Run: %v", err) } - }) + default: + t.Error("no links a sync on, yet it runs") + } cancel() if list, _ := read(); list.Version != proxy.LinkListVersion || len(list.Links) != 0 { t.Errorf("the list once the client has no links: %+v", list) diff --git a/internal/vmssh/relay.go b/internal/vmssh/relay.go index 5fca39f8..636da938 100644 --- a/internal/vmssh/relay.go +++ b/internal/vmssh/relay.go @@ -10,56 +10,84 @@ import ( ) // relayGrace is how long a relay goes on once its client has closed its -// side with nothing coming from the VM (pipeSSHFor). +// side with nothing coming from the VM (sshRelay.carry). const relayGrace = 30 * time.Second // pipeSSH carries conn through ssh run with args (-W), until either side // ends, then closes conn; a VM that never ends its side is cut off -// relayGrace after the client has (pipeSSHFor). +// relayGrace after the client has (sshRelay.carry). func pipeSSH(ctx context.Context, conn net.Conn, args []string) { - pipeSSHFor(ctx, conn, args, relayGrace) + sshRelay{grace: relayGrace, start: execSSH}.carry(ctx, conn, args) } -// pipeSSHFor is pipeSSH with its grace. The ssh (-W) ends only when the -// VM's sshd ends its channel, so a VM that ignored the client's EOF would -// keep it, and its owner's relay slot, for as long as the VM liked. Once -// the client's side has closed, the ssh is killed when the VM has sent -// nothing for grace, so a client that closes for writing alone still -// gets an answer that keeps coming, as long as the VM sends something at -// least every grace, its first byte included; once the client can take -// nothing more, it's killed when it hasn't exited within grace. The grace -// doesn't run while a write to the client waits for it, so a slow client -// is never cut off from what the VM has sent it, but the owner's context +// sshRelay carries a connection through an ssh -W (carry). +type sshRelay struct { + // grace is how long the VM may send nothing once the client's side + // has closed (carry). + grace time.Duration + // start starts ssh with args, killed once ctx ends: execSSH, or a + // test's stand-in. + start func(ctx context.Context, args []string) (sshPipes, error) +} + +// sshPipes is a started ssh's input and output, and how to wait for it +// to end. +type sshPipes struct { + in io.WriteCloser + out io.Reader + wait func() error +} + +// execSSH starts ssh with args, which ctx's end kills. +func execSSH(ctx context.Context, args []string) (sshPipes, error) { + cmd := exec.CommandContext(ctx, "ssh", args...) //nolint:gosec // devvm's own arguments + in, err := cmd.StdinPipe() + if err != nil { + return sshPipes{}, err + } + out, err := cmd.StdoutPipe() + if err != nil { + return sshPipes{}, err + } + if err := cmd.Start(); err != nil { + return sshPipes{}, err + } + return sshPipes{in: in, out: out, wait: cmd.Wait}, nil +} + +// carry carries conn through ssh run with args (-W), until either side +// ends, then closes conn. The ssh ends only when the VM's sshd ends its +// channel, so a VM that ignored the client's EOF would keep it, and its +// owner's relay slot, for as long as the VM liked. Once the client's side +// has closed, the ssh is killed when the VM has sent nothing for the +// grace, so a client that closes for writing alone still gets an answer +// that keeps coming, as long as the VM sends something at least every +// grace, its first byte included; once the client can take nothing more, +// it's killed when it hasn't exited within the grace. The grace doesn't +// run while a write to the client waits for it, so a slow client is +// never cut off from what the VM has sent it, but the owner's context // (ctx) closes the connection when it ends, which ends such a write too. -func pipeSSHFor(ctx context.Context, conn net.Conn, args []string, grace time.Duration) { +func (r sshRelay) carry(ctx context.Context, conn net.Conn, args []string) { defer func() { _ = conn.Close() }() ctx, cancel := context.WithCancel(ctx) defer cancel() stop := context.AfterFunc(ctx, func() { _ = conn.Close() }) defer stop() - cmd := exec.CommandContext(ctx, "ssh", args...) //nolint:gosec // devvm's own arguments - in, err := cmd.StdinPipe() + ssh, err := r.start(ctx, args) if err != nil { return } - out, err := cmd.StdoutPipe() - if err != nil { - return - } - if err := cmd.Start(); err != nil { - return - } - idle := newGraceTimer(grace, cancel) + idle := newGraceTimer(r.grace, cancel) defer idle.stop() go func() { - _, _ = io.Copy(in, conn) - _ = in.Close() + _, _ = io.Copy(ssh.in, conn) + _ = ssh.in.Close() idle.arm() }() - _, _ = io.Copy(&graceWriter{w: conn, idle: idle}, out) + _, _ = io.Copy(&graceWriter{w: conn, idle: idle}, ssh.out) _ = conn.Close() idle.arm() - _ = cmd.Wait() + _ = ssh.wait() } // graceTimer cancels a relay once its grace runs out. It runs only once diff --git a/internal/vmssh/relay_test.go b/internal/vmssh/relay_test.go index 0763b6e7..6c2f6ffd 100644 --- a/internal/vmssh/relay_test.go +++ b/internal/vmssh/relay_test.go @@ -2,6 +2,7 @@ package vmssh import ( "bufio" + "bytes" "context" "io" "net" @@ -9,11 +10,16 @@ import ( "path/filepath" "strconv" "strings" + "sync" + "sync/atomic" "syscall" "testing" + "testing/synctest" "time" "github.com/devvmhq/devvm/internal/daemon" + "github.com/devvmhq/devvm/internal/leaktest" + "github.com/devvmhq/devvm/internal/memnet" ) // relayPair is a connection to relay and its client's end, over TCP on @@ -113,7 +119,7 @@ func TestPipeSSHGrace(t *testing.T) { ended := make(chan struct{}) go func() { defer close(ended) - pipeSSHFor(t.Context(), relayed, nil, grace) + sshRelay{grace: grace, start: execSSH}.carry(t.Context(), relayed, nil) }() pid := pidOf(t, pidFile) if tc.half { @@ -167,7 +173,7 @@ func TestPipeSSHGraceSlowClient(t *testing.T) { ended := make(chan struct{}) go func() { defer close(ended) - pipeSSHFor(t.Context(), relayed, nil, grace) + sshRelay{grace: grace, start: execSSH}.carry(t.Context(), relayed, nil) }() pid := pidOf(t, pidFile) _ = client.CloseWrite() @@ -201,33 +207,265 @@ func TestPipeSSHGraceSlowClient(t *testing.T) { // A relay whose write waits on a client that stopped reading still ends // with its owner's context, as LoopbackForward.Close or a forward's close // cancels it: the cancel closes the connection, which ends the write. -func TestPipeSSHCancelEndsBlockedWrite(t *testing.T) { - dir := t.TempDir() - pidFile := filepath.Join(dir, "pid") - fakeSSH(t, "echo $$ > "+pidFile+".tmp && mv "+pidFile+".tmp "+pidFile+"\nexec yes") - relayed, client := relayPair(t) - ctx, cancel := context.WithCancel(t.Context()) +func TestRelayCancelEndsBlockedWrite(t *testing.T) { + leaktest.Check(t) + synctest.Test(t, func(t *testing.T) { + ssh := &memSSH{vm: vmYes} + ctx, cancel := context.WithCancel(t.Context()) + _, ended := ssh.relay(ctx, time.Hour) + // Never read: the relay's write to the client waits once its + // buffer fills. + time.Sleep(time.Minute) + synctest.Wait() + if isClosed(ended) { + t.Fatal("the relay ended while its context lasted") + } + cancel() + synctest.Wait() + if !isClosed(ended) { + t.Fatal("the relay outlived its context while its write waited") + } + if ssh.running() != 0 { + t.Error("its ssh still runs") + } + }) +} + +// memSSH is an ssh -W in memory, for a relay in a synctest bubble: what +// the VM sends (vm) until it's killed, as exec.CommandContext kills ssh +// once its context ends, and its input read and dropped. Killed, its +// output ends and its input takes nothing more. +type memSSH struct { + vm func(ctx context.Context, out io.Writer) + + mu sync.Mutex + procs []chan struct{} // each one started, closed once it has ended + ended int +} + +func (m *memSSH) start(ctx context.Context, _ []string) (sshPipes, error) { + inR, inW := io.Pipe() + outR, outW := io.Pipe() + done := make(chan struct{}) + m.mu.Lock() + m.procs = append(m.procs, done) + m.mu.Unlock() + kill := func() { + _ = outW.Close() + _ = inR.CloseWithError(syscall.EPIPE) + } + stop := context.AfterFunc(ctx, kill) + go func() { _, _ = io.Copy(io.Discard, inR) }() + go func() { + m.vm(ctx, outW) + <-ctx.Done() // it never ends its channel: only the kill ends it + stop() + kill() + m.mu.Lock() + m.ended++ + close(done) + m.mu.Unlock() + }() + return sshPipes{in: inW, out: outR, wait: func() error { <-done; return nil }}, nil +} + +// count is how many of its ssh started; running how many run. +func (m *memSSH) count() int { + m.mu.Lock() + defer m.mu.Unlock() + return len(m.procs) +} + +func (m *memSSH) running() int { + m.mu.Lock() + defer m.mu.Unlock() + return len(m.procs) - m.ended +} + +// alive is whether the i-th ssh started still runs. +func (m *memSSH) alive(i int) bool { + m.mu.Lock() + defer m.mu.Unlock() + return !isClosed(m.procs[i]) +} + +// relay carries a connection in memory through m, with grace, until ctx +// ends: the client's end, and what's closed once the relay has ended. +func (m *memSSH) relay(ctx context.Context, grace time.Duration) (*memnet.Conn, chan struct{}) { + client, relayed := memnet.Pipe() ended := make(chan struct{}) go func() { defer close(ended) - pipeSSHFor(ctx, relayed, nil, time.Hour) + sshRelay{grace: grace, start: m.start}.carry(ctx, relayed, nil) }() - pid := pidOf(t, pidFile) - // Never read: the relay's write to the client waits once the buffers - // fill. - time.Sleep(500 * time.Millisecond) - cancel() + return client, ended +} + +// vmSilent is a VM that sends nothing; vmYes one that sends without end, +// as yes does. +func vmSilent(context.Context, io.Writer) {} + +func vmYes(_ context.Context, out io.Writer) { + line := bytes.Repeat([]byte("y\n"), 2048) + for { + if _, err := out.Write(line); err != nil { + return + } + } +} + +// vmSays is a VM that sends each line it's given on say. +func vmSays(say chan string) func(context.Context, io.Writer) { + return func(ctx context.Context, out io.Writer) { + for { + select { + case <-ctx.Done(): + return + case s := <-say: + if _, err := io.WriteString(out, s+"\n"); err != nil { + return + } + } + } + } +} + +// isClosed reports whether ch is closed. +func isClosed(ch chan struct{}) bool { select { - case <-ended: - case <-time.After(10 * time.Second): + case <-ch: + return true + default: + return false + } +} + +// endsAt checks, in a bubble, that a relay ends exactly after d more, +// with its ssh killed, and not a moment before. +func endsAt(t *testing.T, what string, ended chan struct{}, ssh *memSSH, d time.Duration) { + t.Helper() + time.Sleep(d - time.Nanosecond) + synctest.Wait() + if isClosed(ended) { + t.Fatalf("%s: ended before %s", what, d) + } + time.Sleep(time.Nanosecond) + synctest.Wait() + if !isClosed(ended) { + t.Fatalf("%s: still carried after %s", what, d) + } + if ssh.running() != 0 { + t.Errorf("%s: its ssh still runs", what) + } +} + +// The grace, on the bubble's clock: a relay whose client has closed, +// fully or for writing alone, ends exactly the grace after, its ssh +// killed, though the VM never ends its channel. One whose VM keeps +// sending to a half-closed client goes on as long as it sends within each +// grace, and ends the grace after its last line. One whose client has +// closed fully, its VM still sending, ends the grace after the write that +// failed. +func TestRelayGrace(t *testing.T) { + const grace = 30 * time.Second + for _, tc := range []struct { + name string + half bool + }{{"closed", false}, {"half closed", true}} { + t.Run("silent, "+tc.name, func(t *testing.T) { + leaktest.Check(t) + synctest.Test(t, func(t *testing.T) { + ssh := &memSSH{vm: vmSilent} + client, ended := ssh.relay(t.Context(), grace) + time.Sleep(time.Hour) // nothing ends it while the client's side is open + synctest.Wait() + if isClosed(ended) { + t.Fatal("ended with its client's side open") + } + if tc.half { + _ = client.CloseWrite() + } else { + _ = client.Close() + } + endsAt(t, "silent", ended, ssh, grace) + }) + }) + } + t.Run("talking, half closed", func(t *testing.T) { + leaktest.Check(t) + synctest.Test(t, func(t *testing.T) { + say := make(chan string) + ssh := &memSSH{vm: vmSays(say)} + client, ended := ssh.relay(t.Context(), grace) + _ = client.CloseWrite() + r := bufio.NewReader(client) + for i := range 10 { + time.Sleep(grace - time.Nanosecond) + say <- strconv.Itoa(i) + if line, err := r.ReadString('\n'); err != nil || line != strconv.Itoa(i)+"\n" { + t.Fatalf("line %d: %q, %v", i, line, err) + } + } + endsAt(t, "talking", ended, ssh, grace) + }) + }) + t.Run("talking, closed", func(t *testing.T) { + leaktest.Check(t) + synctest.Test(t, func(t *testing.T) { + say := make(chan string) + ssh := &memSSH{vm: vmSays(say)} + client, ended := ssh.relay(t.Context(), grace) + _ = client.Close() + time.Sleep(grace / 2) + say <- "x" // its write to the client fails: the grace starts again + endsAt(t, "talking", ended, ssh, grace) + }) + }) +} + +// A half-closed client that stops reading holds the VM's answer back, and +// the relay's write to it waits: the grace doesn't run while it does, +// however long that is. Read again, the answer keeps coming; closed, the +// relay ends the grace after. +func TestRelayGraceSlowClient(t *testing.T) { + const grace = 30 * time.Second + leaktest.Check(t) + synctest.Test(t, func(t *testing.T) { + ssh := &memSSH{vm: vmYes} + client, ended := ssh.relay(t.Context(), grace) + _ = client.CloseWrite() + time.Sleep(10 * grace) + synctest.Wait() + if isClosed(ended) { + t.Fatal("the relay ended while its write to a slow client waited") + } + if _, err := io.CopyN(io.Discard, client, 1<<20); err != nil { + t.Fatalf("the slow client's answer: %v", err) + } _ = client.Close() - _ = daemon.Signal(pid, syscall.SIGKILL) - <-ended - t.Fatal("the relay outlived its context while its write waited") - } - if daemon.Alive(pid) { - t.Error("its ssh still runs") - } + endsAt(t, "slow client", ended, ssh, grace) + }) +} + +// A relay whose writes to its client fail ends the grace after the first, +// with the client's side never seen to close. +func TestRelayGraceWriteError(t *testing.T) { + const grace = 30 * time.Second + leaktest.Check(t) + synctest.Test(t, func(t *testing.T) { + say := make(chan string) + ssh := &memSSH{vm: vmSays(say)} + block := make(chan struct{}) + defer close(block) + ended := make(chan struct{}) + go func() { + defer close(ended) + sshRelay{grace: grace, start: ssh.start}.carry(t.Context(), deafConn{block: block}, nil) + }() + time.Sleep(time.Hour) + say <- "x" + endsAt(t, "deaf client", ended, ssh, grace) + }) } // deafConn is a client that can take nothing more, and whose reads never @@ -254,7 +492,7 @@ func TestPipeSSHGraceWriteError(t *testing.T) { ended := make(chan struct{}) go func() { defer close(ended) - pipeSSHFor(t.Context(), deafConn{block: block}, nil, grace) + sshRelay{grace: grace, start: execSSH}.carry(t.Context(), deafConn{block: block}, nil) }() defer func() { close(block) }() pid := pidOf(t, pidFile) @@ -272,11 +510,11 @@ func TestPipeSSHGraceWriteError(t *testing.T) { // A grace timer runs only once armed, never while a write waits, and // never once stopped: an arm or a write after the relay has ended, from -// the client's goroutine that outlives it, doesn't start it again. Each -// case's timer either fires within a second, or doesn't within ten -// graces. +// the client's goroutine that outlives it, doesn't start it again. On the +// bubble's clock, a timer that fires does so exactly the grace after its +// last arm or write, and one that doesn't never does. func TestGraceTimer(t *testing.T) { - const grace = 20 * time.Millisecond + const grace = 30 * time.Second write := func(g *graceTimer, d time.Duration) { _, _ = g.write(func() (int, error) { time.Sleep(d); return 0, nil }) } @@ -287,40 +525,38 @@ func TestGraceTimer(t *testing.T) { }{ {"never armed, though written to", func(g *graceTimer) { write(g, 0) }, false}, {"armed", func(g *graceTimer) { g.arm() }, true}, - {"armed, then written to", func(g *graceTimer) { g.arm(); write(g, 0) }, true}, + {"armed, then written to", func(g *graceTimer) { g.arm(); time.Sleep(grace / 2); write(g, 0) }, true}, + // Armed, then a write that waits many graces: the grace doesn't run + // while it waits, and starts again once it's done. + {"armed, then a long write", func(g *graceTimer) { g.arm(); write(g, 10*grace) }, true}, + // A write that waits many graces, armed while it waits: the grace + // starts once it's done. + {"armed while a write waits", func(g *graceTimer) { + _, _ = g.write(func() (int, error) { g.arm(); time.Sleep(10 * grace); return 0, nil }) + }, true}, {"stopped, then armed", func(g *graceTimer) { g.arm(); g.stop(); g.arm() }, false}, {"stopped, then written to", func(g *graceTimer) { g.arm(); g.stop(); write(g, 0) }, false}, } { - fired := make(chan struct{}, 1) - g := newGraceTimer(grace, func() { fired <- struct{}{} }) - tc.steps(g) - wait := 10 * grace - if tc.fires { - wait = time.Second - } - select { - case <-fired: - if !tc.fires { - t.Errorf("%s: fired", tc.name) + synctest.Test(t, func(t *testing.T) { + var fired atomic.Bool + g := newGraceTimer(grace, func() { fired.Store(true) }) + tc.steps(g) + time.Sleep(grace - time.Nanosecond) + synctest.Wait() + if fired.Load() { + t.Errorf("%s: fired before the grace", tc.name) } - case <-time.After(wait): - if tc.fires { - t.Errorf("%s: never fired", tc.name) + time.Sleep(time.Nanosecond) + synctest.Wait() + if fired.Load() != tc.fires { + t.Errorf("%s: fired %v once the grace passed, want %v", tc.name, fired.Load(), tc.fires) } - } - } - // A write that waits many graces, armed while it waits: the timer - // doesn't fire until it's done. - fired := make(chan struct{}, 1) - g := newGraceTimer(grace, func() { fired <- struct{}{} }) - _, _ = g.write(func() (int, error) { - g.arm() - time.Sleep(10 * grace) - return 0, nil - }) - select { - case <-fired: - t.Error("fired while a write waited") - default: + time.Sleep(time.Hour) + synctest.Wait() + if fired.Load() != tc.fires { + t.Errorf("%s: fired %v an hour on, want %v", tc.name, fired.Load(), tc.fires) + } + g.stop() + }) } } diff --git a/testdata/coverage/darwin.txt b/testdata/coverage/darwin.txt index 46a38b60..95187401 100644 --- a/testdata/coverage/darwin.txt +++ b/testdata/coverage/darwin.txt @@ -21,6 +21,7 @@ internal/hostsafety 95.9 internal/image 99.4 internal/jsonc 97.1 internal/leaktest 87.0 +internal/memnet 96.8 internal/msg 72.1 internal/msg/gen 93.9 internal/netpolicy 91.8 diff --git a/testdata/coverage/linux.txt b/testdata/coverage/linux.txt index 8e0b67a6..329040e9 100644 --- a/testdata/coverage/linux.txt +++ b/testdata/coverage/linux.txt @@ -21,6 +21,7 @@ internal/hostsafety 87.5 internal/image 99.3 internal/jsonc 97.1 internal/leaktest 87.0 +internal/memnet 96.8 internal/msg 68.6 internal/msg/gen 93.3 internal/netpolicy 88.5