mirror of
https://github.com/devvmhq/devvm.git
synced 2026-12-01 06:23:17 -10:00
A VM's proxy runs as two processes, as design.md's "The proxy's broker"
says: devvm _proxy, the broker, which keeps what only the host should
do, and devvm _proxy-child, which reads the VM's network and can be
confined by the follow-ups.
- wire.go: the protocol over one socketpair (close-on-exec from the
start: SOCK_CLOEXEC on Linux, ForkLock elsewhere), length-prefixed JSON
frames of at most 2 MiB, unknown fields refused, bytes as base64, one
descriptor on a frame's first bytes (SCM_RIGHTS, MSG_CTRUNC breaks the
rules), wire types for every secret (redact.Secret at once).
- broker.go: newBroker, the start (handshake: version 1 and each side's
executable's SHA-256, within 4 s), the answers (value through lookups,
kept 30 s or 5 min, a failure 5 s, dropped when the bindings change;
file by number; link connected by the broker and passed as a
descriptor; token exchanged by the broker), each by something in its
own config, with caps 1/8/4/256; live: the lifeline closes the socket
and kills the child 6 s later, SIGTERM stops it within a second, a
child that ends ends the broker, a rule broken stops the child.
- child.go: the start (startOf), the child's server (newChildServer),
the broker as hostSide over the socket (brokerClient), runChildOn;
ready only after it reads the host's addresses (kept: the last good
read), roots and time zone loaded first.
- process.go: Main(ctx, ...) and ChildMain; the child spawned with
/proc/self/exe on Linux, PR_SET_PDEATHSIG from a locked thread
(daemon.Cmd.DieWithThread), descriptors 3 and 4, and TZ, SSL_CERT_*
and GODEBUG with updatemaxprocs=0 alone; run/proxy-child.pid and
run/proxy.confined ("none" until the follow-ups); KeepLogs in the
broker. ChildMain refuses to start unless descriptors 3 and 4 are a
unix socket and an IP one (checkInherited): run by hand, without
them, those numbers can be the Go runtime's own, which closing
crashed it (signal_recv: inconsistent state).
- capture.go: a captured token request goes to the broker
(captureToken, exchanger), so a login's real tokens never enter the
child; an error reply passes up to 1 MiB, longer gets 502.
- watched.go: the child stats each changing file and asks the broker
for it once it changed, keeping the stamp of what the broker read.
- rotate.go: proxy.log rotated by both through its descriptor, under a
lock of a description of its own; OpenLog opens a log never through a
link, one link, yours, replacing what a child left in its place.
- nixcache.go: the trim and its count through a safefile.Root, nar/
only as a folder, links deleted as themselves; reads never through a
link; the lock tried for 5 s (ErrNixLocked, nix_cache_locked).
- daemon: Cmd.Err, Files, Env, DieWithThread; Handle.Kill, Exit;
WritePID.
- netpolicy: Proxy.Stop also stops a child that outlived its broker
(run/proxy-child.pid, _proxy-child -for); proxy.log opened with
OpenLog; a refused launch keeps a running VM only while both run.
devvm network log and lock read the event log through safefile.
- vm, vmssh, vmlog: links.log and ports.log opened with OpenLog, read
through safefile, trimmed only as a regular file with one link.
- backend: the build proxy's logs in a logs/ folder of their own.
- cli: _proxy-child; _proxy waits for its child on a signal
(StopsItsOwn); the child reads none of devvm's folders (no
makePrivate); ui.Files.
- Tests: FuzzBrokerFrames, the frames' rules, the handshake and the
pair's end in synctest bubbles, the caps, the broker naming its own
alone, the client over a real socketpair with a passed descriptor,
ChildMain, TestInheritedSocket and proxy.txtar's child run by hand,
the frozen 0.1.0 configs starting a broker and child,
two writers rotating once, planted links, FIFOs and hard links; the
testscript runner stops _proxy-child too; e2e: broker and child, their
arguments, descriptors and environment, stop, SIGKILL either, planted
files in the logs folder and the Nix cache, build proxies gone.
- Review fixes: the lifeline closes the socket and starts the kill's
timer before logging; every log lock (proxy.log's, the event log's
rotation) is tried without blocking for 200 ms (flockWithin, which the
Nix lock shares), then written without or the rotation skipped; a
copied log's rotation streams at most twice its limit from a line's
start (copyFrom, copyAtomic); a reply too long to send goes as
too_long; kept token headers capped at 1 KiB; the child gives up on a
request whose context ended, dropping its late reply and holding its
slot until then; a write deadline on the start frame; errors reach the
child as codes (not_found, refused, busy, too_long, failed), their
text in the broker's log; FuzzFrameStreams, and FuzzBrokerFrames
writes from a goroutine; nix_cache_locked links to How it works.
- Docs: processes, network, overview, design (with threat rows for the
logs' locks and a log made huge), troubleshooting, the proxy's
README, structure, testing; CHANGELOG.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
170 lines
5.8 KiB
Go
170 lines
5.8 KiB
Go
package backend
|
|
|
|
import (
|
|
"errors"
|
|
"os"
|
|
"path/filepath"
|
|
"reflect"
|
|
"slices"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/devvmhq/devvm/internal/daemon"
|
|
"github.com/devvmhq/devvm/internal/msg"
|
|
"github.com/devvmhq/devvm/internal/proxy"
|
|
"github.com/devvmhq/devvm/internal/redact"
|
|
)
|
|
|
|
// A build's proxy starts with its own password, its policy and the
|
|
// company proxy in its config, the user's alone, and none of them in its
|
|
// arguments; it's found by the port its status file names. Stop ends it
|
|
// and deletes the config, leaving the logs.
|
|
func TestProxyStarter(t *testing.T) {
|
|
dir := filepath.Join(t.TempDir(), "build")
|
|
var args []string
|
|
var ended <-chan struct{}
|
|
s := ProxyStarter{Self: "/devvm", Tick: time.Millisecond, Spawn: func(c daemon.Cmd) (*daemon.Handle, error) {
|
|
args = append([]string{c.Path}, c.Args...)
|
|
h, err := sleeper(t, c, "127.0.0.1:40123")
|
|
if err == nil {
|
|
ended = h.Done()
|
|
}
|
|
return h, err
|
|
}}
|
|
up := &proxy.Upstream{HTTPS: corpProxy}
|
|
p, err := s.Start(dir, proxy.Config{VM: "devvm-img-x", Lifeline: "/run/ha.pid", Upstream: up, UpstreamUnresolved: true})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if p.Port != 40123 || len(p.Password.Reveal()) != 64 {
|
|
t.Errorf("port %d, password %q", p.Port, p.Password.Reveal())
|
|
}
|
|
config := filepath.Join(dir, "proxy.json")
|
|
if want := []string{"/devvm", "_proxy", "-config", config}; !slices.Equal(args, want) {
|
|
t.Errorf("arguments %q, want %q", args, want)
|
|
}
|
|
c, err := proxy.ReadConfig(config)
|
|
if want := (proxy.Config{
|
|
Version: proxy.ConfigVersion, Listen: "127.0.0.1:0", VM: "devvm-img-x", Password: p.Password,
|
|
Policies: []string{filepath.Join(dir, "policy")}, Log: filepath.Join(dir, "logs", "events.jsonl"),
|
|
// Its own log, held to its limit as a VM's proxy holds its own.
|
|
ProxyLog: filepath.Join(dir, "logs", "proxy.log"), Lifeline: "/run/ha.pid", Upstream: up, UpstreamUnresolved: true,
|
|
}); err != nil || !reflect.DeepEqual(c, want) {
|
|
t.Errorf("config = %+v, %v; want %+v", c, err, want)
|
|
}
|
|
for _, f := range []string{"proxy.json", "policy"} {
|
|
fi, err := os.Stat(filepath.Join(dir, f))
|
|
if err != nil || fi.Mode().Perm() != 0o600 {
|
|
t.Errorf("%s: %v %v", f, fi, err)
|
|
}
|
|
}
|
|
if b, _ := os.ReadFile(filepath.Join(dir, "policy")); !strings.HasSuffix(string(b), "\n**\n") { //nolint:gosec // the test's own folder
|
|
t.Errorf("policy = %q", b)
|
|
}
|
|
p.Stop()
|
|
select {
|
|
case <-ended:
|
|
case <-time.After(2 * time.Second):
|
|
t.Fatal("not stopped")
|
|
}
|
|
if _, err := os.Stat(config); !errors.Is(err, os.ErrNotExist) {
|
|
t.Errorf("its config stayed: %v", err)
|
|
}
|
|
// The logs, in a folder of their own, which the child writes.
|
|
if fi, err := os.Stat(filepath.Join(dir, "logs", "proxy.log")); err != nil || fi.Mode().Perm() != 0o600 {
|
|
t.Errorf("the log went: %v %v", fi, err)
|
|
}
|
|
|
|
// Without a company proxy, none in its config.
|
|
if p, err = s.Start(dir, proxy.Config{VM: "devvm-img-x", Lifeline: "/run/ha.pid"}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if c, err := proxy.ReadConfig(config); err != nil || c.Upstream != nil || c.UpstreamUnresolved {
|
|
t.Errorf("no upstream: %+v %v", c, err)
|
|
}
|
|
p.Stop()
|
|
}
|
|
|
|
// sleeper starts a sleep in c's place that says it's ready with say in
|
|
// c's status file ("" for never), stopped when the test ends.
|
|
func sleeper(t *testing.T, c daemon.Cmd, say string) (*daemon.Handle, error) {
|
|
t.Helper()
|
|
h, err := daemon.Spawn(daemon.Cmd{Path: "sleep", Args: []string{"60"}, Out: c.Out})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
t.Cleanup(func() { h.Stop(time.Second) })
|
|
if say != "" {
|
|
err = daemon.WriteStatus(c.Status, h.PID(), say)
|
|
}
|
|
return h, err
|
|
}
|
|
|
|
// A proxy that never says it listens, or says so of an address that
|
|
// isn't loopback or has no port, is stopped, naming its log; so is one
|
|
// that said it listens but has already ended (another program took the
|
|
// port from it).
|
|
func TestProxyStarterFails(t *testing.T) {
|
|
for _, say := range []string{"", "192.0.2.1:3128", "127.0.0.1:0", "127.0.0.1:x", "ended"} {
|
|
dir := t.TempDir()
|
|
var h *daemon.Handle
|
|
s := ProxyStarter{Self: "/devvm", Tick: time.Millisecond, Spawn: func(c daemon.Cmd) (*daemon.Handle, error) {
|
|
if say != "ended" {
|
|
var err error
|
|
h, err = sleeper(t, c, say)
|
|
return h, err
|
|
}
|
|
var err error
|
|
if h, err = daemon.Spawn(daemon.Cmd{Path: "true", Out: c.Out}); err != nil {
|
|
return nil, err
|
|
}
|
|
<-h.Done()
|
|
return h, daemon.WriteStatus(c.Status, h.PID(), "127.0.0.1:40123")
|
|
}}
|
|
_, err := s.Start(dir, proxy.Config{VM: "b", Lifeline: "/l"})
|
|
if msg.NamesOf(err) != "proxy_start_failed log="+filepath.Join(dir, "logs", "proxy.log")+" vm=b" {
|
|
t.Errorf("%q: Start = %v", say, err)
|
|
}
|
|
select {
|
|
case <-h.Done():
|
|
case <-time.After(5 * time.Second):
|
|
t.Errorf("%q: left running", say)
|
|
}
|
|
if _, err := os.Stat(filepath.Join(dir, "proxy.json")); !errors.Is(err, os.ErrNotExist) {
|
|
t.Errorf("%q: its config, with its password, stayed: %v", say, err)
|
|
}
|
|
}
|
|
// One that can't be started at all leaves no config either.
|
|
dir := t.TempDir()
|
|
s := ProxyStarter{Self: "/devvm", Tick: time.Millisecond, Spawn: func(daemon.Cmd) (*daemon.Handle, error) {
|
|
return nil, errors.New("no such program")
|
|
}}
|
|
if _, err := s.Start(dir, proxy.Config{VM: "b", Password: redact.NewSecret("x")}); err == nil {
|
|
t.Error("Start: no error")
|
|
}
|
|
if _, err := os.Stat(filepath.Join(dir, "proxy.json")); !errors.Is(err, os.ErrNotExist) {
|
|
t.Errorf("a proxy that never ran left its config: %v", err)
|
|
}
|
|
}
|
|
|
|
// A build's proxy is stopped through the process devvm started: one still
|
|
// running ends; one that has ended is left alone (no signal reaches a
|
|
// process given its pid since); none is nothing.
|
|
func TestBuildProxyStop(t *testing.T) {
|
|
h, err := daemon.Spawn(daemon.Cmd{Path: "sleep", Args: []string{"60"}})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
bp := &BuildProxy{proc: h, dir: t.TempDir()}
|
|
bp.Stop()
|
|
select {
|
|
case <-h.Done():
|
|
case <-time.After(2 * time.Second):
|
|
t.Fatal("not stopped")
|
|
}
|
|
bp.Stop()
|
|
var none *BuildProxy
|
|
none.Stop()
|
|
}
|