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]>
114 lines
4.3 KiB
Go
114 lines
4.3 KiB
Go
package backend
|
|
|
|
import (
|
|
"net/netip"
|
|
"os"
|
|
"path/filepath"
|
|
"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"
|
|
"github.com/devvmhq/devvm/internal/state"
|
|
)
|
|
|
|
// A build that reaches the internet through a company proxy goes through
|
|
// a proxy of devvm's own on the host, one per build: devvm _proxy with any host on ports 80 and 443 but
|
|
// the host's own and internal addresses, through the company proxy (its
|
|
// config's Upstream), and a password made for the build. The build gets only
|
|
// that proxy's address with that password, so the company proxy's
|
|
// credentials stay on the host, out of reach of the code a build runs,
|
|
// which is an image's own.
|
|
|
|
// ProxyStarter starts build proxies: devvm's own binary (Self), run by
|
|
// Spawn (daemon.Spawn: a process that can outlive devvm, stopped through
|
|
// the process itself), looked at every Tick while it starts, ten times at
|
|
// most.
|
|
type ProxyStarter struct {
|
|
Self string
|
|
Spawn func(daemon.Cmd) (*daemon.Handle, error)
|
|
Tick time.Duration
|
|
}
|
|
|
|
// BuildProxy is one build's proxy: its port on the host's loopback and its
|
|
// password, which a build reaches it with (ProxyURL).
|
|
type BuildProxy struct {
|
|
Port int
|
|
Password redact.Secret
|
|
proc *daemon.Handle
|
|
dir string
|
|
}
|
|
|
|
// Start starts the proxy of a build (c.VM), its broker and its child, its
|
|
// files in dir, made again and the user's alone: its config (proxy.json),
|
|
// its policy and its status file, and in a folder of their own, logs/,
|
|
// which the child writes, its log (proxy.log) and its event log
|
|
// (events.jsonl). c has what the build chose: its lifeline, the company
|
|
// proxy it goes through and whether names the host can't resolve go
|
|
// there; Start sets the rest. It listens on a loopback port of its own
|
|
// and ends when the process its lifeline's pid file names does, or at
|
|
// Stop. It returns once the proxy says it listens, in its status file
|
|
// (status), and still runs.
|
|
func (s ProxyStarter) Start(dir string, c proxy.Config) (*BuildProxy, error) {
|
|
if err := os.RemoveAll(dir); err != nil {
|
|
return nil, err
|
|
}
|
|
logs := filepath.Join(dir, "logs")
|
|
if err := os.MkdirAll(logs, 0o700); err != nil {
|
|
return nil, err
|
|
}
|
|
pw, err := NewProxyPassword()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
p := &BuildProxy{Password: pw, dir: dir}
|
|
policy, logPath := filepath.Join(dir, "policy"), filepath.Join(logs, "proxy.log")
|
|
if err := state.WriteFile(policy, []byte("# a build: any host, not this machine's own or internal addresses\n**\n")); err != nil {
|
|
return nil, err
|
|
}
|
|
// Its own log is its output, which it holds to its limit as a VM's
|
|
// proxy does (proxy.Config.ProxyLog).
|
|
c.Listen, c.Password, c.Policies = "127.0.0.1:0", pw, []string{policy}
|
|
c.Log, c.ProxyLog = filepath.Join(logs, "events.jsonl"), logPath
|
|
// The password and the company proxy's credentials go in the config,
|
|
// the user's alone: a process's arguments are visible to other users.
|
|
config := filepath.Join(dir, configFile)
|
|
if err := state.WriteFile(config, c.Encode()); err != nil {
|
|
return nil, err
|
|
}
|
|
out, err := proxy.OpenLog(logPath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer func() { _ = out.Close() }()
|
|
status := filepath.Join(dir, "status")
|
|
if p.proc, err = s.Spawn(daemon.Cmd{Path: s.Self, Args: []string{"_proxy", "-config", config}, Out: out, Status: status}); err != nil {
|
|
_ = os.Remove(config) // its passwords, for a proxy that never ran
|
|
return nil, err
|
|
}
|
|
said, ok := daemon.WaitReady(status, p.proc.PID(), p.proc.Running, s.Tick, 10)
|
|
if ap, err := netip.ParseAddrPort(said); ok && err == nil && ap.Addr().IsLoopback() && ap.Port() != 0 {
|
|
p.Port = int(ap.Port())
|
|
return p, nil
|
|
}
|
|
p.Stop()
|
|
return nil, msg.ProxyStartFailed(logPath, c.VM)
|
|
}
|
|
|
|
// Stop stops the proxy, through the process Start started (daemon.Handle),
|
|
// so the signal reaches it alone, never another process given its pid
|
|
// since: SIGTERM, which has the broker stop its child, then after two
|
|
// seconds SIGKILL. It deletes its config, which holds its password and
|
|
// the company proxy's, leaving its logs. A nil one is none.
|
|
func (p *BuildProxy) Stop() {
|
|
if p == nil {
|
|
return
|
|
}
|
|
p.proc.Stop(2 * time.Second)
|
|
_ = os.Remove(filepath.Join(p.dir, configFile))
|
|
}
|
|
|
|
// configFile is a build proxy's config in its folder.
|
|
const configFile = "proxy.json"
|