mirror of
https://github.com/devvmhq/devvm.git
synced 2026-12-01 21:36:40 -10:00
The design notes are for contributors: they hold each emulation's design note, its threat check and its tests, with hundreds of Go identifiers, so the page moves from How it works to Contributing (weight 8, after Writing docs), keeping its title and anchors. An alias keeps /docs/internals/design/ working, as a redirect to the new page. Every reference follows: the internals, using, safety and contributing pages' links, the page's own links to the How it works pages, the section index pages, AGENTS.md's Backends rule, contributing/docs.md's What goes where, internal/proxy/README.md and two e2e comments. Co-Authored-By: Claude Opus 5.5 <[email protected]>
137 lines
45 KiB
Markdown
137 lines
45 KiB
Markdown
# internal/proxy
|
|
|
|
The network policy proxy runs on the host, one for each VM, on every [network tier](../../docs/content/docs/internals/network.md), as two processes. Its broker, `devvm _proxy`, keeps what only the host should do: each value's lookup (`IO.Secret`), the token exchange of a login made in the VM (`IO.Capture`), connecting to the VM's links' sockets, reading the files that change while it runs, the SSH agent's relay and the lifeline. The broker starts its child, `devvm _proxy-child`, with the VM's proxy port's listener and one end of a socketpair. The child reads the VM's network and does everything below, and it asks the broker over the socket for each of the broker's jobs, naming each by something the broker finds in its own config ([the proxy's broker](../../docs/content/docs/contributing/design.md#the-proxys-broker)). The proxy is Go and uses the standard library alone, with five of devvm's packages that also use only the standard library, which depguard enforces for all six: `internal/daemon`, devvm's background-process helper, `internal/safefile`, devvm's reader of files a VM can write, `internal/vmname`, the type of a VM's name, `internal/redact`, whose `Secret` is the type of the VM's password, the company proxy's and every value the proxy looks up, and `internal/landlock`, Linux's sandbox for the child.
|
|
|
|
The VM can reach nothing but this proxy. On macOS its Lima hostagent runs under a Seatbelt profile, and on Linux QEMU's network is restricted. Other programs on the host can reach the port too, so the port alone doesn't identify the VM. Every request must carry the VM's password in `Proxy-Authorization`, with the user `devvm`, and the VM's proxy URL has it. The VM's placeholders end in a random value of its own, which isn't the password, so no other VM's or program's placeholder gets a secret. The proxy runs with one config, `Config`, which holds the password, and it refuses to start without one ([how devvm runs it](#how-devvm-runs-it)). For each connection it:
|
|
|
|
- answers `407` without the VM's password;
|
|
- takes only a host name with no empty label, after it lowercases the name, in ASCII alone, and drops one trailing dot, or an address without an IPv6 zone, whose trailing dot stays, and answers `400` to anything else, a name with a character that isn't printable ASCII included, which it never folds into ASCII (the Kelvin sign into `k`);
|
|
- refuses `devvm.proxy`, its own domain, and every name under it with `403`, logged as a refused block, before the links, the policy or a company proxy see it: only an absolute-form request for `http://devvm.proxy/` reaches its endpoints, and `CONNECT devvm.proxy:P` has none; it refuses the stand-in address `198.18.0.1` (`SentinelAddr`) the same way, with a reason that says the tool resolved the name itself;
|
|
- takes `CONNECT transparent.devvm.proxy:PORT` (`TransparentHost`), which a confined VM's `devvm-transparent` sends for a tool that skipped the proxy settings, after the password and the tunnel slot and before anything else: the host is the TLS ClientHello's SNI or each HTTP request's `Host`, read from the first bytes within 10 seconds, and the connection is then judged and carried as `CONNECT host:PORT` is (`routeFor`), its events with `"via": "dns"`; a blocked TLS host gets a certificate for it from the VM's CA and the `403` text, and `GET http://devvm.proxy/transparent/ports` lists the ports to redirect (`transparentPorts`) ([transparent mode](../../docs/content/docs/internals/network.md#tools-that-skip-the-proxy));
|
|
- with `links` in its config, sends a request for one of the VM's links (`CONNECT db:5432`, `GET http://db:5432/`) to that link's socket on the host before any rule (below);
|
|
- checks `CONNECT host:port` and absolute-form requests (`GET http://host/…`) against the VM's policy, which is devvm's built-in policies, read from the binary, and then the user's policy files, and tunnels or forwards allowed ones untouched;
|
|
- resolves names through this machine's resolver, which the broker asks for the child (`dial.go`), and refuses the host's own addresses and internal ones (loopback, private, link-local, multicast, unspecified, CGNAT `100.64.0.0/10`) unless a rule names the address; through a company proxy (`upstream`), which resolves names itself, it refuses a name when the host's resolver answers with such an address, and a name the host can't resolve when only `**` allows it (unless `upstream_unresolved`, which builds on Lima get), and it reads at most 64 KiB of the company proxy's answer to `CONNECT`;
|
|
- requires a TLS ClientHello in a tunnel to name the CONNECT host (SNI), in ASCII, letters' case aside, whole in one record of at most 16 KiB and 256 bytes (`helloRecordMax`) within 10 seconds of its first byte (`helloTimeout`), and passes nothing the VM sends to the far end before it has checked it, while the far end's bytes reach the VM at once, so a server that speaks first, such as SMTP's, sends its greeting before the VM sends anything; a stream whose first byte starts a TLS record is TLS from then on, so a record header that never comes whole, or a ClientHello that doesn't parse in its one record, is refused, never passed on, an address's tunnel's included, which may have no name;
|
|
- for a host whose rules narrow it to some methods or paths (`api.github.com GET,HEAD /repos/`), judges each of its requests, every one on a kept-alive or HTTP/2 connection, with one matcher (`match` in `request.go`), decrypting its `:443` tunnels with the VM's CA and refusing them on other ports (`hostRules.byRequest`, `server.judgeRequest`), and answers `403` to a request the rules refuse, logged with its method and path;
|
|
- for hosts with a bound secret, swaps the placeholder in one header for the real value: it intercepts their `:443` tunnels, and does the same for absolute-form `https://` requests (everything else passes unread), with certificates from the VM's CA, of which it keeps the 1024 used most recently (`leafCacheMax`);
|
|
- for an agent's OAuth token endpoint (`captures`), intercepts its host's `:443` tunnels the same way, and hands a `POST` to its path, at most 64 KiB, to the broker (`captureToken`). The broker sends it to the endpoint itself and hands the request and its successful reply, at most 1 MiB, to `IO.Capture` (`exchanger`), which saves the login on the host and gives the reply the VM gets, with placeholders and no refresh token, so the endpoint's reply never reaches the VM ([capturing logins](#capturing-logins));
|
|
- carries at most 1024 `CONNECT`s at once (`maxConnects`), links' and intercepted ones too, and answers `503` past it, logged as a refused block, and once in its own log until a tunnel ends;
|
|
- holds at most 2048 connections with the VM's password at once (`maxConns`), of every kind, plain HTTP's and idle ones included. It counts each one from its first request with the password (`conns.admit`), and a request past the limit gets `503` and its connection closed. Connections that haven't sent the password wait in a pool of 128 (`maxWaiting`), where a new one closes the oldest. It sends at most 2048 requests upstream at once (`maxRequests`, `requests.take`), plain HTTP's and intercepted tunnels' alike, and answers `503` past them. Each limit says so in its own log once a minute at most (`everyMinute`);
|
|
- bounds what a connection holds, never how long a request or a tunnel lasts (`httpServer`, `serveOne`): 64 KiB of a request's headers (`maxHeaderBytes`) on every connection it serves HTTP on, 10 minutes between requests (`idleTimeout`), at most 100 HTTP/2 requests at once inside a tunnel (`streamsMax`), its connection closed after a `407`, and a plain HTTP request ended once its client has stopped sending and a minute (`goneWait`) has passed with nothing to pass on, so a client that half-closes still gets an answer that keeps coming (`whileHeard`);
|
|
- with `nix_cache`, answers `http://devvm.proxy/nix/` itself, as a Nix binary cache that VMs share and only the host fills (below);
|
|
- logs every decision as JSON lines, and keeps why a name didn't resolve or a tunnel didn't connect in its own log: the VM's `403`, `/blocked` and the event log get a reason that names neither the host's DNS server nor the company proxy (`reasonUnresolvable`, `reasonConnectFailed`).
|
|
|
|
For a VM whose image has the nix layer, devvm sets `nix_cache`, and the VM's Nix tries `http://devvm.proxy/nix` before `https://cache.nixos.org`. The proxy takes only `GET` and `HEAD` of `nix-cache-info`, `<32 nix-base32>.narinfo` and `nar/<52 nix-base32>.nar` (bare, `.xz`, `.zst` or `.bz2`), with no query, and answers `400` to anything else. It makes up `nix-cache-info` itself, at priority 30, and fetches the rest from `https://cache.nixos.org` alone, only when the VM's policy allows `cache.nixos.org:443` and, by its rules by method and path, a `GET` of the path asked for (`policy.judge`), through the floor or the company proxy, never following a redirect and sending nothing of the VM's request. Before keeping a narinfo, it checks its signature by the pinned `cache.nixos.org-1` key over its fingerprint (`1;StorePath;NarHash;NarSize;References`), that its StorePath is the one asked for, and that its URL is named by its own `NarHash` or `FileHash`. It fetches a NAR only after a narinfo it checked names it, never for a `HEAD`, each one once however many ask and at most four at once, and keeps it only when its SHA-256 and size are that narinfo's `FileHash` and `FileSize`. Files are written whole and renamed into the folder, mode 600 in folders of 700. Anything that fails answers `404`, and nothing of it is kept, so Nix goes to cache.nixos.org itself. Under a lock (`flock` on `.lock`), the proxy takes each file's room in whole blocks before it writes it (`reserve`), deleting the least recently used files (by modification time, which a hit updates) when the file would take the cache past `nix_cache_max`, down to nine tenths of it, and `.size` keeps the running total. A NAR being fetched is made its full size at once and counts against the cap, so a fetch that would pass it with them is refused. devvm gc and the retention settings trim it with `TrimNixCache`, under the same lock.
|
|
|
|
With `links`, the proxy is a second entrance to the VM's [links between VMs](../../docs/content/docs/internals/network.md#links-through-the-proxy), beside the ssh remote forward that carries every link. `devvm _links` writes every link the VM has, carried or not, to the list (`LinkList`, JSON, version 1) whenever they change, and leaves it when it ends, so a link with no socket is refused rather than asked of the rules, and the proxy checks it for every request and reads it again when it has changed (`watched`), a list it can't read having no links, logged once: a regular file, not a symbolic link, that only its owner may write, at most 1 MiB. After the password and before any rule, it lowercases the host, drops one trailing dot, and looks for an entry that names that host (`NAME` or `NAME.devvm.internal`) and port exactly. It takes an entry only when its socket is `LinkSocket` of the sockets' folder (`link_sockets`, devvm's run folder; without it, no link is reached), the VM (`vm`), the entry's address and its port, which is how `vmssh.Links` names it, and its address is in `127.77.0.0/16`, so the proxy never connects to another VM's link or to any other socket. Any other host under `devvm.internal` gets `403`, logged as a refused block, before the rules. A `CONNECT` is tunneled to the socket as it is, with no SNI check, no interception and no secret, and an absolute-form `http://` request goes there in origin form, without the proxy's headers, over a new connection for each request, which ends when the client gives it up. An `https://` request in absolute form gets `400`. The proxy logs nothing for a link it carried, because `devvm _links` logs it, and when the socket doesn't answer, after a few tries for a full backlog, it answers `502` and logs `link_refused` (`not carried`).
|
|
|
|
The child makes no connection of its own, because its sandbox refuses it every one. It asks the broker to look up each name and to open each connection, to an address that the broker's own floor allows or to the company proxy of its config, and the broker hands it the connection (`dial.go`). On macOS the broker starts its child under `sandbox-exec`, with the Seatbelt profile that `IO.Seatbelt` gives for what the child needs (`ChildNeeds`), and the child checks that the sandbox refuses it the broker's config before it says it's ready ([the child's sandbox](../../docs/content/docs/internals/network.md#the-childs-sandbox)). On Linux the child confines itself before it reads a byte of the VM's, with Landlock and a seccomp filter (`internal/landlock`'s `Self`, through `confineself_linux.go`), and makes the same check. Once its child says it's ready, the broker writes the child's pid file (`ChildPIDFile`) and how the child is confined (`ConfinedFile`) beside the config. `ConfinedFile` holds a line that `ParseConfinement` reads, then a line that names the broker by its pid and its start (`BrokerID`), so `ReadConfined` takes the file only from the broker that runs now. Then the broker says it's ready with the address the child serves (`daemon.Ready`), in the status file that devvm names in its environment (`DEVVM_DAEMON_STATUS`), which is what devvm waits for as it starts the proxy. The broker returns when the VM's hostagent is gone, closing the socket, which ends the child. It also returns at `SIGTERM`, stopping the child, when its child ends, or when a frame breaks the protocol's rules. The child returns when the broker's end of the socket closes.
|
|
|
|
## Files
|
|
|
|
| File | What |
|
|
| --- | --- |
|
|
| `config.go` | `Config`, the one config a VM's proxy and a build's run with (`Encode`, `Sum`, `ReadConfig`, `ConfigVersion`), its password a `redact.Secret`, and `configFile`, the config as its file has it, the password a string, which `Encode` writes and `ReadConfig` reads, and `readPrivate`, the checked read of the files devvm writes for the proxy alone (the config, the bindings, the links' list and the CA): a regular file that isn't a symbolic link, at most its cap, as `safefile` reads it (`safefile.ErrNotRegular`, `safefile.ErrTooLong`), owned by the proxy's user and with none of the permission bits it refuses (`ErrNotPrivate`), which `ReadPrivate` gives `internal/secrets` for the list of your secrets |
|
|
| `process.go` | the two processes: `IO`, `Main` and its one flag, `-config`, the broker's run (`runBroker`: its log, its listener, the agent's relay, the child's start, `spawnChild`, the lifeline, and the backend's logs kept to their cap through `IO.KeepLogs`, for `vm_logs`), and `ChildMain`, the child's, with its one flag, `-for`, which refuses descriptors 3 and 4 unless they're the broker's sockets (`checkInherited`) |
|
|
| `broker.go` | the broker (`broker`, `newBroker`), what the child asks of it (`hostSide`), its answers (`serveChild`, `answer`: values through `lookups`, files, links, token exchanges, names' addresses and connections, `dial.go`) and their caps (`requestCaps`), the start (`handshake`), the pair's end (`live`), the child's files and arguments (`ChildPIDFile`, `ConfinedFile`, `IsChild`), its executable and environment (`selfExe`, `selfSum`, `childEnv`) |
|
|
| `child.go` | the child: its start (`childStart`, `startOf`), its server (`newChildServer`, `childServer`), the broker as it asks it over the socket (`brokerClient`), its confinement as it starts (`confineStarted`: `IO`'s `confine`, then the host's addresses read again, `hostAddrs.check`), and its run (`runChildOn`) |
|
|
| `dial.go` | the child's lookups and connections, through the broker: the broker's own egress (`newBrokerNet`), which judges each address again with its own read of the VM's policy and the host's addresses (`egress.addrOK`) before it connects (`broker.dial`, `dialProxy` for the company proxy of its config), the names it looks up (`lookupable`), the codes of a lookup's failure and the resolver's error the child makes of them again (`dnsCode`, `lookupError`), and the child's side (`brokerClient.lookup`, `dial`, `dialProxy`, wired into its egress by `throughHost`) |
|
|
| `wire.go` | the broker's protocol: frames (`frameConn`: a length, then JSON, a descriptor on the first bytes), their wire types (`toChild`, `toBroker`, `wireStart`…), and the rules a frame breaks (`ruleError`) |
|
|
| `socketpair_linux.go`, `socketpair_other.go` | the socketpair, close-on-exec from the start |
|
|
| `touch_linux.go`, `touch_other.go` | a file's times set through its descriptor (`touchFile`), which the Nix cache marks a file used with, as the child's seccomp filter refuses it by its path, and the broker made undumpable (`undumpable`, Linux's `PR_SET_DUMPABLE`) |
|
|
| `childstart.go` | the broker's start of its child (`startChild`): under `IO.Seatbelt`'s sandbox for what it needs (`childSandbox`, `childNeeds`, `ChildNeeds`), once more unconfined only when `sandbox-exec` itself failed (`sandboxFailed`), and the Nix cache's folders made first |
|
|
| `confine.go` | how the child is confined, which every platform shares: `Confinement`, its line in `run/proxy.confined` and the broker's after it (`ParseConfinement`, `BrokerID`, `ReadConfined`), the child's check that it holds (`confineChild`, `checkConfined`, which opens the broker's config), within `confineWait` (`within`), and the hook where a platform confines it in the process (`confineSelf`, in `confineself_linux.go`, which confines it with `internal/landlock` and words its line with `landlockConfinement`, and `confineself_other.go`) |
|
|
| `proxy.go` | the proxy's `server`, which the child makes from its start (`newChildServer`), CONNECT and absolute-form handling, the address floor (`egress`, `hostAddrs`, and `Public`, its ranges, which `devvm network lock` leaves out), the log (`Event`, `events`, `AllowRule`: `devvm network log` reads it), the `devvm.proxy` endpoints |
|
|
| `host.go` | the one form of a host (`Host`, `NormHost`) that the requests, the SNI check, the rules, the bindings and `NO_PROXY` read hosts in, and that `netpolicy`'s risks and ticks, a secret's `--host`, an MCP server's host, `--from`'s registry and a partial clone's promisor remotes read theirs in too: a host of printable ASCII lowercased, in ASCII alone, with its one trailing dot dropped unless it's an address, whose dot can only be its IPv6 zone's, and any other left as it is; the host names the proxy takes (`HostOK`, which `agentlogin` checks MCP servers' hosts with too), and a request's host and port (`splitHostPort`). The structure test refuses another copy of it |
|
|
| `request.go` | requests by method and path: the one matcher (`match`, `allows` strict for allows and bindings, `denies` broad for denies), the methods (`Methods`, `ParseMethods`) and those a request names besides its own (`overrides`: every override-like header in any spelling, `overrideLike`, and the query's `_method`), path patterns (`PathOK`, `matchPath`), the plain form a path must have (`plainPath`), and judging each forwarded request (`server.judgeRequest`) |
|
|
| `policy.go` | the rule syntax and matching (`ValidRule`, `CanonicalRule`, `NarrowRule`, `Narrowable`: `devvm network allow`, `deny` and `rm` take only these), the host's verdict and its requests' (`verdict`, `byRequest`, `judge`); `ReadAllowlist`, a VM's policies read as the proxy reads them, whose `Allows` is the proxy's own decision by its rules, which `devvm network lock` judges a learning VM's hosts with; `ParsePolicy`, the one strict parser of policy files, which `devvm network` and doctor use too: each line that holds more than a comment, with its number and whether it's a rule; the built-in policies are read once (`readBuiltins`), every line a rule, and come first in the union; the user's policy files are re-read when they change, each only as a regular file of at most 1 MiB (`ReadPolicy`, which `devvm network` and doctor read them with too, and `PolicyMax`; one that isn't keeps its last rules, logged once), and each line that isn't a rule is logged and skipped, except one that starts with `!` (`BrokenDeny`), which makes the policy deny everything, as refused blocks naming the file and line, until it's fixed |
|
|
| `sni.go` | reads a tunnel's ClientHello to check its server name |
|
|
| `transparent.go` | the transparent path: the reserved target (`TransparentHost`), the proxy's own domain (`ProxyDomain`, `reservedRefusal`), the stand-in address (`SentinelAddr`, `IsSentinelAddr`, which the port forwarder refuses), `transparent`'s TLS way (`sniHost`, `replay`, `refusePage`) and HTTP way (`handler`), events' `ViaDNS` (`withVia`), and the ports it serves; `routeFor`, in `proxy.go`, is the order of checks it shares with `CONNECT` |
|
|
| `watched.go` | `watched`, the one way the proxy keeps a file it reads again when it changes: the bindings, the policy files and the links list. Each request stats the file, and it's read again when its mtime, size or inode differ from the last read's, or when the last read's mtime was within 2 seconds of then, so two writes within one mtime tick are both seen; its bytes are parsed again only when they differ. A change of mode or owner alone (`chmod`, `chown`) changes none of the three, so after a good read it isn't seen until the file's next write: a file made readable or writable by others then keeps its last contents until it changes. A refused read forgets the stamp, so a file whose mode is fixed after one is read again at the next request. Each user picks its read (`readPrivate`, with its cap, or `ReadPolicy`), whether a symbolic link is followed, and what a failure leaves: the last good contents (the policy files) or none (the bindings and the links list). A missing file has none, silently; any other failure is logged once until the file reads again. The bindings' hook, which clears the cached values, runs under the watcher's lock whenever the file changes, a touch included |
|
|
| `splice.go` | every tunnel the proxy carries itself: `hijack` takes a `CONNECT`'s connection from the HTTP server and answers `200`, and `splice` passes the bytes both ways as they are, the server's from the start and the client's once a check has passed them (the SNI check, for a tunnel the policy allows), passes on the end of what the client sent, and ends once the server's bytes end or the client has gone |
|
|
| `conns.go` | the proxy's close: `conns` holds every connection its listener accepted (`track`) and counts every handler (`handle`), so `closeConns` ends the tunnels and upgrades that `http.Server`'s `Close` leaves, and waits for the handlers |
|
|
| `limits.go` | what the proxy holds for a VM at once: its connections (`maxConns`, `maxWaiting`) and its requests upstream (`requests`, `maxRequests`), each logged at most once a minute when it's reached (`everyMinute`), and the lines that a VM's failures drive, such as the lookups it gives up on and the broker's failed connections, a number of them a minute (`perMinute`) |
|
|
| `secrets.go` | interception for hosts with a bound secret: certificates from devvm's CA (`ca`), which devvm makes (`trust.InitCA`) and the proxy only loads (a day each, never past the CA's end; once the CA has ended, `CONNECT`s to be intercepted answered `403` and logged as refused with `caEndedReason`), header substitution; the VM's bindings and their values (`secrets`), `Binding` (`KindSecret` or `KindLogin`, with the login's `Agent`) in a `BindingList` (JSON, version 1), which `internal/secrets` writes and `ReadBindings` reads, and `InterceptLines`, the allowlist's lines for their hosts; values from `IO.Secret`, looked up in the proxy's own process as `redact.Secret`s (cached briefly, never logged); `writeAtomic`, the proxy's one writer of whole files |
|
|
| `capture.go` | capturing logins at agents' token endpoints: `Capture` (`Config.Captures`' entries), `Exchange` and `Capturer` (`IO.Capture`), which requests are captured (`captures.agents`, `endpointAgents`), the child's side (`captureToken`), the broker's (`exchanger`: the request sent, the reply read and saved, `errorReply`, `keepHeaders`), the `1xx` dropped (`no1xx`), `ModifyResponse` (`captureResponse`: `guard`, `page`) and the `502` for what can't be read (`refuseCapture`) |
|
|
| `upstream.go` | `upstream` and `upstreams`: a company proxy that allowed requests go through (`CONNECT` by name for tunnels and interception, absolute form for plain HTTP), `NO_PROXY`, and the floor for names it resolves (`floorUpstream`) |
|
|
| `rotate.go` | the logs' rotation past `LogLimit` (10 MiB): the event log renamed to `<log>.1` under the file's lock, the proxy's own log, which is also both processes' stderr, copied there and emptied through its descriptor under its lock; `OpenLog`, which opens a log never through a link, only a regular file with one link that's yours, and replaces what a child left in its place; `OpenEventLog`, the event log's writer, which netpolicy's `AppendEvent` uses too, and which opens the log again before a line once the other writer has rotated it |
|
|
| `nixcache.go` | `nix_cache`: the shared Nix cache at `http://devvm.proxy/nix/` (`nixCache`), its path pattern (`nixPath`), narinfo checks (`parseNarinfo`), NAR checks, the cap and its trim (`NixCacheUsage`, `TrimNixCache`) |
|
|
| `agent.go` | the SSH agent's relay (`agentRelay`): its socket (`listenAgent`), the requests it passes on (`agentAllowed`), and the agent protocol's messages, read and written whole (`readAgentMsg`, `writeAgentMsg`) |
|
|
| `links.go` | `links`: the VM's links' list (`LinkList`, `LinkEntry`) and the proxy's way to them (`links`), their sockets' names (`LinkSocket`, `LinkHash`), their addresses and domain, which devvm's other packages use too (`IsLinkAddr`, `LinkAddr`, `LinkDomain`), matching (`links.find`), `CONNECT` and absolute-form requests to a link |
|
|
| `*_test.go` | unit tests, and fuzz targets for policy rules (`FuzzParseRule`), request targets (`FuzzRequest`), a deny's path and method however a request spells them (`FuzzDenyBypass`), ClientHellos (`FuzzClientHello`), a transparent connection's first bytes (`FuzzTransparent`), the Nix cache's paths (`FuzzNixPath`) and narinfos (`FuzzParseNarinfo`), every reader of a host (`FuzzHostSites`), Cursor's replies (`FuzzCursorFrames`), where a binding's value goes (`FuzzInject`), the bindings file (`FuzzParseBindings`), the links list (`FuzzLinkList`), the broker's protocol (`FuzzBrokerFrames`) and streams of its frames either way (`FuzzFrameStreams`), the company proxy's URL (`FuzzParseUpstream`) and `NO_PROXY` (`FuzzNoProxy`), each with the property it checks in [Fuzzing](../../docs/content/docs/contributing/testing.md#fuzzing); `testdata/nix/` holds a narinfo and its NAR from cache.nixos.org, and `testdata/fuzz/` the inputs that failed a target once |
|
|
|
|
## How devvm runs it
|
|
|
|
`internal/cli/proxy.go` holds the hidden `devvm _proxy` and `devvm _proxy-child` commands. `devvm _proxy-child` hands its arguments to `ChildMain` with the same streams and files alone. `devvm _proxy` hands its arguments and the run's context, which `SIGTERM` ends, to `Main`, with the run UI's streams (`IO`: the event log and `-help` on its `Stdout`, the proxy's own log lines on its `Stderr`), the same streams as files for the child's own output (`IO.OutFile`, `IO.ErrFile`), devvm's own files (`IO.FS`, which is `assets.FS`, so the package never imports `assets`), the lookup of secrets' values (`IO.Secret`, which is `secrets.Store.Get`) and the capture of logins (`IO.Capture`, which is `netpolicy.Capturer`), so the package never imports `internal/secrets` or `internal/agentlogin`, and returns an error as its failure, in `proxy_failed`. The package itself prints nothing.
|
|
|
|
```text
|
|
devvm _proxy -config ~/.local/share/devvm/vms/<hash>/run/proxy.json
|
|
```
|
|
|
|
Flags take one dash or two. The proxy has one, `-config`, and everything it runs with is in that file, `Config` as JSON, which `netpolicy.Proxy` writes for a VM's proxy and `backend.ProxyStarter` for a build's, each whole (`Encode`), mode 600, before it starts the proxy. The file holds the VM's password and the company proxy's credentials, which is why none of it is in the arguments: a process's arguments are visible to other users. `ReadConfig` reads it once, as the proxy starts: a regular file, not a symbolic link, owned by the proxy's user and readable and writable by nobody else, at most 1 MiB, of `ConfigVersion` (`"version": 1`), with no field `Config` lacks (`DisallowUnknownFields`), with a password, a loopback `listen` address, `ca` and `ca_key` together and a `nix_cache_max` of at least 0. Anything else is an error, and the proxy never listens. A running VM's proxy starts again when the config devvm would start it with has another `Sum`, the SHA-256 of its encoding.
|
|
|
|
| Field | What |
|
|
| --- | --- |
|
|
| `version` | `ConfigVersion`, 1: a file of another isn't read |
|
|
| `listen` | the VM's proxy port, on loopback; port 0 for any free one (a build's) |
|
|
| `vm` | the VM's name, for the log |
|
|
| `password` | the VM's key: requests need it as the proxy password, user `devvm` |
|
|
| `builtin_policies` | devvm's built-in policies, paths in `IO.FS` (`layers/base.policy`, `shared-tools/node.policy`), in order: read once as the proxy starts, ahead of `policies`, and never again; one that's missing, or holds a line that isn't a rule, is devvm's bug, so `Main` returns an error and the proxy never listens |
|
|
| `policies` | the user's policy files, in order, each re-read when it changes; a missing file has no rules |
|
|
| `deny_policies` | policy files after `policies`, read as they are, whose denies alone apply: their allows are dropped as they're read, and a broken deny still refuses everything (the internet and none tiers' user files) |
|
|
| `open` | every host and address on every port, internal ones and this machine's included: no rule or floor applies, and a name the host can't resolve goes to `upstream` unjudged; refused together with any policy (an open VM's) |
|
|
| `log` | the JSON-lines event log, mode 600, rotated past 10 MiB; none: stdout |
|
|
| `proxy_log` | the file the proxy's stderr appends to (devvm opens it for the process): the proxy's own log lines, and its HTTP servers' errors, go through it and rotate past 10 MiB by copying, so the last error, written to stderr after `Main` returns, reaches the current file |
|
|
| `lifeline` | the hostagent's pid file (`daemon.Lifeline`): wait up to 15 minutes for it to name a process that runs, past what it held when the proxy started, and return once it no longer holds what it held then or that process is gone |
|
|
| `ca`, `ca_key` | the VM's own CA, for interception |
|
|
| `ca_next`, `ca_next_key` | with `ca`: the VM's next CA, which signs from an hour after its start; the VM trusts it too |
|
|
| `secrets` | the VM's bindings file, `BindingList` (no values), re-read when it changes ([secrets](#secrets)); `Main` refuses it without `IO.Secret` |
|
|
| `captures` | agents' OAuth token endpoints (`Capture`: `agent`, `host`, `path`), which `agentlogin.Endpoints` lists for every VM: their logins are captured ([capturing logins](#capturing-logins)); refused without `ca`, or with an entry without an agent, a host name or a clean path, and `Main` refuses them without `IO.Capture` |
|
|
| `upstream_cas` | CA certificates (PEM) the proxy's own TLS connections trust besides the system's: the user's |
|
|
| `upstream` | the host's `HTTPS_PROXY`, `HTTP_PROXY` and `NO_PROXY` (`https`, `http`, `no_proxy`): allowed requests go through that company proxy, which gets host names, and its credentials only in its own `Proxy-Authorization`; logs name it by `host:port` |
|
|
| `upstream_unresolved` | with `upstream`: names the host can't resolve go there even when only `**` allows them (a build's, which reaches internal addresses anyway) |
|
|
| `nix_cache` | the shared Nix cache's folder (`~/.local/share/devvm/cache/nix-cache`), made mode 700 if it isn't there: serve `http://devvm.proxy/nix/` from it; devvm sets it for VMs whose image has the nix layer |
|
|
| `nix_cache_max` | with `nix_cache`: the cache's cap, in bytes (devvm sets `nix-cache.size`, 10 GiB when it's off; none: `NixCacheDefault`) |
|
|
| `links` | the VM's links' list, which `devvm _links` writes (`~/.local/share/devvm/vms/<hash>/run/links.json`): reach each link through its socket, before any rule; a missing list has no links |
|
|
| `link_sockets` | with `links`: the folder of the links' sockets, devvm's run folder (`~/.local/share/devvm/run`); without it, no link is reached |
|
|
| `vm_logs` | the logs the VM's backend writes as the VM runs, which the VM can drive, such as its serial console's. The proxy, which runs as long as the VM, holds each to its cap through `IO.KeepLogs`, which devvm sets to `vmlog.KeepVM`, and `vm_logs` needs it set |
|
|
| `agent`, `agent_socket` | together, absolute: the SSH agent the VM's start forwards, your own or devvm's, and the VM's own socket in devvm's run folder (`~/.local/share/devvm/run/agent-<hash>.sock`) that the proxy relays it on, which the VM's backend forwards instead ([the SSH agent's relay](#the-ssh-agents-relay)). devvm keeps a running VM's as its start set them |
|
|
| `devvm_sha256`, `ca_sha256`, `ca_next_sha256` | the SHA-256 of the devvm binary, of the VM's CA certificate and of its next one's: not read by the proxy, there so a new binary or CA changes the config's `Sum` and devvm starts the proxy again |
|
|
|
|
Running the proxy is `Main`'s only mode. What only the host does for network policy runs in devvm itself, never through the proxy's arguments: `trust.InitCA` readies the VM's own CA and its next one in the VM's `run/ca/` (`ca.pem` and `ca.key`, `next.pem` and `next.key`, each written whole; each valid 30 days; no host name in them), and the proxy signs with the next one from an hour after its start, and `internal/agentlogin` makes the VM's copies of agents' login and settings files, their bindings and their values.
|
|
|
|
## The SSH agent's relay
|
|
|
|
With `agent`, the proxy relays the VM's SSH agent before it says it's ready. It removes a socket that an earlier proxy left at `agent_socket`, listens there, mode 600, and removes the socket when it returns. OpenSSH's `ssh-agent` answers every request a forwarded connection sends, so a VM with the agent's own socket could remove every key (`ssh-add -D`), lock the agent with a password of its own (`ssh-add -x`) or add keys without bound, for you and every other VM that uses it. For each connection, the relay reads each request whole, its length first, at most 256 KiB (`agentMsgMax`, OpenSSH's `AGENT_MAX_LEN`), and passes on only `SSH_AGENTC_REQUEST_IDENTITIES` (11), `SSH_AGENTC_SIGN_REQUEST` (13) and the extension `[email protected]` (27), which ssh sends as it forwards the agent and as it logs in with it, so a key added with destination constraints keeps them. Those go to the agent over a connection of the client's own, made at its first such request, and the agent's answer, read whole the same way, goes back. It answers any other request with `SSH_AGENT_FAILURE` (5) itself, so the agent never sees it, and logs the first such request on each connection in its own log. A longer message, or one either side cuts short, ends the connection. It carries at most 16 connections at once (`agentConnsMax`), a cap of each VM's own, not the agent's, and closes any past them. After an accept error that leaves its listener open, such as running out of files, it waits 5 ms and then twice as long each time, up to a second, logging only the first error, as devvm's other accept loops do (`daemon.AcceptRetry`). It closes a connection that sends no whole request within 2 minutes (`agentIdle`), but a request the agent asks you about (`ssh-add -c`) waits on the agent's side, with no limit.
|
|
|
|
## The server
|
|
|
|
Everything a proxy runs with, and everything it keeps between connections, is in the child's `server`, which `newChildServer` makes from the start its broker sends it, asking the broker for what only the broker has (`hostSide`). The package keeps no state of its own: its only package-level variables are error sentinels and fixed tables (`notPublic`, `withIPv4`, `githubMinting`), which the structure test allows. The server holds the VM's name and password, its own log, and these parts, each of which keeps what it changes under a lock of its own:
|
|
|
|
- `events`: the event log and the last 50 blocks, for `/blocked` and `/blocked/new`;
|
|
- `egress`: the policy (`policy`, which reads the user's files again when they change), the host's own addresses (`hostAddrs`, read again every 30 seconds) and the company proxy (`upstreams`, set as the proxy starts and only read after);
|
|
- `secrets`: the bindings file, read again when it changes, and the values the broker gave for them, held through each request for one so those go one at a time;
|
|
- `ca`: the VM's CA, its next one, and the certificates the proxy has made with each;
|
|
- `links`: the links' list and their sockets' folder, which are only read;
|
|
- `nixCache`: the Nix cache's folder, which every proxy shares under its `.lock`, and the narinfos this proxy has checked and the NARs it's fetching.
|
|
|
|
A test makes a server of its own with `newServer` (`inprocess_test.go`), a broker and its child's server in the test's process with no socket between them, and sets on it whatever else it needs, so no test changes another's proxy and the tests run in parallel.
|
|
|
|
## Secrets
|
|
|
|
The bindings file, `secrets.json` in the VM's run folder, is a `BindingList`: `{"version": 2, "bindings": [...]}`, which `secrets.Store` writes whole, mode 600, at each launch and again whenever a secret is saved, deleted, bound or unbound. Each `Binding` has its `name`, its `kind`, its `hosts`, its `header` and its `placeholder`, sometimes a `path` and `methods`, and never a value. Its kind says where the value comes from: `secret` is one that devvm keeps (`devvm secret set`), yours included, in the Keychain or in devvm's secrets folder, and `login` is one of an agent's logins, read from the login file of its `agent` (such as `codex`, `opencode`, `pi` or `claude`) on the host each time. The kind also says how the value goes in (`Binding.takes`), so the VM can't put the value where a server echoes it, or bytes of its own around it. A secret's placeholder is replaced only when exactly one value of its header holds it, and that value is the placeholder alone, or in `Authorization`, `Bearer`, `Token` or the binding's own `scheme` (never `Basic` or `Digest`: `SchemeOK`), one space and the placeholder, or `Basic` credentials whose password is the placeholder, or with `basic_user` whose username is (`secretValue`). A login's is replaced only when the header has one value that's the placeholder alone, or `Bearer`, one space and the placeholder in `Authorization`. A secret of yours' binding also carries its definition's `id`, which the lookup checks it against. A binding with a `path`, a pattern as a rule's is (`PathOK`), such as `/api/` for everything below `/api/`, or with `methods`, such as `GET,HEAD`, gets its value only for a request that they match, as it goes upstream, as a rule's allow matches it (`match.allows`): the path plain, clean, unencoded and without a backslash or `;`, and the method, and each method-override header, among the methods as written. Nothing about a binding is worked out from its name. The proxy reads the file with `ReadBindings` when its modification time changes: a regular file, not a symbolic link, owned by the proxy's user and readable and writable by nobody else, at most 1 MiB, of version 2, which a proxy that knows only version 1 refuses, so it puts no value in rather than put one in for every method, or of version 1 without methods or a `*` in a path, each binding of a kind it knows, and each `path` and `methods` one it takes. A file it can't read that way has no bindings until devvm writes it again, and the proxy logs why once. A change also drops every value it has cached.
|
|
|
|
The proxy looks a value up in its own process, through `IO.Secret`, which `devvm _proxy` sets to `secrets.Store.Get`, so no other devvm runs for it, and no value is in any process's arguments. On macOS the Keychain is still asked through `security find-generic-password`, whose output is the value, as when you save one. `Main` refuses a config with `secrets` and no `IO.Secret`. The lookup gets the binding itself, so the kind decides whether it's the Keychain, devvm's secrets folder or the agent's file (`agentlogin.File.Get`, which refreshes an OAuth login on the host when it's due, under the file's lock). Each lookup's context carries the route of the proxy's own company proxy, with its password (`WithRoute`), and a refresh goes through it (`RouteOf`), so it leaves the host the way the VM's requests do. The context also carries the proxy's own roots, the system's and `upstream_cas` (`WithRoots`), which a refresh trusts (`RootsOf`), so a company proxy that inspects TLS doesn't refuse it. A proxy without `upstream` gives a direct route. It runs for at most 20 seconds and one at a time, so two requests never refresh a login at once. The proxy keeps a value for 5 minutes, or for 30 seconds when its kind is `login`, by its binding's kind, agent and name together (`valueKey`), so a secret of yours and an agent's login never get each other's value, and it never logs it, and a lookup that fails or gives nothing puts nothing in and is logged, without a value, to the proxy's own log.
|
|
|
|
## Capturing logins
|
|
|
|
`captures` lists the token endpoints of the VM's agents, each an agent, a host and a path, such as Codex's and opencode's `auth.openai.com` and `/oauth/token`. The proxy intercepts a host that has one on `:443` as it does a host with a bound secret, with or without bindings, and forwards each request to it as it does any other. A `POST` whose path is an endpoint's, once it's cleaned (`path.Clean`), without its path parameters (`;x`) and in any case, is captured, for every agent whose endpoint it is, and goes to the endpoint's own path, without a query (`capturing.path`). The proxy reads its body whole, at most `captureRequestMax` (64 KiB), and hands it to `IO.Capture`'s `Request` in an `Exchange`, with the VM, the agents, its `User-Agent` and its `Content-Type`. The body `Request` returns is what goes out, or the answer it returns is the VM's reply, and the request goes nowhere. At most `captureReads` (8) requests and replies to and from the host are read whole at once. No `1xx` from the host reaches the VM (`no1xx`), and an upgrade (`101`) is refused. Every request to the host goes without the VM's `Accept-Encoding`, so Go's transport asks for gzip itself and undoes it. `ModifyResponse` (`captureResponse`) takes a successful reply (`2xx`) whole, at most `captureReplyMax` (1 MiB), and hands it to `Response`, which saves the login on the host and returns the reply the VM gets and whose login it was. The proxy sends the VM that reply alone, with its own `Content-Length` and only the headers that can't hold a credential (`keepHeaders`: `Content-Type`, `Cache-Control`, `Pragma` and `Date`), and logs a `login` event, which names the agent. An error reply reaches the VM as it is, unless `Request` changed the request's body, putting a real value in, when the VM gets only its OAuth error code (`errorReply`), in case the message quotes the request. Any other successful reply from the host, to a request that wasn't captured, is refused when it names an `access_token`, a `refresh_token` or an `id_token` anywhere, whatever its type (`guard`), so another path there can't hand the VM a login; a web page and its parts pass unread (`page`), and one guard can't read is refused. When `Response` returns a reply and an error, the login was saved, so the VM gets the reply and the error goes to the proxy's own log. A request or a reply that's too long, a reply with a `Content-Encoding`, or one that `Request` or `Response` refuses gets `502`, logged as a refused block, and why goes to the proxy's own log, which never holds a value from either: `Capturer`'s errors name none. Each call gets the lookup's 20 seconds, and the request's end doesn't cancel it, because the endpoint may already have replaced the refresh token.
|
|
|
|
`agentlogin.Endpoints` lists Codex's and opencode's endpoint and Claude Code's two, `platform.claude.com` and `console.anthropic.com` with `/v1/oauth/token`, for every VM, whatever its image holds. `netpolicy.Capturer` is `devvm _proxy`'s `IO.Capture`: it reads the VM's state for its salt, picks the agent, the image's when it has one of the endpoint's, else by `User-Agent` (`agentlogin.Pick`), and has `secrets.Store`'s `CaptureRequest` and `Capture` read and write the store's login file through `agentlogin.File`, or for `claude setup-token`'s token the `claude` secret, then writes the VM's bindings again, which the proxy reads at its next request.
|
|
|
|
Inside the VM, `http://devvm.proxy/blocked` lists recent blocks, `/blocked/new` those since the last prompt, `/ca.pem` serves the VM's CA certificate and the next one's, and with `nix_cache`, `/nix/` is the shared Nix cache.
|
|
|
|
## Testing
|
|
|
|
`go test ./internal/proxy` runs the unit tests, in parallel, each with a server of its own ([the server](#the-server)), and the fuzz targets' seeds; `go test -fuzz FuzzRequest ./internal/proxy` fuzzes one. `testdata/script/proxy.txtar` runs `devvm _proxy` itself and checks that it refuses any flag but `-config`. `nix_cache.txtar` runs it with a config of its own. `internal/agentlogin` and `internal/trust` have the tests of the logins, the redaction and the CA, and `internal/secrets` those of `Store.Get`, the lookup `IO.Secret` runs; the proxy's own tests give it a fake one. `internal/agentlogin` has the tests of each agent's capture, and `internal/netpolicy` those of `Capturer`; the proxy's own give it a fake `IO.Capture` and a fake token endpoint (`capture_test.go`).
|