mirror of
https://github.com/devvmhq/devvm.git
synced 2026-12-01 06:23:17 -10:00
main
61
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
47593e21ab |
fix(proxy): NormHost keeps an address's trailing dot, its IPv6 zone's, and Public calls no zoned address the internet's
NormHost dropped one trailing dot from any host, so an IPv6 address whose zone is "." (::1%.) became ::1%, an empty zone, which netip reads as no address. The proxy refused both forms (HostOK), but a partial clone's promisor warning (privateHost) no longer saw ::1%. as private, as FuzzPromisorHostSite found. NormHost now leaves an address as it is, its dot included, so every judge reads such a host as the zoned address it is. Public now calls no address with a zone the internet's: netip's prefixes never contain a zoned address, so the ranges alone missed, for example, a zoned documentation address, which --from's registry check took as public. No VM could reach anything through such a host: every way in (CONNECT, absolute-form requests, a transparent connection's Host and its TLS server name) refused it with 400 before any lookup or connection, on every tier, the broker refuses a lookup of it and a connection to a zoned address, and no rule or NO_PROXY entry names one. Tests: TestZonedHostsRefused sends each zoned and empty-zone host through CONNECT, plain HTTP and the transparent path on the open, internet, allowlist, none and loopback-allowing tiers, checking each refusal is the proxy's own where net/http lets the request through, with a control on each path that [::1] itself reaches the dialer where allowed; it passed before the fix too, and fails when HostOK takes a zone. TestNormHost, TestBrokerLookup, TestBrokerDial, TestInternal and TestPublicAddr gain zoned cases; FuzzHostSites' splitSite and policySite list the new divergence (zoneDot), and FuzzPromisorHostSite lists a zoned address now counting as private; its crash input and the zoned-unspecified one ([::%[]:) are added. design.md's list of the host readers' differences names both. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
3da38436a7 |
feat(proxy): the broker opens the child's connections; its sandbox refuses it every one of its own
A sandbox fixed at the child's start can't tell this machine's loopback, its own addresses and the LAN apart from the internet as a rule changes, so the child's sandbox now refuses it every connection of its own, and the broker looks up each name and opens each connection for it, once its own read of the VM's policy and of the host's addresses allows the address, as the floor does. A child that a VM takes over reaches this machine's loopback, its own addresses and the private and link-local ranges only where a rule names the address, as the VM does; a company proxy, which the child still speaks to with its password, reaches whatever it reaches. - wire.go: lookup (a host name, absolute, with its trailing dot), dial (an address and a port, or the https or http company proxy of the broker's config, never both), the connection as the reply's one descriptor, and cancel, for a lookup or a dial the child gave up on, which frees its slot. - dial.go: the broker's own egress (newBrokerNet: the VM's built-in policies, its policy files, looked at on every dial, and the host's addresses), lookupable, broker.lookup, dial and dialProxy, within 20 s and 15 s; the child's side (brokerClient.lookup, dial, dialProxy) wired into its egress by throughHost; the resolver's errors as codes the child makes into net.DNSError again. - broker.go: the caps (256 lookups, 1024 connections at once); its line for each failed lookup and connection, which the VM drives, at most 20 a minute and then one that says it stops (logFailed, perMinute in limits.go, which egress.abandoned now shares). - child.go and confine.go: every lookup and connection through the broker; the child lowers its open files, soft and hard, before it's confined (limitFiles). - seatbelt: the child's profile allows no network out, TCP, UDP or a unix socket, nor mDNSResponder. - landlock: the seccomp filter refuses every socket but a netlink route socket, connect, socketpair, listen and MSG_FASTOPEN on sendto, sendmsg and sendmmsg; Landlock no longer opens the resolver's files below /etc. - Tests: the broker's dial and its rules (TestBrokerDial, TestBrokerDialFollowsRules, TestBrokerDialProxy), lookups and their errors, cancel, the client over a real socketpair, TestBrokerFailedLogCapped, TestPerMinute, the filter's programs, the child's own connections refused under Seatbelt and under Landlock and seccomp. - Docs: the design note's broker (what crosses to the broker: the names and addresses, never a connection's bytes), its threat check, network's The child's sandbox and proxy.log, processes, attack vectors, troubleshooting, testing, tests, the proxy's README; CHANGELOG, with the company proxy's reach. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
1793353dd9 |
feat(proxy): Linux confines the proxy's child with Landlock and seccomp
Before it reads a byte of the VM's, devvm _proxy-child confines every thread of itself through proxy.confineSelf on Linux: no_new_privs (syscall.AllThreadsSyscall), Landlock from ABI 2 (TSYNC from ABI 8) to its logs folder, the Nix cache and the resolver's files (never /, the home folder or one that holds it), binding no TCP port (ABI 4), scoping signals and abstract sockets (ABI 6, or ABI 6/7 with erratum 2), refusing named unix sockets (ABI 9) and UDP but to port 53 (ABI 10); then a hand-written classic BPF seccomp filter, installed with TSYNC, that refuses with EPERM AF_UNIX socket/socketpair, listen, io_uring, ptrace, process_vm_readv/writev, pidfd_getfd, a file's mode, owner, xattrs and times by its path (chmod, fchmodat, fchmodat2, chown, lchown, fchownat, the six xattr calls, utime, utimes, futimesat, utimensat with a path), truncate, the keyrings (add_key, request_key, keyctl), prlimit64 on any pid but 0, setpriority, ioprio_set, sched_setaffinity, sched_setscheduler, sched_setparam, sched_setattr, inotify_init, inotify_init1, inotify_add_watch, fanotify_init, fanotify_mark, execve, execveat, fork, vfork, unshare, setns, bpf, userfaultfd, perf_event_open, clone for anything but a thread or with a namespace's flag, and clone3 with ENOSYS; it kills a foreign architecture's call or an x32 number. fchmod, fchown, ftruncate and utimensat on a descriptor stay. It checks the confinement holds, then proxy.checkConfined, and that it still reads the host's addresses, within 2 seconds, or fails the start. A kernel without Landlock or seccomp leaves that part out; the child runs and says so. The broker sets itself undumpable (PR_SET_DUMPABLE 0). The Nix cache marks a file used through its descriptor. The broker's start, and its life with the child, take a reset of the socket (ECONNRESET, Linux's end of a socket closed with frames unread) as the child's end, as EOF is (socketEnded, TestHandshakeChildGone). Built on the Seatbelt item's shared owner, proxy.Confinement: - internal/landlock (new, stdlib only, Linux build tags): Self, Result, Floor, ABIPorts/ABISignals/ABIUnix, ErrUnsupported; landlock_linux.go (resolverFolders, refusedFolder, homeFolder), filter_linux.go (filter, asm, encode, archOf), seccomp_linux.go, self_linux.go (Self, check, refused). - internal/proxy: confineSelf on Linux calls landlock.Self; landlockConfinement words it (By landlock, seccomp; Why no-landlock-or-seccomp, no-landlock, no-seccomp, landlock-below-abi4, landlock-signals; full from ABI 6 with seccomp and scoped signals); confineChild takes the child's needs and returns an error, bounded by confineWait (within, confineWith); checkConfined only where Landlock or Seatbelt confines files; confineStarted; IO.confine required, set by ChildMain alone; hostAddrs.check; touch_linux.go and touch_other.go (touchFile, undumpable); IO.dumpable for tests. - devvm doctor: netpolicy.Unconfined's Linux warnings (proxy_unconfined_no_kernel, _no_landlock, _no_seccomp, _old_ports, _old_signals). - Tests: TestFilter and TestFilterBytes (an interpreter of the program's bytes, amd64 and arm64, and the assembler's refusals), TestSelf (a real confined child: outside file, ssh-like unix socket, listen, bind, signal, chmod, chown, setxattr, utimes, truncate, a keyring, unshare, exec, clone3, and new threads, fchmod, ftruncate and futimens kept), TestKernel, TestCheck, TestRights (refusedFolder), TestArchNumbers, TestLandlockConfinement, TestConfineWithin, TestCheckConfined, TestConfineStarted, TestRunChildOn, TestUnconfined; network.txtar; e2e network's Landlock, NoNewPrivs and Seccomp check. - CI: a nocgo job (CGO_ENABLED=0) for internal/landlock and internal/proxy. - Structure test, depguard, goroutineSites; docs: the child's sandbox, processes (and its why-Go note on unsafe), design (the network row's loopback follow-up on Linux, other processes and /proc without Landlock), doctor's checks, troubleshooting, attack vectors, Contributing, the proxy's README, AGENTS.md, CHANGELOG. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
aeea3135b2 |
feat(proxy): the proxy's broker and its child
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]>
|
||
|
|
9c74dac11e |
fix(logs): a VM's logs are held to their caps while it runs
internal/vmlog owns every log a VM can drive but the proxy's own: Limit (moved from vmssh's logLimit, with Allow for the link session's warnings), Capped and Trim for ports.log and links.log while they run, and KeepVM, which the VM's proxy (proxy.IO.KeepLogs, Config.VMLogs from backend.Run.Logs) and a Lima build run on the serial consoles' and the hostagent's logs: redacted as they grow (redact.FileFrom), so a reboot in place can't leave the proxy password there, and rotated past 10 MiB, counting what a log holds past the hole its writer left (platform.DataStart). The proxy's http.Server logs through its own limited log, and its copied log counts what reached it as stderr; the build proxy's log is held as a VM's proxy's is. git-pins.jsonl has a cap. Run logs take at most 256 MiB together, never the newest or a live run's. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
19f9900b86 |
fix(sshagent): a VM reaches its SSH agent only through its proxy's relay
OpenSSH's ssh-agent answers every request a forwarded connection sends, so a VM that forwarded your agent or devvm's own (shared by every VM that uses it) could remove all its keys (ssh-add -D), lock it with a password of its own (ssh-add -x) or add keys without bound, denying the agent to you and to the other VMs. Checked with a throwaway sshd and ssh-agent: all three succeed over ssh -A. Each VM's proxy now relays the agent its start chose on a socket of the VM's own (paths.Dirs.AgentRelay, run/agent-<hash>.sock, mode 600), and the VM's backend, devvm's own connections and the ssh entries for editors name that socket. The relay passes on only SSH_AGENTC_REQUEST_IDENTITIES, SSH_AGENTC_SIGN_REQUEST and the [email protected] extension (so destination-constrained keys keep their constraints), answers everything else with SSH_AGENT_FAILURE, reads messages whole up to OpenSSH's 256 KiB, carries at most 16 connections and closes one idle for 2 minutes. A filtering relay rather than an agent per VM: it covers your own agent too, needs no copy of a key or a passphrase per VM, and fronts hardware and app-held keys. - proxy: Config.Agent/AgentSocket (checked together, absolute), the relay in agent.go, listened before the proxy says it's ready; its accept loop backs off after an error that leaves the listener open (EMFILE), 5 ms doubling to 1 s, logging the first. - daemon: AcceptRetry, vmssh's acceptRetry moved to the stdlib-only package the proxy already imports, so the relay, the port forwarder, the link session and a login's forward share one owner. - netpolicy: Prepare takes a start's agent; a running VM's proxy keeps its start's agent from proxy.json (relayedAgent); Stop deletes the relay's socket. - structure: paths.Dirs may have 62 methods (AgentRelay); the relay's goroutines in goroutineSites. - sshagent: Made.Relayed, which RecordStart sets on every start of this devvm's whose choice forwards an agent, one without SSH_AUTH_SOCK included, and ReachOf(st, start): a relayed start gets the relay (or none while it's down), a start devvm didn't record (one outside devvm) gets none, or its proxy's relay, and only an older devvm's recorded start keeps the raw agent until its next start (runningConfinement, finder.inspect, sshconfig). - vm: LeftoverSockets also finds a killed proxy's relay socket for devvm gc --orphans and devvm space. - Tests: relay filter, wiring through Main, bounds and idle close, real ssh-agent/ssh-add/ssh-keygen through the relay, Prepare's relay, RecordStart/Relayed, sshconfig entries, vm agent tests, ssh_agent.txtar, an outside start in ssh_agent.txtar, and e2e checks that the VM can't remove, lock or add to your agent, nor the VM or an editor's connection remove devvm's agent's keys. - Docs: processes (the SSH agents, listeners), ssh, attack-vectors, security, design, lima, overview, space, structure, proxy README, AGENTS.md, CHANGELOG Fixed. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
f37c70a5cd |
fix(bounds): bound what a VM can make the host hold
Five bounds, each with a test that failed first. Long downloads,
WebSockets, slow streams and SSE are never cut: every bound is on what a
connection holds, never on how long it lasts.
- _qemu connect (Linux): each guest connection to the proxy was a host
process with no cap. Connect now takes one of connectMax (256) slots,
lock files in the VM's run/proxy.slots (paths.VM.Proxy(".slots")),
each process about 7.7 MB, so about 2 GB per hostile VM. A connection
past them gets an HTTP 503 (connectsFullReply) and closes before it
dials; QEMU's stderr says qemu_connects_full at most once a minute,
decided under full.lock so refusals at once say it once. A VM started
before keeps the two-argument form, unbounded until its next start.
No idle timeout or byte bound: the proxy bounds what each carries.
TestConnectSlots.
- The VM proxy (limits.go):
- maxConns (2048, twice maxConnects so a CONNECT still gets its 503
first) counts a connection from its first request with the VM's
password (conns.admit, via httpServer's ConnContext); a request past
it gets 503 and the connection closes. Connections without the
password wait in a pool of maxWaiting (128) where a new one closes
the oldest, so holding connections can't take a VM's room (a host-speed flood still slows it
through the accept queue: listed in design.md).
- maxRequests (2048) requests upstream at once, plain HTTP's and
intercepted tunnels' (requests.take), 503 past it: per-tunnel
HTTP/2 streams alone allowed ~100,000 upstream connections.
- each limit logs once a minute at most (everyMinute).
- httpServer adds IdleTimeout (10 min); a 407 closes its connection;
handleHTTP's WithoutCancel is replaced by whileHeard, which ends a
plain HTTP request once its client has stopped sending and goneWait
(1 min) passes with nothing written, so half-closing clients still
get answers that keep coming; quiet WebSockets aren't cut.
- heardWriter.Unwrap: plain ws:// upgrades got 502 (pre-existing) and
get 101.
- No ResponseHeaderTimeout: non-streaming LLM requests wait minutes
for headers, and a waiting client is counted.
Tests: TestProxyLimitsSet, TestProxyConnectionBounds,
TestProxyConnectionLimit, TestProxyWaitingConnections,
TestUpstreamRequestLimit, TestUpstreamRequestLimitIntercepted,
TestPlainWebSocket,
TestPlainHTTPEndsWithClient.
- serveOne (intercepted tunnels, transparent HTTP, the 403 page) takes
maxHeaderBytes (64 KiB) always, not 1 MiB, and HTTP/2
MaxConcurrentStreams streamsMax (100, not 250). TestServeOneHeaderLimit,
TestServeOneStreamsLimit.
- Accept loops (forwarder, link session, login forward) retried nothing
or at a fixed 100 ms: vmssh.acceptRetry backs off from 5 ms to 1 s and
logs the first error of a run, ending only when the listener closes or
ctx ends. TestAcceptRetry, TestForwarderAcceptRetries,
TestLinksAcceptRetries.
- The login callback (LoopbackForward) carries at most
loopbackConnsMax (16) connections, an ssh each.
TestForwardLoopbackLimit.
Docs: processes, network, ports, lima, design (threat rows),
attack-vectors, the proxy README, CHANGELOG Fixed.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
||
|
|
c872cfe66c |
fix(proxy): look names up absolute, so the host's DNS search domain never applies
The proxy looked up the checked name without a trailing dot, so the host's resolver added its search domain: with api.corp.example denied and ** allowing the rest, CONNECT api:443 (or api.eu, once api.eu itself had no address) reached api.corp.example. Validated on macOS (a CGO_ENABLED=0 darwin build resolves through libSystem's getaddrinfo, which applies scutil's search domain) and on Linux (Go's resolver applies resolv.conf's search, single- and multi-label names, at ndots 1 and 5). egress.lookupName now asks for host+".", for direct connections and the company proxy's floor alike. A block because an allowed name didn't resolve is now Refused: a rule allows the name already, so its 403, /blocked/new and devvm network log --blocked suggest no devvm network allow command. A name without a dot that has no address gets reasonShortName, which says to use the full name. Tests: TestLookupIgnoresSearchDomain, with a resolver that has a search domain; TestShortNameBlock; TestUnresolvedReason checks Refused and the short name. Docs: safety/network (inside the VM, the refused field), internals/network (the proxy, the reasons), internals/design (a company proxy and its own search domain, links' short names), using/troubleshooting (a name that doesn't resolve); CHANGELOG Fixed. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
1b8fd8a639 |
test(lifecycles): synctest bubbles for the relays, the forwarder, the links, the proxy and the daemon's stop
Timeouts, graces and closes are tested in testing/synctest bubbles on the
bubble's fake clock, to the moment, instead of sleeping and polling on the
real one, with stand-ins in memory behind seams that are fields. Each kind
keeps one real-process test. No behaviour change: each seam's production
value is what the code did before.
Seams:
- vmssh: sshRelay{grace, start} carries a relay (pipeSSH's body, as
pipeSSHFor was); start is execSSH in production.
- vmssh: Links.Listen (listenSocket unless set), for the links' sockets.
- proxy: egress.connect, the dialer for allowed far ends (a net.Dialer
with its 15 s timeout, set in newServer).
- daemon: Proc.Alive (Alive unless set).
- proxy: httpServer, the proxy's http.Server as run serves it, which the
tests' memServe shares.
New test-only package internal/memnet (standard library only): Pipe, whose
connections half-close, buffer 64 KiB and have deadlines, and Network,
listeners by address with Listen, Dial, DialContext and SetDeadline. The
structure test keeps it for tests and a leaf, depguard keeps it standard
library only, and its AfterFuncs are in goroutineSites.
Bubble tests:
- relay: TestRelayGrace (silent and talking, closed and half closed),
TestRelayGraceSlowClient, TestRelayGraceWriteError,
TestRelayCancelEndsBlockedWrite, TestGraceTimer (exact grace).
- forwarder: TestForwarder, TestForwarderAliveOnEnd, TestForwarderOnly,
TestForwarderGap (reports exactly Gap apart), TestForwarderGivesUpSilently,
TestForwarderClosesConnections (now also its stuck relay's ssh and slot).
- links: TestLinks, TestLinksSessionLost, TestLinksCap,
TestLinksEndStuckRelays (memSSH; relays end at the next sync on removal,
master replacement and target change), TestLinksList.
- proxy: TestTunnelHelloDeadline (EOF at exactly helloTimeout),
TestTunnelHelloStall (and a hello whole a moment before the deadline),
TestTunnelAddressSplitHello, TestConnectLimit, TestCloseConns,
TestCloseConnsWaitsBounded (close gives up at exactly closeWait),
TestSpliceEnds, TestSpliceEndsWhenItsClientCloses.
- secrets: TestSecretLookupFailuresNeverCached (hung lookups cut at
lookupTimeout, cancelled, failed and empty ones never cached; a request's
end doesn't cancel a lookup; the TTL to the moment).
- daemon: TestProcStopWaitsForTheEnd, TestProcStopKillsOnlyItsOwn,
TestProcStopKillsAfterWait (fakeProc), TestFollowLifeline.
- TestCursorReplyScans uses httptest.NewTestServer.
Kept on real processes and the real clock: TestPipeSSHGrace,
TestPipeSSHGraceSlowClient, TestPipeSSHGraceWriteError,
TestForwarderEndsStuckRelay, TestLinksBurst, TestSpliceKeepsAnEarlyAnswer,
TestProcStop.
Docs: Contributing's Tests has Time and lifecycles; structure.md, _index.md
and AGENTS.md name memnet.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
||
|
|
4d409589bb |
refactor(redact): every secret's value is a redact.Secret, revealed only where it's used
redact.Secret holds a value that lets whoever has it act as the user or
a VM, behind a pointer, so fmt's raw printing of an unexported field
shows only an address. String, GoString and Format print <redacted> for
every verb; MarshalJSON, UnmarshalJSON and MarshalText return
redact.ErrEncode, so a secret is never silently written as a stand-in
(which would lose a login); there's no LogValue. NewSecret ("" is the
zero Secret), Reveal, Empty and TrimSpace are the rest. internal/redact
joins the proxy's standard-library-only depguard group.
Reveal is refused by forbidigo outside tests; each of the 23 call sites
carries a //nolint:forbidigo saying why, and testdata/lint/forbidigo.go
keeps a call the rule must report. The structure test (checkSecrets)
refuses a struct that embeds redact.Secret outside internal/redact and
an interface that declares Reveal() string.
Typed now: proxy.Config.Password (configFile is the wire type, in
Config's order, held to it by TestConfigFile), the server's password,
proxy.Lookup and the cached values, upstream.auth, upstreamPassword,
Upstream.WithPassword's password; backend.NewProxyPassword, ProxyURL,
Confinement.ProxyPassword, BuildProxy.Password; netpolicy.Key and
NetMade.ProxyKey (netMade wire type); settings.CompanyProxy.Password;
secrets.Store.Value, saved, ProxyPassword, Token, Save, save, Get,
SaveKey, Yours.Save, Claude.Env, saveToken, oauthToken; agentlogin
File.Get, SetKey, ClaudeToken, every format's get, setKey and chatGPT,
refresh's refresh token, capture's access, refresh and id tokens, and
the JWT helpers (a login's map stays the wire, through token and
setToken; piKey is piBound); vm.Net.SecretSave, AgentLoginOptions.Key;
ui.UI.Secret. Strings by design: platform.KeychainGet/Set and the
desktop's VNC password.
Tests: TestSecret (unexported and nested fields too), TestConfigFile,
TestV010ProxyConfigs (0.1.0's proxy.json round-trips byte for byte),
TestFixtureStoreGet saves the Linux secret file back byte for byte,
checkV010Logins (login files read, copied and bound without a change),
secretCases, and e2e netNoLeaks, twice in the network section: every
VM's proxy password and the section's values, also as Basic
credentials, in no run log or proxy log, and the passwords in no
ha.stderr.log or serial log. Docs: Contributing's Secrets in the code,
the owners table, the secrets How it works page, design.md's Where
secret values live.
Fixed, found by netNoLeaks: Lima's boot script 07-etc-environment.sh
runs under set -x, so the console logs (serial*.log) kept the VM's
proxy password; redactLog now stars passwords in them as it does in
ha.stderr.log (CHANGELOG, overview, processes and attack-vectors pages).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
||
|
|
cc94465400 |
test(leaktest): goroutine leak checks, and the leaks they found
A new internal/leaktest, standard library only, so the proxy's and the daemon's tests use it too (depguard's proxy rule allows it, and the structure test holds it to tests and to importing nothing of devvm's): - leaktest.Main(m), in TestMain: once the tests pass, every goroutine's stack (runtime.Stack), a settle of 5 s, then a failure naming those still running, but the standard library's own that outlive every test (allowed: signal.Notify's loop, an HTTP client's idle connections); then Go 1.27's goroutineleak profile, which fails on any goroutine blocked for good. - leaktest.Check(t), first in a test: its own goroutines, followed by parent through those still running, and by which ran before it, never by ID (each thread takes a batch of IDs). Main runs in proxy, vmssh, daemon, desktop, ui, vm, backend/lima, platform, cli and gitprotect (main_test.go, or the TestMain they had). Check runs in TestLinksEndStuckRelays (replacing its NumGoroutine count), TestForwarder, the desktop relay's serve helper, TestRunChild, TestPinWaits, and the proxy's new close tests. The structure test's goroutines rule (internal/structure/goroutines_test.go): goroutineSites lists every function outside tests that starts a goroutine, with a go statement, a wait group's Go, or time's or context's AfterFunc, function literals in package-level vars included, as "file: Func", with its waiter, or "detached: " and why nothing waits. A new one fails until listed, a listed one that starts none fails, and a package that starts one fails until its tests call leaktest.Main. Leaks it found, each fixed with a test: - The proxy's close left its connections running: http.Server's Close neither closes a connection a handler took (a CONNECT's tunnel, a WebSocket upgrade ReverseProxy takes) nor waits for a handler. conns (conns.go) holds every connection the listener accepted (track) and counts every handler (handle); serve calls closeConns once Serve returns, which closes them, closes any accepted after, and waits up to 5 s for the handlers. splice also ends when its client's connection can't be read (closed, reset), rather than half-closing the far end and waiting on it; a failed write to the server (one that answered early and closed) still lets its answer through. Tests: TestCloseConns (a tunnel and an upgrade), TestConnectAfterClose, TestSpliceEndsWhenItsClientCloses, TestSpliceKeepsAnEarlyAnswer; the tests' listen closes as the proxy does, and the fake upstream closes its target once its client's end comes. - platform's runChild left its signal-passing goroutine blocked on a channel signal.Stop never closes; it now closes it and waits (TestRunChild). - platform's WaitExit and WatchFolders blocked in poll(2) and read(2), which closing their fd from the stop doesn't wake on every kernel (Debian's didn't), and a retried call could land on a reused fd. They now wait in Go's poller (pollable), which the stop wakes (TestPinWaits, with a wait stopped before its process ends). Docs: Contributing's tests page (Goroutine leaks), the structure page (the goroutines rule, goroutineSites, the layers, the packages), the Go lint rules' depguard line, the proxy's shutdown in How it works' processes page and the proxy's README, and AGENTS.md. Coverage baselines: internal/leaktest's line on both systems, netpolicy's raise on macOS. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
4e925492ca |
fix(proxy): every host is read in one form, proxy.NormHost, guarded by the structure test
Every check that judges or compares a host now reads it through proxy.NormHost (internal/proxy/host.go), which also holds HostOK, splitHostPort, hostASCII and asciiEqualFold: a host of printable ASCII is lowercased in ASCII alone and loses its one trailing dot; any other host stays as it is, so HostOK refuses it and no Unicode fold makes another name match. A host with two trailing dots or more, or a dot after a closing bracket, keeps them, so NormHost is idempotent and reading a host twice can't turn evil.test.. into evil.test. A proxy.Host is what the matchers take (rule.matchHost, noProxyRule.matches, local, sniMatches). Brackets are strict (hostAddr): HostOK, Host.Addr and splitHostPort take an address bare or an IPv6 address in one pair of brackets, never a stray bracket ([[::1]], 1.2.3.4]) or brackets around a name or an IPv4 address ([evil.com]:443, [1.2.3.4]:443), which get 400. Migrated: splitHostPort, sniMatches, sniHost, parseHostRule, the policy's rulesFor, quiet, byName and coversOn, secrets.forHost, parseNoProxy, route and local in internal/proxy; netpolicy.RiskOf, Tickable and sameRule (devvm network rm and the duplicate check, so a Kelvin sign never names the rule with a k); secrets.CheckHost; from.publicHost (a name HostOK refuses isn't public); agentlogin.claudeHost; vm.urlHostPort and privateHost. vm.urlHost (cloneseed.go) keeps its own reading: it's a remote's ssh host, which ssh lowercases and keeps the trailing dot of, to find a VM's alias. Differential fuzz targets keep a frozen copy of each reader as it was and allow only the decided differences: FuzzHostSites (proxy), FuzzRiskSites, FuzzCheckHostSite, FuzzPublicHostSite, FuzzClaudeHostSite and FuzzPromisorHostSite. A rule line is the same rule or no rule exactly as before, so a broken deny stays a broken deny. TestFixtureHosts reads the frozen v0.1.0 state's secrets.policy, secrets.json and links.json hosts and finds them unchanged. The structure test's new hosts check refuses, outside host.go and tests: Trim, TrimLeft or TrimRight with a cutset holding ".", TrimSuffix or CutSuffix with "."; ToLower, ToUpper, EqualFold and the TrimFunc family on an argument named for a host; and a conversion to proxy.Host of anything but a literal. Exceptions are by file and function, each with why (request.go:trimDots, cloneseed.go:urlHost, cloneworktree.go:safeIndexPath, cloneconfig.go:transportHelper, lima/start.go:machines.fillPassword). It doesn't see slicing, strings.Map or variables not named for a host. The owners doc, the proxy README, structure.md, design.md (One form of a host), network.md and safety/network.md say so. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
b6954e1e11 |
refactor(vmname): a VM's name is a vmname.VM, parsed where it's read
vmname.VM is the name of every machine devvm runs on a backend: a project VM, an image's machine (devvm-img-<key>), a build VM and a remake's aside. Fields, parameters, results and map keys that held a VM's name as a string now hold a VM, from the backend interface down to the CLI's --json structs, whose output is byte for byte the same. Boundary parsers, the only places a string becomes a VM: - vmname.Parse: a project VM's name (state's vm.json name, export file names, devvm _links's argument, the forwarder's -vm, project.Nth) - vmname.ParseListed: one path element, for what a backend lists - VM.UnmarshalText: JSON (Lima's list, proxy config and events, links' targets in state, link lists); empty stays no VM - vmname.Image(key), VM.Aside(), and typed constants for Lima's build VMs - msg.M.VM: the VM a message's function took, read back vmname's functions on names became methods (Hash, Slug, Short, Aside, AsideHash, ImageKey, IsProject); Lima's image prefix moved to vmname; vmname.Join joins VM lists. Messages' vm and vm_name fields are typed by the generator. Seven messages whose field took something else became what= (backend_lacks, backend_unreviewed, backend_unreviewed_used, starting, deleting, configuring, running_script) and rm_vm_failed's name=: the text is unchanged, the names-mode scripts follow. Review.RequireFor names an image or the tools being built. Typed sites per package (added lines with vmname.VM, non-test): msg 347 (generated), vm 124, lima 48, backendtest 32, vmssh 31, netpolicy 22, backend 16, gitprotect 14, proxy 11, cli 11, project 10, state 8, ports 6, paths 3, sshagent 2, sshconfig 2, tools 2. The structure test's owners rule now fails on a field, parameter or result named for a VM (vm, vms, otherVM, vmName) typed string, []string or map[string]…, and on converting anything but a literal to vmname.VM outside the files it lists; internal/stubtest is free. depguard holds internal/vmname to the standard library, and the proxy may import it. ParseListed and UnmarshalText refuse a name starting with -, which would read as a flag in limactl's argv, and vmname.Image refuses a key that's empty, holds a / or NUL, or makes a project VM's name, so Lima's ImageSize and DeleteImage no longer check it themselves. The check also fails on a *string VM name and an alias of vmname.VM, and says what it doesn't see. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
02ba74e614 |
build(lint): stricter linters, and the fixes they need
golangci-lint now also runs govet's nilness, unusedwrite, hostport and waitgroup analyzers, nilnesserr, durationcheck, canonicalheader, errchkjson, forcetypeassert, contextcheck and gochecksumtype. - errchkjson checks each JSON encoding's error where the value could fail and drops it where errchkjson proves it can't, and reports structs without exported fields; tests may drop theirs. - forcetypeassert holds the code; tests are exempt. - gochecksumtype: agentlogin's format is a sum type (//sumtype:decl), and a switch on one names every case, default or not. - canonicalheader: WWW-Authenticate, X-Request-ID, X-Api-Key. - contextcheck: ctx threaded through carry, peekClientHello and sniOf, and through inject and value, whose cached lookup takes WithTimeout(WithoutCancel(ctx)), so two forbidigo nolints go; openTransparent takes its dialer's ctx. nolints stay where contextcheck can't follow: ReverseProxy's Rewrite, WithoutCancel alone, cobra's cmd.Context, e2e's runner window. - No-behaviour fixes: scrubList for redact's list, the loopback forward's ports kept with its listeners, upgradetest's Key keeps its public key, a CA's leaves read through leafOf. Contributing's Go lint rules lists each one and the sum-type convention. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
5d7f941678 |
feat(network): quiet hosts: documented telemetry stays blocked without a notice in the VM
A built-in policy's `quiet HOST[:PORT]` line, for one exact host name, marks a host devvm leaves out on purpose. A quiet host is blocked as any host no rule allows, and an allow of the user's still lifts it. A block is quiet only when its reason is "not on the allowlist" (notAllowed), it isn't refused, and no rule covers the host (an allow, a deny or one that narrows): then it's logged with "quiet": true but never counted in /blocked or /blocked/new, so neither the VM's prompt nor devvm-why shows it, its 403 page suggests no command, devvm network log --blocked shows it as a row of its own with "- (quiet)", and devvm network lock never offers it. - proxy: rule.quiet, parseQuiet (exact hosts only), PolicyLine.Quiet, policy.quiet, Allowlist.Quiet, Event.Quiet, server.blocked (proxy and transparent paths), notAllowed; loadPolicy skips and logs quiet lines in the user's files. - netpolicy: Judge.Quiet, Block.Quiet (its own row key), FormatEvent's ", quiet", RuleFile.Quiet, quietMark, policy_quiet_not_own in PolicyWarnings. - cli: quiet in network log --json, log --blocked --json and network --json; the agents' table leaves quiet lines out. - Quiet hosts, each with its source: api3.cursor.sh (the host Cursor documents for Tab requests; Cursor's CLI uses it for its metrics) and telemetry.go.dev (Go). Not marked: Claude Code's Datadog intakes (shared multi-tenant hosts projects may need), .NET's telemetry (no host in Microsoft's docs). - Tests: TestParseQuiet, TestQuietHosts, TestQuietOnlyWhenNoRuleAllows, learn/log/rules tests, network_rules.txtar, e2e network check for api3.cursor.sh. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
99f57d4003 |
fix(proxy): 6to4 judged by its IPv4 address, and more special ranges internal
A 6to4 address (2002::/16) passed the floor as public even when the IPv4 address in it was private, and Teredo, IPv6's documentation, discard-only, benchmarking, ORCHID, SRv6 and IPv4-translated ranges, and IPv4's documentation ranges and 192.88.99.0/24, counted as the internet. - withIPv4 (was nat64): the IPv6 ranges that carry an IPv4 address, NAT64's and 6to4's, each with its site's prefix length (6to4's /48); embeddedIPv4 (was nat64IPv4) reads either. - hostAddrs.internal: the host's own address first, then the 6to4 site of any of its own addresses (its LAN's), then the embedded IPv4 address; hostAddrs.own, the address map, replaces has. - rule.matchAddr: a 6to4 address matches as its IPv4 address for a deny alone, as 6to4 goes through relays anyone may run; NAT64 still matches for both. - notPublic gains 2001::/32, 2001:db8::/32, 3fff::/20, 100::/64, 2001:2::/48, 2001:10::/28, 2001:20::/28, 5f00::/16, ::ffff:0:0:0/96, 192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24 and 192.88.99.0/24. - Tests: TestInternal's rows, TestInternalOwn6to4, TestSixToFourAllowsNot, TestResolveSixToFourName, a 6to4 deny in TestAddressDenyAppliesToNames; the learning tests' public address is 93.184.215.14 now, as 203.0.113.5 is documentation's. - The structure test's table name, the proxy's README, network.md's range list (with Teredo under a broad IPv6 allow), attack-vectors and safety/network, and a CHANGELOG Fixed entry. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
09c5be1887 |
fix(proxy): a block for a name that doesn't resolve says why
A name the host's DNS couldn't resolve was blocked with "can't resolve it"
whatever the cause, and a request whose client went away mid-lookup was
logged as a block too, so a cancelled lookup looked like a DNS failure.
- egress.lookup: the resolver, a field tests set (net.DefaultResolver's
LookupNetIP otherwise); resolve and floorUpstream go through lookupName,
which asks once more after a temporary failure (not a not-found), within
floorUpstream's 3 s.
- unresolvedReason: reasonNotFound ("this machine's DNS has no address for
it"), reasonDNSTimeout, else reasonUnresolvable; the error itself stays
in proxy.log, as before.
- floorCheck: a lookup that ended with the request's context gives
reasonClientLeft; events.record drops a block with it, so /blocked and
the counts never see it, and egress.abandoned names it in proxy.log,
at most abandonedLogMax (20) a minute, as a name can carry data out.
The Nix cache's floor gives the context's error for it.
- Tests: TestUnresolvedReason, TestCanceledLookupNotBlocked,
TestCanceledLookupsLogCapped, TestFloorUpstreamLookupBudget;
TestUpstreamNoProxyDirect no longer needs the real resolver.
- network.md's log files and a CHANGELOG Fixed entry.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
||
|
|
647ad4bf2a |
feat(network): transparent mode for tools that ignore the proxy settings
On every confined tier, a tool that ignores the proxy settings (workerd
under wrangler dev, a static Go binary, a container made through Docker's
API) reaches the VM's proxy by the names it looks up. In the VM, dnsmasq
answers every name with the stand-in address 198.18.0.1 and has no
upstream; nftables sends that address's ports 80, 443 and those the allow
rules name to socat listeners on it, which make each an authenticated
CONNECT transparent.devvm.proxy:PORT to the VM's proxy. The proxy reads the
host from the connection's first bytes (TLS SNI, or each HTTP request's
Host) and judges it as CONNECT host:PORT, with the same order of checks,
log, secrets and floor. A blocked HTTPS host gets the 403 over a
certificate from the VM's CA. Nothing new runs on the host, and the
backends don't change.
Proxy (internal/proxy):
- transparent.go: TransparentHost, ProxyDomain, SentinelAddr,
IsSentinelAddr, ViaDNS, transparent (serve, take, tls, handler,
refusePage, ports), sniHost, replay, reservedRefusal, withVia, viaOf.
- routeFor and route: the one order of checks for CONNECT and the
transparent path; carry, the one tunnel with its SNI check; block split
into the record and blockPage; links.refuse split (isLinkDomain);
caEndedRefusal's test moved to routeFor; handshake and serveOne shared
by intercept and the 403 page.
- devvm.proxy reserved whole, CONNECT devvm.proxy:P included; the stand-in
address refused with its own reason.
- Hosts and SNI in ASCII alone, never folded (the Kelvin sign), in
splitHostPort, sniMatches and sniHost.
- A ClientHello record past 16 KiB + 256 is never read; once it starts,
a ClientHello must arrive whole within 10 s, on every tunnel; a stream
whose first byte is 0x16 is TLS from then on, so a record header that
doesn't come whole, or isn't TLS's version, is refused, never passed on
unchecked; and only a ClientHello that parsed (sniOf) counts, so one
split across records is refused, an address's tunnel's included, which
may have no name (a gap older than this change).
- routeFor carries the method and path rules: a host they narrow is
refused where it can't be decrypted and intercepted where it can, on
the transparent path too.
- On the transparent HTTP path, devvm.proxy answers /blocked alone.
- policy.transparentPorts and /transparent/ports: 80, 443, then the ports
allow rules name for hosts by name, at most 32, never 22 or 53.
- Event.Via ("dns"), shown in devvm network log, /blocked and the prompt's
note as "without proxy settings".
Guest (assets/): base.sh installs dnsmasq(-base), socat and nftables;
guest/transparent.sh is devvm-transparent: setup and teardown from
sync.sh (the proxy URL on stdin), the supervisor service (systemd or
OpenRC), the ruleset (render: two filter chains at -150 keep every
interface but lo and Docker's bridges, and every protocol but TCP, UDP
and ICMP, off the stand-in address; both NAT chains at -110 map every port of
the stand-in address, so Docker's published ports never take one; DNS to
public servers and 127.0.0.1:53 go to dnsmasq, which listens on the
stand-in address alone; private, link-local, CGNAT and loopback servers
are left alone, but the VM's own name servers, which Lima's DHCP adds
beside 127.0.0.1 and Docker gives containers, go to dnsmasq too), slots,
the port list's check, and status for devvm-why. Names without a dot and
names under the search domains (this machine's network's, through Lima)
don't resolve.
Setting: config.toml's transparent-proxy, and devvm network transparent
[on|off], the VM's own value in net.transparent (Settings.Transparent,
SetTransparent; netpolicy.TransparentOf, TransparentAddr); the setup gets
DEVVM_TRANSPARENT_ADDR while the VM runs confined and its mode is on.
devvm network --json has transparent; devvm network lock lists apart the
hosts only tools without proxy settings reached (Learned.NoProxy, via in
--json). vmssh.dialAddr refuses the stand-in address.
Tests: the transparent path's unit tests and FuzzTransparent; the
setting, TransparentOf, FormatEvent's via and learned hosts; the ruleset,
slots and port list under bash 3.2; network_transparent.txtar and
sync.txtar; e2e: transparentRuns, the network section's checks, a docker
step, the from section's Debian 12 and Alpine on the allowlist tier, and
the guarantee checks run with transparent mode stopped and running.
Docs: safety/network.md (tools that ignore the proxy, what isn't
covered, the setting, logs, lock), internals/network.md (tools that skip
the proxy), internals/design.md (the design note and threat check),
using/settings.md, using/troubleshooting.md, using/limits.md,
using/images.md, safety/attack-vectors.md, internals/lima.md,
contributing/tests.md and testing.md, the proxy's README, the CLI
reference and the Commands page.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
||
|
|
01e5d2488a |
feat(network): rules by HTTP method and path, and secrets by method
A policy rule for a host name can narrow it to some of its requests: `api.github.com GET,HEAD /repos/` in a policy file, written by devvm network allow, deny and rm from --method and --path. Allows add up and a deny beats any allow, as for every rule, so narrowing a host that a rule allows whole, such as devvm's built-in GitHub, takes a deny: `devvm network deny api.github.com --method POST,PUT,PATCH,DELETE`, or `devvm network deny github.com --path '/*/*/git-receive-pack'`. An allow by method and path for a host already allowed whole warns that it narrows nothing and names the deny. The proxy decrypts such a host's HTTPS on :443 with the VM's CA, refuses its tunnels on other ports and without a CA, and judges every request on the connection, kept-alive HTTP/1.1 and HTTP/2 alike, every absolute-form one, and the shared Nix cache's own fetches. A connection's verdict and whether its requests are judged come from one read of the policy files. A blocked request gets 403 and a blocked event with its method and path; devvm network log shows it, and an allowed one's forward event names the rule that let it through. One matcher, internal/proxy/request.go, judges rules and secrets' bindings: methods from a closed list (RFC 9110's, PATCH, QUERY; never CONNECT); the methods a request names besides its own (every override-like header in any spelling, `_` for `-`, and the query's _method), each word judged, and while a rule narrows by method, a value that isn't exactly one method refused; path patterns with *, ** and a last / for everything below; and only a path in plain form. Allows and bindings match strictly, denies broadly: any case, every path that isn't plain, the prefix above a trailing /, and a last segment cut at its first dot (/admin.json, /admin.). A method devvm doesn't know isn't a rule, so a typo in a deny is a broken deny. Upgrades other than WebSocket and CONNECT inside a decrypted tunnel are refused for narrowed hosts. devvm secret set takes an optional --method (none for every method), and a secret's --path takes the same patterns, marked path_pattern in custom-secrets.json; a saved path with a * from before is refused rather than read as a wildcard. The bindings file stays version 1 while every binding reads alike to an older proxy, so devvm secret set and rm after an upgrade don't take a running older proxy's bindings away; a binding with methods or a pattern makes it version 2, which such a proxy refuses instead of putting a value in for every method, and writing one warns for each such VM. devvm network allow, deny and rm warn, naming the VM, when a rule by method and path changes while the VM's proxy runs from another devvm binary, or one devvm can't tell. A query with a ; or one Go can't read whole is refused while a rule narrows the host by method, and denies also match each segment with its trailing dots dropped. An allow that narrows nothing names the VMs, with -g by each VM's own allowlist, and says when it narrows only port 80's plain HTTP. - proxy: match, Methods, ParseMethods, PathOK, plainPath, matchPath, overrides, overrideLike, server.judgeRequest; parseRule/parseHostRule, CanonicalRule, NarrowRule, Narrowable, hostRules (rulesFor, verdict, byRequest, judge, unjudgeable), egress.checkHost, Allowlist.CoversWhole, trimDots; Binding.Methods, BindingListVersion 2 when needed (v1Binding); pathWithin and PathPrefixOK folded into match; the Nix cache judged - netpolicy: Rule(rule, deny, methods, path), NarrowedHost, sameRule, Proxy.Allowlist, Proxy.NarrowNotes, Proxy.OtherBinaries, BasePolicy, Proxy.SecretsWritten (after RefreshSecrets and devvm agent login --api-key's write); FormatEvent shows a blocked request's method and path and a forward's rule - secrets: Def/Secret/customJSON Methods, path_pattern, CheckMethods, CheckPath on proxy.PathOK - vm: RuleChange, PolicyChange(ctx, rules, RuleChange) - cli: --method and --path on network allow, deny and rm, --method on secret set, METHODS in devvm secret and "methods" in its --json - messages: bad_request_path (was bad_secret_path), bad_methods, rule_not_narrowable, rule_narrows, rule_narrows_nothing, rule_narrows_http_only, rule_narrows_unknown, proxy_other_binary, secrets_other_binary - tests: TestParseRuleNarrowed, TestMatchPath, TestDenyBypasses, TestAllowNarrowed, TestCoversWhole, TestForRequestMethods, TestInterceptRules and TestInterceptSecretMethods (HTTP/1.1 kept alive and HTTP/2), TestNarrowedNotDecrypted, TestNixCacheRulesByPath, FuzzDenyBypass (paths, methods, headers, _method), TestRule, TestNarrowedRules, TestOtherBinaries, TestRefreshSecretsOtherBinary, TestNarrowNotesUnreadable, TestDefine's path of /, TestReadBindings' versions, TestCustomsUnreadable's prefix path, network_narrow.txtar (narrows nothing), secret_custom.txtar's --method; on 0.1.0's frozen state: TestV010Bindings, TestV010ProxyConfig, TestV010Rules (0.1.0's TestParsePolicy and TestDecide, frozen), fixture_v010_network.txtar; e2e network: netRequestRules and the basic secret's --method GET,HEAD - docs: safety/network.md's Rules by method and path, the secrets' flags and an example, internals/network.md's Requests by method and path, the design note replacing the open-work entry, attack vectors, the commands page, internal/proxy/README.md, the CLI reference Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
2865158e02 |
feat(network): learn the hosts a new VM needs, then lock it to them (#22)
--network learn runs a VM on the internet tier while it records the hosts it reaches beyond its allowlist, shown as internet (learning). devvm network lock picks which of them go into the VM's own rules, ticking only reviewed registries on 443 and listing risky hosts apart, then gives the VM the allowlist tier at once. learn is per VM only. The lock command names its docs page in its about. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
8d44175601 |
refactor: the Go module is github.com/devvmhq/devvm
Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
d209071ec3 |
feat(network): devvm-why and the agents' note point at a tool that skipped the proxy
With nothing blocked, the proxy's /blocked answer (devvm-why) adds that a DNS or connection error for an allowed host means the tool skipped the proxy, to turn on its own proxy setting or give it $HTTPS_PROXY, and links troubleshooting's A host on the allowlist doesn't resolve. The agents' note in ~/.claude/CLAUDE.md and ~/.codex/AGENTS.md says the same in one sentence. Tests: proxy_test's empty answer, network.txtar asks a running proxy's /blocked, and the e2e network section checks that curl --noproxy fails for github.com, devvm-why's hint and the note in CLAUDE.md. Docs: internals and safety network pages. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
760e602d18 |
fix(agents): host-side login refreshes trust the user's CAs
An agent's OAuth refresh (Claude Code, Codex, opencode) runs in the VM's proxy on the host and goes through the company proxy, but trusted only the system's roots, so a company proxy that inspects TLS made it fail. Each secret lookup's context now carries the proxy's own roots, the system's and upstream_cas (proxy.WithRoots, RootsOf), which the refresh's client trusts through the new fetch.Client.Trust. Tests: fetch TestTrust, agentlogin TestRefreshTrustsTheProxysRoots and proxy TestLookupRoots, each against a TLS server signed by a test CA; the e2e network section's Claude refresh check now expects success. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
3a2c290d3d |
refactor(msg): messages and comments say network tier and the VM's proxy, not network policy
Every VM runs a proxy and is on one of four tiers, so the proxy's messages name the VM's proxy, the unenforced ones its network tier, and the redaction ones say devvm keeps secrets on this machine on every tier. Message IDs are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
2151d1b959 |
feat(proxy): capture agents' logins at their token endpoints
A login that Codex or opencode makes inside a VM goes to devvm's agent store, and the VM gets only placeholders. Every VM's proxy intercepts OpenAI's token endpoint (auth.openai.com/oauth/token, listed in its config's captures for Codex and opencode on every tier), and its host joins the allowlist of a VM whose image has either agent. This is the proxy's first response rewriting (ModifyResponse, stdlib only). - proxy: Config.Captures, IO.Capture (Capturer: Request, Response), Exchange; a POST to the endpoint's path (cleaned, without ;params, any case) is read (64 KiB) and its 2xx reply (1 MiB) goes to IO.Capture, never to the VM; the VM gets IO.Capture's reply with only Content-Type, Cache-Control, Pragma and Date; a "login" event names the agent; what can't be read gets 502, logged as a refused block, values never logged. - agentlogin: Endpoints, Pick (the User-Agent tells opencode, Bun's, from Codex), File.CaptureRequest and File.Capture under lockLogin: Codex's auth.json (tokens, account_id, last_refresh; the id_token->API-key exchange's key in OPENAI_API_KEY, the VM's id_token placeholder swapped for the store's on the way out), opencode's auth.json openai entry, Claude Code's .credentials.json (capturer only: no VM captures Claude yet). A code replaces the login, a refresh adds to it (newest refresh token kept). The VM's reply: the bindings' placeholders, refresh token devvm-proxy-managed, expiry 2099. - secrets: Store.CaptureRequest, Store.Capture (folder private, out of backups), the token endpoints' hosts in secrets.policy. - netpolicy: Capturer (devvm _proxy's IO.Capture: the VM's salt, its agent, the bindings written again at once); devvm network log shows login lines. - e2e (network): a fake token endpoint behind a company proxy of the run's own, with the run's CA; the store gets the real tokens and key, the VM placeholders and no refresh token, no log holds a value, the next launch gets the login as placeholders. - Docs: Logins made in a VM (internals/network.md), coding-agents.md, safety/network.md (the account swap), the proxy's README. Security review (security-audit skill, plus an independent read): - Fixed: a VM could spell the path another way (/oauth/token;x) and get real tokens uncaptured: path parameters dropped before matching. - Fixed: another path on the host could hand the VM tokens: any 2xx from a token endpoint's host naming access_token, refresh_token or id_token is refused, whatever its type (web pages pass unread); 101 refused. - Fixed: 1xx replies (103 with Set-Cookie) reached the VM before ModifyResponse: dropped on token endpoints' hosts. - Fixed: Set-Cookie and other headers on a captured reply reached the VM: only four headers kept. - Fixed: an error reply to the exchange could quote the real id_token: it reaches the VM as its OAuth error code alone. - Fixed: a captured request went upstream under the VM's raw path and query: it goes to the endpoint's own path, no query. - Fixed: repeated form or JSON fields, which devvm and the endpoint could read apart, are refused. - Fixed: captures depended on the image's agents, so a self-installed Codex logged in uncaptured: every VM's proxy captures at the endpoint. - Fixed: at most 8 bodies read whole at once. - Fixed: the VM's refresh with its managed refresh token is answered from the store, so a VM's Codex isn't logged out after 8 days. - Fixed: a login saved whose bindings write failed reached the VM as a 502: it reaches the VM, the error is logged. - Accepted, documented: any VM with the agent can replace the store's login (an account of its choosing); on the open tier a program can go around the proxy; Claude Code's own /login in a VM isn't captured. - Unconfirmed: domain fronting through a sibling OpenAI host whose tunnel isn't intercepted (depends on the CDN routing on Host). Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
c0f4b8fb5c |
feat(netpolicy): network tiers in state, confinement and the proxy
A VM's network is one of four tiers, open, internet, allowlist and none, in its state's net section (netpolicy.Tier), in place of on/off. Every VM has its proxy. Confined tiers start on NetProxy; open starts on the backend's own network with its proxy set in the guest (Confinement.GuestProxy): on Lima no Seatbelt profile and no QEMU wrapper, the proxy at 192.168.5.2 on both hosts, propagateProxyEnv off. The proxy: Config.Open (every host and address, no floor, no policies), Config.DenyPolicies (files whose denies alone apply), the rule port :* (any port), and ** matching address literals (the floor still holds). Policies per tier (netpolicy.PolicySet): internet is network/internet.policy (**:*) plus your denies; none is the agents' built-in policies, the secrets' hosts and your denies; open none. Links: a client links only to a target on its tier or a stricter one, and a group's VMs are all on one tier. The self-check per tier: open asks its proxy through the guest's settings and warns (net_proxy_unreachable). devvm ls and devvm network show the tier. A backend without egress-proxy offers open alone (net_tier_backend). devvm network on/off and --network-policy/--no-network-policy map to allowlist/open. Design note, threat check and docs; e2e in the network and link sections. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
1131c07d28 |
fix(proxy): bound the leaf-certificate cache and a VM's CONNECTs at once
The CA keeps the leaves of the 1024 hosts used most recently (leafCacheMax, an LRU over container/list), so a binding with a wildcard host can't grow it without end. The proxy carries at most 1024 CONNECTs at once per VM (maxConnects, a semaphore taken after the password check, links' and intercepted tunnels included): one past it gets 503 with the reason "1024 tunnels open already", logged as a refused block, and proxy.log says so once until a tunnel ends. 1024 is four times Chrome's 256-socket pool and many times a package manager's (npm's 15 sockets, uv's 50 downloads). Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
937a4901e1 |
fix(proxy): keep resolver and company-proxy errors out of the VM's refusal reasons
A name that doesn't resolve and a tunnel that can't connect now give the VM's 403, /blocked and the event log a fixed reason (reasonUnresolvable, reasonConnectFailed) that points at proxy.log; the error itself, which can name the host's DNS server or the company proxy's address and answer, goes to the proxy's own log alone (egress gets the proxy's logger). Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
8d00c42e14 |
fix(netpolicy): a VM's CAs are readied under a lock and deleted once its policy is off, and the proxy refuses minting GitHub credentials in absolute form too
- trust.InitCA takes the caller's ctx and holds the CA folder's lock (paths.CA.Lock, vms/<hash>/run/ca/lock), so two launches of one VM at once never leave a key and a certificate of different runs (TestInitCATogether failed first, TestInitCACancelled, TestInitCAMismatched). - netpolicy.Proxy.Unconfined: a VM's first start without network policy stops its proxy and then deletes its CA folder, keys and all, under that lock; a proxy that won't stop keeps them (TestUnconfined, network.txtar). - The proxy's forwarder refuses GitHub calls that make a lasting credential for every HTTPS request, so absolute-form https:// requests get the 403 that intercepted tunnels got (TestForwarderRefusesMinting failed first); the minting paths also match /repositories/ID and /organizations/ID. Each forwarder's idle upstream connections close when its request or tunnel ends. - e2e: the build proxy check expects the run log's devvm:<key>@ and no proxy key in the log. - Docs: design.md's CA threat check, network.md, overview.md's locks, space.md, safety/network.md. Baselines raised (darwin). Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
9568e6c47f |
fix(proxy): agents' OAuth refreshes go through the VM's proxy's company proxy
A VM's proxy refreshed Codex's and opencode's OAuth logins with net/http's environment proxy alone, so with config.toml's [proxy] the refresh went directly, and failed behind a company proxy. The proxy now makes its upstream's route for its own requests as it starts (proxy.Upstream's WithPassword, with the proxy secret it looked up, then Route) and gives it to each lookup in the lookup's context; agentlogin's refresh sets it as its transport's proxy. A proxy without an upstream routes the refresh directly, as it does the VM's requests. - proxy.WithRoute, proxy.RouteOf; upstreams.host; secrets.route. - Tests: TestRefreshGoesThroughTheProxysRoute (fails without the fix), TestLookupRoute. - Docs: How it works' Through a company proxy, network policy's Behind a company proxy, the proxy's README. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
2304f26bf0 |
feat(netpolicy): config.toml sets the company proxy, and a start warns when its proxy loses one
config.toml's [proxy] table (https, http, no-proxy) is the company proxy that VMs' proxies and builds go through when devvm's environment sets neither HTTPS_PROXY nor HTTP_PROXY; the environment's settings win whole, never mixed with config.toml's. Each value is checked as config.toml is read (backend.CheckProxyURL, backend.CheckNoProxy), and a URL holding a password is refused (proxy_password_in_config): config.toml is copied between machines and kept with dotfiles. The password is the host-only secret proxy (devvm secret set proxy, in the Keychain or devvm's secrets folder). A URL that names a user gets upstream.secret in the proxy's config, and the proxy looks the value up through IO.Secret as it starts (upstreamPassword), so no file of devvm's holds it. No VM is ever bound to it: devvm secret use refuses (secret_host_only) and secrets.Names drops it. A new VM and a VM's proxy refuse to start while it isn't saved (proxy_password_missing, netpolicy.Proxy.Upstream). A start whose VM's proxy last ran with an upstream and now has none warns (upstream_proxy_gone), naming config.toml, with a doc link. - settings.HostProxy: the environment's, else config.toml's; used by netpolicy, Lima's build proxy (buildUpstream) and devvm doctor's CA hint. - proxy.Upstream.Secret, proxy.UpstreamSecret; secrets.Secret.HostOnly; secrets.Token keeps spaces inside the proxy password. - Messages: proxy_password_in_config, proxy_password_missing, upstream_proxy_gone, secret_host_only, proxy_password_howto, password_prompt (answered by --stdin). - Tests: TestHostProxy, TestUpstreamSecret, TestPrepareUpstreamConfig, TestBuildUpstreamConfig, config.toml refusals, the warning in TestPrepareUpstream, company_proxy.txtar, secret.txtar and ca.txtar cases. - Docs: troubleshooting's Behind a company proxy, network policy's Behind a company proxy and secrets, config.toml's reference, How it works. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
1640feb608 |
feat(netpolicy): one CA per VM, with a successor the VM trusts ahead of time
Each VM with network policy has CAs of its own in its run folder, vms/<hash>/run/ca/ (paths.VM.CA, paths.CA: ca.pem/ca.key, next.pem/ next.key; folder 700, keys 600, kept out of Time Machine on macOS), so a leaked key reaches one VM and no proxy can sign for another VM. The shared ~/.local/share/devvm/ca (Dirs.CA) is gone. trust.InitCA(paths.CA) readies the current CA and the next one at each launch: the current one stays while it has over a week left, then the next one (started) takes its place, else a new one; the next one starts a week and an hour before the current one ends and is made again when it doesn't follow it. Each CA lasts 30 days and an hour, and its common name holds its serial, so a VM's two CAs never share a subject. The proxy's config gains ca_next, ca_next_key and ca_next_sha256 (part of Sum); the proxy signs with the next CA from an hour after its start (ca.signer), so the switch needs no launch or new proxy, and a VM not opened again stays verifiable for at least 30 days less an hour after its last launch. /ca.pem serves both certificates. loadCA reads the CA files with readPrivate (no links, a key only the user may read, 64 KiB cap) instead of tls.LoadX509KeyPair. The VM's setup sends both certificates (devvm-proxy.crt, devvm-proxy-next.crt) and no key. Tests: TestInitCA, TestInitCASwitch, TestInitCAReplaced (trust); TestNextCASigns, TestLoadCA, config check rows (proxy); TestPrepare and TestPrepareRestartsTheProxy for the VM's CA files and both sums (netpolicy); TestVMFiles; network, sync and layout txtar; e2e network: a second network-policy VM with different CAs, each VM trusting only its own and holding no key, each proxy serving and presenting only its own VM's CAs, devvm rm deleting one VM's CAs. Docs: internals/network.md (The VM's CA), design.md (A CA per VM, its threat check), safety/network.md, overview.md's per-VM files, space.md, security.md, attack-vectors.md, limits.md, coding-agents.md, contributing, internal/proxy/README.md. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
a77157e267 |
refactor(proxy): one watched file helper for the bindings, the policy files and the links list
watched[T] stats its file on each call (Lstat, or Stat for a file read through a link) and reads it again when its mtime, size or inode differ, or while its last read's mtime was within 2 s of then, so two writes within one mtime tick are both seen; it parses again only when the bytes differ. Each user picks its read (readPrivate or ReadRegular with its cap), keep (last good) or none on a failure, logged once per distinct error, and an on-change hook run under the watcher's lock. - secrets: readPrivate 0o077, none on failure; the hook clears the values cache (watcher lock, then valueMu), a touch included. - policy: ReadRegular, following links, last good rules and broken deny kept; per-file state is policyFile; policy.mu and its maps go. - links: readPrivate 0o022, none on failure; the list is read again only when it changes, and an unreadable one is logged once, not per request. readLinkList goes (readLinkListFile, parseLinkList). Tests: TestWatchedSameTick, TestWatchedSettled, TestWatchedFailures, TestWatchedRefused. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
bcafcda739 |
refactor(proxy): one server struct holds what a proxy runs with and keeps, and a tunnel passes the far end's bytes at once
internal/proxy keeps no package state. newServer makes a server from the config, as Main starts (it replaces Config.apply, loadPolicies and every global they set), and each part keeps what it changes under its own lock: events (the event log and recent blocks), egress (the policy, the host's addresses in hostAddrs, the company proxies in upstreams), secrets (the bindings file and the values cache, file lock taken before the values'), ca (devvm's CA and its leaves), links (the list and the sockets' folder) and nixCache (the cache's folder, checked narinfos, fetches and slots). The proxy's own log is a *log.Logger each part is given; Main's lifeline tick is a const, and run takes it for tests. What's left package-level is error sentinels and three fixed tables (notPublic, nat64, githubMinting), now in the structure test's allowedVars; the structure test no longer leaves internal/proxy out, and its rule case for the proxy fails a var. Tests make their own server with newServer (testServer, listen, logs, fakeSecret on a secrets, testCA) and all run in parallel. TestServersApart checks two servers in one process share no password, blocks, events, values or CA leaves. A tunnel to a host the policy allows passes the far end's bytes to the VM from the start (splice's before), so a server that speaks first gets its greeting through; the VM's bytes still pass only after the SNI check, which reads one byte first and the ClientHello only when it starts 0x16. TestTunnelServerSpeaksFirst failed on the code before. Docs: the proxy README (the server, files, testing), network.md's tunnel paragraph, AGENTS.md's test-seams line, Contributing's package-vars row. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
329e31be1d |
refactor(secrets): the proxy looks secrets up in-process, from one versioned bindings file
The proxy no longer runs devvm secret get for a value: proxy.IO.Secret,
which devvm _proxy sets to secrets.Store.Get, looks a binding's value up
in the proxy's own process (Keychain, devvm's secrets folder, or the
agent's login file), so internal/proxy stays standard library only.
Config.SecretCmd (secret_cmd) and the hidden devvm secret get command go,
with secret_to_terminal and secret_read_failed; Main refuses a config
with secrets and no IO.Secret.
One binding type, proxy.Binding, with kind secret|login and a login's
agent, in proxy.BindingList ({"version": 1, "bindings": [...]}), written
by secrets.Store (Encode) and read by the proxy and RefreshFiles with
proxy.ReadBindings (private regular file, no link, 1 MiB, version and
kinds checked; an unreadable file has no bindings). It replaces
proxy.binding, secrets.binding and agentlogin.Binding; the kind replaces
the name-prefix classifiers in proxy.ttlOf, secrets.loginOf and
RefreshFiles' Lookup check; proxy.InterceptLines replaces
agentlogin.Hosts and RefreshFiles' host loop.
agentlogin's user-actionable errors are typed (ErrCodexNoKey,
ErrCodexNoChatGPT, RefreshError) and secrets maps them to messages:
codex_no_key, codex_no_chatgpt, codex_refresh_failed,
opencode_refresh_failed, and login_read_failed for the rest.
Tests: proxy TestSecretValueLooksUpInProcess, TestReadBindings,
TestBindingsUnreadableHaveNone, ttlOf by kind, Main refusing secrets
without a lookup and -secret-cmd, config refusing secret_cmd; secrets
TestGet by kind, TestLoginFailed; agentlogin TestCodexBindings (kind and
agent checked on every binding), TestGetErrorsSayWhatToDo; secret.txtar
and network.txtar on the new file and without secret get; e2e's network
section keeps the fake token off argv and checks no command prints it.
Docs: the proxy README (Secrets section), internals/network.md,
safety/network.md, using/coding-agents.md, contributing.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
||
|
|
361087f95a |
refactor(proxy): host-only modes out of proxy.Main, into agentlogin and trust
devvm _proxy takes one flag, -config, and running the proxy is Main's only
mode. What only the host does runs in devvm itself, through typed functions:
- internal/agentlogin (new; imports only fetch, jsonc, proxy and state):
File{Kind, Path, Salt, TokenURL} with VMCopy (the VM's copy and what it
keeps as it is), Bindings, Get (refreshing OAuth tokens), plus Hosts,
MCPSecrets and Redact. The salt is a parameter, not a global or
DEVVM_LOGIN_SALT. Login files are read with proxy.ReadRegular (no FIFO
hang, 64 MiB cap) and written with state.WriteFile; the refresh goes
through fetch.NewClient (HTTPS-only redirects, 30 s, reply capped at
1 MiB) with context.WithoutCancel.
- trust.InitCA makes devvm's CA (state.WriteFileMode), replacing -init-ca;
netpolicy's InitCA field is it, and proxy_ca_failed carries the error.
- internal/jsonc: devcontainer's JSONC stripper, now redaction's too; the
redactor's own copy changed commas inside strings.
- proxy.HostOK is exported for agentlogin's MCP host check.
- secrets.Store loses its Login seam and LoginKept; IO loses Stdin and Kept.
Tests: proxy.txtar's login, redact and init-ca cases become unit tests in
agentlogin and trust; proxy.txtar and TestMainRefuses check the old flags
are refused. New: TestRefreshOutlivesItsCaller, TestRefreshFails,
TestGetRefuses, TestLoginFileNotRegular, TestHosts, TestRedactRefuses,
TestRedactJSONKeepsStrings, TestInitCA, TestInitCAFails, TestBundle.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
||
|
|
8e914b17c9 |
refactor(proxy): one typed, versioned config for every proxy, read as a private file
devvm _proxy runs with one argument, -config FILE: proxy.Config as JSON (version 1), which a VM's proxy (vms/<hash>/run/proxy.json, written by netpolicy.Proxy) and a build's (build-proxy/proxy.json, written by backend.ProxyStarter) both use. It holds what the flags and the run folder's sidecars held: the address, the VM, the password (proxy.auth), the built-in policies and the user's files (proxy.policy), the logs, the lifeline, the CA, the secrets, the user's CAs (proxy.cas), the company proxy (proxy.upstream, now proxy.Upstream), upstream_unresolved, the Nix cache and its cap, the links, and the SHA-256 of devvm's binary and CA (proxy.bin, proxy.ca), which the proxy doesn't read. devvm writes it whole, mode 600, before each start, and starts a running VM's proxy again when the config it would start it with has another Sum. ReadConfig reads it as the links' list is read (readPrivate): O_NOFOLLOW and O_NONBLOCK, fstat, a regular file owned by the proxy's user that nobody else may read or write, at most 1 MiB, of ConfigVersion, no unknown field, a password, a loopback listen address. The VM's proxy is found by _proxy -config with its own config's path. paths.VM names ProxyConfig, ProxyPID and ProxyStatus. Policy files are read only as regular files of at most 1 MiB (proxy.ReadRegular, PolicyMax), in the proxy, devvm network and doctor, so a FIFO or a link to /dev/zero can't hang them (ErrNotRegular, ErrTooLong; ErrNotPrivate for the config and the links' list); the proxy keeps a file's last rules and logs why once. hostOK refuses a name with an empty label (evil.test.., evil..test, .evil.test), so no form of a name gets past a deny the policy's own trim would miss. A build proxy that can't be spawned leaves no config behind. Tests: config round trip and Sum; ReadConfig refusing a link, a FIFO, a folder, group-readable and group-writable files, a long file, other versions, unknown fields, two configs, no password, non-loopback addresses, a CA without its key, a negative cap; ReadRegular and the policy readers on a FIFO, /dev/zero and a big file without hanging; the running proxy keeping its last rules; hostOK and requests with empty labels (failing on the code before); Prepare's config, restarts on a binary change, a missing config and one others may read; concurrent config writes; the build proxy's config and its removal; proxy.txtar, network.txtar, nix_cache.txtar and layout.txtar; e2e checks of the config's mode, password and the proxy's arguments. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
f4fd373439 |
refactor(backend): remove the smolvm backend
Lima is devvm's only backend. The backend architecture stays (Backend, Caps, Features, Review/Require, the registry, backendtest.Fake), so another backend is an addition. State from a smolvm VM reads as an unknown backend (backend_unknown_vm, gc_orphans_unknown); nothing migrates it. The image keys of layers/docker.sh, layers/nix.sh and features/desktop.sh change, so images rebuild once. Lima's port forwarder moves off smolvm's files first: newForwarderCmd and forwarderMain from internal/cli/smolvmports.go to limaports.go, and assets/container/ports.sh to assets/guest/ports.sh (sent by the forwarder at run time, so no image key changes). Removed: - internal/backend/smolvm (4,070 lines with tests), _smolvm-ports, its registry entry, registry.Experimental and backend_experimental. - The decider: backend.Decider/UsesDecider, Confinement.Decider and DeciderToken, internal/proxy/decider.go and its test, the proxy's -decider, -decider-to and -decider-token-file, netpolicy's KeyDeciderPort, KeyDeciderToken and deciderToken, the decider port in vm's forwarding and UsedPorts. - backend.AgentStarter/AgentUnchosen, vm's checkAgentStart and agent_unchosen_stop. - vmssh/key.go (EnsureKey, Public, HostKey, ServicesArgs, Capped). - paths.Smolvm/SmolvmImage and space's smolvm folders; paths.VM's Record, Key, KnownHosts and ProxyURL; project.Detect, which nothing called (a test helper now). - ubuntu.ContainerRepo/ContainerDigest/ContainerRef/ContainerOrigin and bump.sh's ubuntu_image, with its part of bump.txtar. - assets/smolvm/ and assets/container/; the no-init-system branches of layers/docker.sh, layers/nix.sh and guest/sync.sh, and the notes in features/desktop.sh and guest/ca.sh. - Messages: smolvm_* (14), vm_no_ssh, vm_no_sshd, ports_no_ssh, creating_from_image, packing_image, pack_failed, backend_experimental, agent_unchosen_stop; descriptions naming smolvm reworded. - Tests: smolvm.txtar, the smolvm stub, registry, decider, netpolicy and sshagent cases; gc_backend, gc_skipped, gc_orphans and space test a failing or hanging Lima listing instead (the limactl stub's list-fails and list-hangs); the --backend smolvm examples; e2e's --backend smolvm and its section (about 1,130 lines), the smol_* helpers and the link section's backend switch. - Coverage: internal/backend/smolvm's lines in both baselines. - Docs: backends/smolvm.md, internals/smolvm.md, design.md's smolvm notes (Ports on Lima now holds the forwarder's description), the backends table's smolvm column, every page naming smolvm, the README, the home page's backends art, and AGENTS.md's smolvm rows and gotchas (and the Docker bind-mount gotcha, which nothing refers to). Kept: the docker layer, on Lima; --from's local Docker; --backend, the BACKEND column and setup's backend choice, which the next commit removes. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
1917072228 |
refactor(backend): remove the Docker backend
devvm is about VMs, and Docker's containers aren't VMs: Lima is the default backend and smolvm stays experimental. The backend architecture (Backend, Caps, Require, the registry, backendtest.Fake) stays, so another backend is an addition. Removed: - internal/backend/docker, its registry entry and Names/Experimental's docker half; devvm _docker-connect and _docker-ports (internal/cli/dockerssh.go); assets/docker/unpack.sh. - Test-build overrides DEVVM_DOCKER_KIND, DEVVM_DOCKER_PROC_SYS, DEVVM_LINUX_BUILD_URL/_SHA256, the registry.linuxURL/linuxSHA256 ldflags vars and the CLI tests' Linux-build archive (linux_release). - Interfaces only Docker implemented, with their callers: backend.ProxySocket/ProxySocketOf (the proxy's -listen-unix), DiskUser (ls's and size's disk-over warning, size's disk_used and --json disk_used_gib), Reporter (doctor), LeftoverLister and Leftover (gc --orphans' volumes, networks, containers and images), DockerLayerVM and VMSpec.DockerLayer, SSHTarget.ProxyCommand and vmssh.SSH.Proxy, vmssh.SSH.SessionArgs, CacheEntry.Name. - The docker layer's runtime on a backend that makes VMs for it: vm/dockerlayer.go, KeyDockerLayer, chooseNet's refusal (chooseNet returns a bool now), the refusals at start and devvm network on, ls's "(sysbox)" and --json docker_layer, size_disk_default_unused. - The proxy's relay mode (relay.go, -relay, -relay-to, -listen-unix). - paths.Dirs.Docker and paths.VM.Lifeline. - assets/guest/tools.sh's linked-folder branch; services.sh's DEVVM_LOOP, DEVVM_DOCKERD and DEVVM_SSHD=inetd. - Messages: every docker_* the backend used, docker_layer_runtime, net_docker_layer, net_off_docker_layer, committing_image, pulling_image, unpacking_tools, disk_over, size_disk_default_unused, gc_orphan_volume/_network/_container/_image, docker_connect_failed; gc_orphan_elsewhere reworded. - Tests: docker.txtar, the docker stub's engine (its --from half stays), the ssh stub's login-shell branch; e2e's --backend docker, --engine, the docker host VM and Docker Desktop runs. - Release: one GoReleaser pass, no Linux-build pin in the macOS builds, no Linux devvm in the Homebrew formula's libexec. Linux builds stay. - Docs: backends/docker.md and internals/docker.md, design.md's Docker notes, the Docker column of the feature table, and every page's mentions of the Docker backend, Docker Desktop as one, and Sysbox. Kept: the docker layer in Lima VMs, devcontainer docker-in-docker, --from with images only a local Docker has, Docker Hub references. State written by a Docker VM before this reads as an unknown backend (backend_unknown_vm). Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
d8a7d4de7f |
refactor(state): a folder per VM, keyed by its project folder's hash
Every file devvm keeps for a project VM is in one folder, vms/<hash>/, where <hash> is the 14-hex hash of the project folder's path that the VM's name ends with: its state, its own rules (policy), its backend's files (backend/: record.json, key, known_hosts, proxy, ports and the port forwarder's ports.*), what its runs leave (run/: proxy.*, sandbox.sb, started, lifeline.pid, secrets.*, links.*) and its logs (logs/: network.jsonl, proxy.log, links.log). Build VMs keep the same layout in run/builds/<name>/. The top-level run/ holds only what isn't one VM's or must be short: the hashed control sockets, links' link-<hash>.sock/.ctl, the QEMU wrapper and the ports lock. A folder's VM is found by its path's hash (state.ReadHash), with the name and backend its state records, so devvm --backend docker then devvm in the same folder opens the one VM, and a backend's name limit applies to new VMs only. The state records the VM's name and its ssh alias, chosen once at creation (sshconfig.ChooseAlias) and never recomputed. Links' targets match recorded names, aliases and folders (project.Targets). One teardown (vmFolders.teardown) replaces Lifecycle.forget, undoCreate's own list, Leftovers.Forget's, Proxy.Forget and space's leftoverFiles: it stops the proxy and link session, then the pieces outside the folder (clone remote or .git locks, other VMs' links and the group, host keys, the backend's leftovers), removes the folder, and writes the ssh config. Each backend's Delete and Forget remove the VM's backend/ folder (vmssh.Forwards.Forget). A new VM made where an earlier one's folder was left clears it first. devvm space counts an orphan's whole folder as leftover state and the other VMs' logs as network logs. Path builders move into paths: Dirs.VMDir, Dirs.VM and paths.VM's files (secrets' BindingsFile/PolicyFile, netpolicy's run, EventLog, ProxyLog, LinkList, VMPolicyFile, Lima's profileFile, startedFile, forwards.file, vmssh.Forwards.file, links' LinksLog/linksPID, Docker's vmFile and lifeline), ToolLockConfig, ToolLockChecked and ToolsCheckLog; the user's cache folder for Lima's and smolvm's caches is Dirs.UserCache, from HOME, not os.UserCacheDir. Dirs.VMState, LimaVMs, SmolvmVM and DockerVM go. vmname.HashOf and IsHash, project.Hash. The proxy takes the links' sockets' folder (-link-sockets, devvm's run folder) apart from the links' list, which is in the VM's run folder. Tests: a VM made and removed (rm, gc --orphans) leaves nothing under vms/, and with network policy has no file named for it outside its folder (TestTeardownLeavesNothing); a new VM over an old folder starts clean; lookup finds a VM made on another backend with a long folder name and makes no second one (TestLookupOtherBackend, and in docker.txtar); the alias stays put when a second VM shares the folder name (TestChooseAlias, ssh.txtar); every socket fits under a 35-character home with the longest VM name (TestSocketsFit); space counts an orphan's whole folder (TestLeftoverFolders); paths.VM's files; state by hash and name; the proxy refuses a socket in the list's own folder. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
e9f791bc96 |
refactor: one owner for the proxy's constants, URLs, variables and tunnels
The proxy owns the links' addresses and domain and the proxy user: proxy.IsLinkAddr, proxy.LinkAddr, proxy.LinkDomain and proxy.ProxyUser replace vm.IsLinkAddr, vmssh.IsLinkAddr, vm.LinkNet, vm's linkNetAddr, vm.LinkDomain, netpolicy.LinkDomain and the proxy's own isLinkAddr and linkDomain. TestLinkAddrsAgree goes, because there's nothing left to agree. The proxy's link list now refuses an IPv4-mapped address too, as vm's parser already did. backend owns the guest's view of a proxy: ProxyUser (proxy.ProxyUser), ProxyURL, GuestProxyVars, ClientProxyVars and NewProxyPassword replace four URL builders (BuildProxy.URL, Lima's, Docker's and smolvm's), the user written out in three places (netpolicy.ProxyUser, buildProxyUser, Docker's proxyUser), the guest's variable list in three (Lima's inline loop, smolvm.proxyVars, Docker's proxyVars) and the client's in two (limaProxyVars, Docker's noClientProxy list), and the two password generators. Confinement.ProxyUser goes: Docker ignored it, and every backend now uses ProxyUser. A new VM's proxy key is NewProxyPassword's 64 hex digits, as a build proxy's was; a VM keeps the key it has. doctor reads HTTPS_PROXY through backend.ReadHostProxy. In the proxy, hijack and splice replace the three CONNECT copies (tunnels to allowed hosts, tunnels to links, interception's hijack) and the relay's pipe. A tunnel passes the bytes as they are, passes on the end of what the client sent, and ends, closing both connections, when the server's bytes end or the client has gone. A relayed connection now ends with the proxy's side too, where before it waited for both. Tests: splice_test.go characterises the allowed-host tunnel, the link tunnel and the relay (a megabyte of every byte value, a half-close answered, a client that goes away ending the tunnel), written against the code before this change; TestSpliceEnds, TestHijack and TestIsLinkAddr (every LinkAddr) are new, and so are TestProxyURL, TestNewProxyPassword and TestProxyVars. TestLinkListRefused gains a mapped address. e2e: the relaunch without a company proxy says which step failed, with the launch's output, the VM's status and the proxy's log, and a link helper that doesn't start shows its output. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
2687eec488 |
refactor: one background-process helper, internal/daemon
internal/daemon (standard library only, so devvm _proxy uses it too) owns devvm's background processes: Detach and Spawn (own session, no input, reaped once they end, DEVVM_DAEMON_STATUS naming the process's own status file), Handle (signals through the process started), Proc (a pid file checked against the process's arguments, Stop: SIGTERM, a wait, SIGKILL, the pid file removed once stopped), readiness by status file (Ready, WriteStatus, WaitReady: the pid and data, written in one line-ended write, never another start's), Alive and Signal (no pid below 1), and one lifeline meaning (FollowLifeline, Lifeline.Holds and Wait: content equality, a bounded wait past what the file held first). It replaces netpolicy's proxy pid, stop and start wait, vmssh.Forwards' pid, stop and start wait, the build proxy's process and log-read port, links' link-session pid, stop and start, the proxy's watchLifeline and vmssh's lifeline reading, platform.StartDetached/StartDetachedProcess, and the alive copies (netpolicy alive/signal, lima alive, vmssh.ProcessRuns, smolvm runsOn's). The three log-scraping waits go: the proxy and the forwarder say they're ready in a status file, and the build proxy's port comes from its own. forbidigo bans os.FindProcess, syscall.Kill and unix.Kill outside internal/daemon and internal/platform, with its line in testdata/lint/forbidigo.go; the structure test lists DEVVM_DAEMON_STATUS and puts internal/daemon among the leaves; depguard holds it to the standard library. Tests: daemon's own (detach, handle stop, a reused pid, a stale pid file, groups refused, readiness, lifeline), characterisation tests first for the proxy's, the forwarders', the link sessions' and the build proxy's pid handling; coverage: internal/daemon 97.7%, lima 87.6 to 87.7. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
f71adb5a04 |
refactor: devvm's own files stay in the binary
assets.FS is the only copy of devvm's own files: nothing writes them to
~/.local/share/devvm/assets/<hash> any more, so an edit on disk can't
widen running proxies' allowlists or change a --from base its key
doesn't describe.
- Proxy: -builtin-policy NAME,... names policies in IO.FS (cli's _proxy
passes assets.FS; proxy stays stdlib-only). Built-ins are parsed once
at start (readBuiltins), ahead of -policy's files in the union, never
re-read; a missing one, or one with a line that isn't a rule, refuses
to start. -policy carries only the user's files.
- netpolicy: PolicyFiles(d, assets, vm, img) becomes Policies(d, vm, img)
(builtin, files); Proxy.PolicyFiles and AssetsInUse go. .proxy.policy
records both lists, a line each, for the restart check. ReadRules takes
built-ins from an fs.FS; RuleFile.Builtin.
- devvm network: built-ins labelled "# devvm: layers/base.policy";
--json entries carry "builtin": NAME or "file": PATH ("version": 1).
- Lima: createArgs ends in "-" and create() feeds base.yaml on stdin;
convert writes oci/ and, with company CAs, guest/ca.sh into its own
temp folder beside vm/ (writeScripts, state.WriteFile), mounted
read-only and deleted by the existing cleanup. Lima.assets() goes.
- Deleted: internal/state/assets.go and its test (WriteAssets,
StaleAssets, AssetsHash), paths.Dirs.Assets, gc's stale-assets plan
and the gc_assets/deleted_assets messages, space's devvm's files row.
- Tests: proxy built-ins (order, not re-read, missing/invalid refuse,
Main refuses before listening), Policies, the restart check on either
list, ReadRules/WriteRules labels, JSON shape, createArgs and create's
stdin, writeScripts' files and modes; CLI scripts check
$XDG_DATA_HOME/devvm/assets never appears after up, build and --from,
base.yaml on create's input (the limactl stub keeps it), the
conversion's mounts and script paths in its temp folder.
- Docs: design (One binary), install, overview, space, images (gc),
internals network, images and lima, safety/network, proxy README,
the network command's Long and its CLI page; AGENTS.md rule.
- Coverage baselines (darwin) raised: cli 88.2, netpolicy 87.2,
proxy 88.2, state 91.8. Dirs' method cap lowered to 41.
Image keys are unchanged: they already hash the embedded files.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
||
|
|
487366d186 |
fix(netpolicy): one strict parser for policy files, lines that aren't rules named, broken denies fail closed
The proxy read policy files with a laxer parser than devvm network allow's check: a line that wasn't a rule was dropped without a word, or kept as a rule that matched nothing (example.com:x became a host of that name, a rule's trailing dot never matched), so a hand-edited deny could lapse unseen. proxy.ParsePolicy is now the one parser: it returns each line that holds more than a comment, with its number and whether it's a rule, and a line is a rule only when ValidRule takes it, which is what devvm network allow and deny take. parseRule is strict: ports 1 to 65535 in digits, printable ASCII names with no empty label, brackets for IPv6 alone, no address under *., IPv4-mapped prefixes as their IPv4 ones, and one trailing dot dropped, as requests' are. A line that isn't a rule but starts with ! (proxy.BrokenDeny) fails closed: while any of a VM's policy files has one, its proxy denies every name and address, each request getting 403 and a refused block that names the file and line, with no allow advice (block honours Refused; policy.verdict and checkRefused carry it). Other lines that aren't rules are skipped. The proxy logs each one, devvm network marks it (its control characters dropped, msg.OneLine) and --json lists it in not_rules. netpolicy.PolicyWarnings warns of each (policy_broken_deny or policy_not_rule): at each launch with network policy (Proxy.Prepare), after devvm network allow, deny and rm for the file they change, and in devvm doctor for the files you edit (NotRules). AddRule and RemoveRule find rules through ParsePolicy, so ruleOf is gone. A policy file that comes back after it was missing is read again whatever its mtime, an error other than a missing file keeps its last rules and broken deny, and a leading byte-order mark isn't part of the first line. Docs: rules, broken denies and devvm network's output (safety network), the parser and the fail-closed policy (internals network), doctor's warnings (install, internals install), the e2e network section (contributing), the proxy's README. Tests: TestParsePolicy, TestPolicySkipsBadLines, TestPolicyBrokenDeny, TestPolicyFileBack, TestValidRule's new cases and FuzzParseRule's agreement and host properties (proxy); TestBuiltinPolicies, every policy file devvm ships, TestNotRules, TestPrepareWarnsPolicy, TestWriteRules and TestAddRemoveRule's new cases (netpolicy); TestDoctorReport and the network JSON shape (cli); network_rules.txtar's mark, not_rules and the warnings on a change, a launch and in doctor; e2e network: a broken deny makes the running proxy refuse an allowed host until it's gone. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
aa24efe2e7 |
fix(proxy): certificates never outlast devvm's CA, and a CA that ended is named
The proxy keeps the CA it started with, because its VM trusts no other, so a VM that runs past its CA's end without a launch can't verify the proxy's certificates. Leaves were minted for a day whatever the CA had left, so they could outlast it, and once it ended every intercepted tunnel failed its handshake with a misleading reason. leafFor now caps a leaf's NotAfter and NotBefore at the CA's, keeps a leaf that ends with the CA until then, and mints none once the CA has ended (errCAEnded); a CONNECT that would be intercepted then gets 403 before its tunnel opens (caEndedRefusal), logged as a refused block, so no allow rule is suggested, with a reason that says to open the VM again, which makes a new CA, installs it and starts the proxy again. Docs: how a VM trusts the CA and what happens at its end (internals network and security, safety network), the proxy's README. Tests: TestLeafWithinCA, TestInterceptCAEnded (proxy). Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
6c14ee0748 |
fix(network): the event log's two writers rotate it by one rule and follow each other's rotations
devvm _links rotated a VM's event log by its own size check while the proxy still had the file open, so the proxy went on writing into the renamed .1 file, devvm network log --follow missed those lines, and the proxy's next rotation, by its stale counter, renamed the link-only log over .1 and lost the old one. Both writers now use the proxy's writer: proxy.OpenEventLog, which netpolicy.AppendEvent writes each event through. Before each line it checks that its open file is still the one at the path (os.SameFile), opens the path again when it isn't, and takes the log's size from the file. A rotation holds the file's flock and checks the name again, so two writers past the limit at once rename it only once. One exported proxy.LogLimit replaces logLimit and eventLogMax, and the limit is a field of the writer, so the proxy's tests pass their own. Tests: TestAppendEventRotatesUnderTheProxy (netpolicy; fails on the old code: the padding and the proxy's first line were lost) and TestRotateFollowsTheOtherWriter (proxy). Docs: internals/network.md's log files, design.md's link events, internal/proxy/README.md. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
5db31c92be |
feat(link): the per-VM proxy reaches a VM's links, and link names leave NO_PROXY
In a VM with network policy, an HTTP client that honors HTTP_PROXY now reaches a link through the VM's proxy, so a link added while the VM runs works at once and nothing restarts. The ssh remote forward stays the transport for every link; the proxy is a second entrance to the same host socket, and devvm _links's per-connection checks apply to both. - devvm _links writes every link the client has, carried or not, to run/<vm>.links.json (proxy.LinkList, mode 600, written whole) whenever they change or the file is gone; it stays after the session, so a link with no socket is refused rather than asked of the rules. Forget removes it with the VM. - devvm _proxy -links FILE reads it per request (regular file, no symlink, owner-only writes, 1 MiB, version 1, O_NONBLOCK), before any rule: CONNECT and absolute-form http, exact match after lower case and one trailing dot, NAME and NAME.devvm.internal. An entry counts only when its socket is proxy.LinkSocket(list folder, -vm, addr, port) and its address is in 127.77.0.0/16. Bytes pass as they are: no SNI check, interception, secrets or rules; absolute form goes in origin form without the proxy's headers, one connection per request, cancelled with the client's request; https in absolute form gets 400. No event for a carried link (devvm _links logs link); a dead socket gets 502 and link_refused "not carried", after retries for a full backlog. Any other name under devvm.internal is refused (403, a refused block). - vmssh.Links.Socket uses proxy.LinkSocket and LinkHash (same names). - The link socket's accept loop only accepts, and hands a burst on whole (5 ms quiet, 50 ms at most, or 257 waiting) before relays start, as fork-heavy relay starts let macOS's 128 backlog overflow unlogged; past the cap, refused in the loop with link_limit. Temporary accept errors back off instead of ending the link. - NO_PROXY is localhost,127.0.0.1,::1 everywhere: netpolicy.LinkEnv and linksNoProxy are gone, netpolicy.NoProxy is a constant, the start only checks the links (checkStartLinks). No dockerd or nix-daemon restart and no limactl edit on link changes. assets/guest/sync.sh: comment only. - devvm network log's help says link events land there for every VM. - Docs: using/links.md, safety/network.md, internals/network.md (Links through the proxy, -links), ports.md, lima.md, design.md (the proxy's entrance, the burst, threat-check rows for the proxy path, links added while running and untouched bytes, the sshd row reworded, Not covered), contributing, internal/proxy/README.md. - Tests: proxy TestLinkConnect, TestLinkConnectUntouched, TestLinkForward, TestLinkGone, TestLinkListRefused, TestLinkDomainRefused, TestNoLinksFile, TestLinkSocket; vmssh TestLinksBurst, TestLinksList; netpolicy TestNoProxy and the -links argument; e2e lk_proxy_added and lk_proxy_own, and lk_cap's burst without pacing. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
6805d194bd |
feat(link): devvm _links, the host side that carries a client's links, and the forwarder skipping links' addresses
vmssh.Links runs a running client VM's link session: one ssh master of its own to the client (never the forwarder's), started with ClearAllForwardings=yes and -N, to which each link is added with -O forward -R 127.77.x.y:PORT:<socket> and from which it's removed with -O cancel, read again every second (Want). Each forward is its own, so one the client refuses fails that link alone (Failed, which warns with link_port_taken through Link.PortTaken). Each link's end on the host is a unix socket, mode 600, in the run folder (made 700), named link-<hash of client, address, port>.sock; masters' control sockets are link-<hash>.ctl (the session's; a target's by target and start). A stale socket is replaced, anything else refused, and sockets go with their link or the session. Each connection is checked again (Check), then carried by ssh -S <target master> -o ProxyCommand=/usr/bin/false -W 127.0.0.1:PORT through a master kept per target and start: a channel goes through the master or nowhere. At most 256 at once, then refused (link_limit). Events (link, link_refused, link_target_stopped, link_limit) go to the client's event log. The session ends once the client no longer runs its start, or has no links. vm.Links.Session builds it from the state and the backends: the client's and targets' ssh from Backend.SSH, the key its first IdentityFile, host keys devvm's pinned known_hosts (HostKeyAlias), only on a host loopback port or through the backend's ProxyCommand, FeatureSSH allowed. linkConn re-reads the states per connection: the link still in the client's state (removed), CheckLink (gone, replaced, unpublished, policy), the link features on the target's backend, the target running (Inspect, StartID: link_target_stopped otherwise; it never starts one), its ssh (ssh). devvm _links VM (hidden, one argument) runs it, failing with link_session_failed or vm_not_running. The port forwarder never forwards a listener in 127.77.0.0/16 (dialAddr, vmssh.IsLinkAddr), on any VM; a test keeps vmssh.IsLinkAddr equal to vm.IsLinkAddr on every link address and around them. netpolicy.AppendEvent writes devvm _links's events beside the proxy's, mode 600, rotating past 10 MiB; events carry target, which FormatEvent and devvm network log --json show. Tests: TestLinkArgs, TestLinkFiles, TestListenSocket, TestLinks, TestLinksSessionLost, TestLinksCap, TestIsLinkAddr, TestListeners (range exclusion) in vmssh; TestLinkAddrsAgree, TestLinkConn, TestSessionLinks, TestLinkEvents in vm; TestAppendEvent and link cases in TestFormatEvent; link_session.txtar for _links's argument and refusals; e2e's project section checks a server on 127.77.0.1 isn't forwarded while the VM's own on 127.0.0.1 with its port is. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
3b1959efd2 |
feat(network): network policy rules and log under devvm network, and network -g for new VMs
devvm network allow|deny|rm RULE... [-g] and devvm network log [-f] [-n N] [--blocked] replace devvm policy and devvm log. Bare devvm network shows the VM's network policy, then its allowlist file by file. devvm network -g shows or saves whether new VMs get network policy (ask, on or off), through the network file devvm setup also writes; --network-policy and --no-network-policy beat it and skip reading it, a saved off makes a VM without the docker-layer and backend warnings, and with ask and no terminal a new VM gets it. The proxy's block messages, devvm-why's, network log --blocked's ALLOW WITH and the VM's setup note name devvm network allow. New messages: net_default_failed, net_ask_global; -g reports with network_default. Docs, the CLI reference, txtars (network_rules, network_log, network), e2e (bare devvm network's first line) and AGENTS.md follow. Co-Authored-By: Claude Opus 5.5 <[email protected]> |
||
|
|
6f680a6f8b |
feat(proxy): a shared, read-only Nix cache that only the host fills
VMs with network policy and the nix layer share their downloads from cache.nixos.org: the proxy answers http://devvm.proxy/nix/ itself (a reserved endpoint, never forwarded), and the guest setup puts it before https://cache.nixos.org in Nix's substituters, trusted-public-keys left as Nix's own (cache.nixos.org-1). Each VM keeps its own store and daemon; only downloads are shared, and no VM can change what another gets. The proxy (internal/proxy/nixcache.go, -nix-cache DIR and -nix-cache-max BYTES): - takes only GET and HEAD, no query, nothing escaped, of nix-cache-info, <32 nix32>.narinfo and nar/<52 nix32>.nar with no suffix or .xz, .zst or .bz2 (nixPath, FuzzNixPath); 400 otherwise; - makes up nix-cache-info (priority 30, before cache.nixos.org's 40); - fetches from https://cache.nixos.org alone, when the VM's policy allows cache.nixos.org:443, through the floor or the company proxy, with the system's roots and the user's CAs, following no redirect, sending nothing of the VM's request; - keeps a narinfo when its StorePath is the path asked for, its URL is of the pattern and named by its own NarHash or FileHash, and a Sig by the pinned cache.nixos.org-1 Ed25519 key verifies over 1;StorePath;NarHash;NarSize;References (parseNarinfo, against a real narinfo and NAR of cache.nixos.org's in testdata/nix/); - fetches a NAR only after a narinfo it checked names it, never for a HEAD, once however many ask and at most four at once (fetchOnce), and keeps it when its SHA-256 and size are the narinfo's FileHash and FileSize; a cached copy of another size is dropped; - answers 404 to anything that fails, keeping nothing, so Nix goes to cache.nixos.org itself; logs each request as a nix-cache event (hit, fetched, or why not), which devvm log shows as cache; - writes files whole and renames them in, 600 in folders of 700. The cap: the nix-cache.size retention setting, 10 GiB when off (state.NixCacheDefault, proxy.NixCacheDefault), with state.ParseSize (500M, 20G, 1T). Under a flock on .lock every proxy takes a file's room before writing it (reserve, in whole blocks), deleting the least recently used files (by mtime, which a hit sets) down to nine tenths of the cap; a NAR being fetched is made its full size at once and counts, so a fetch the in-flight files leave no room for is refused. devvm gc trims to the cap, devvm gc --nix-cache empties it, and the daily retention run trims it (proxy.TrimNixCache, NixCacheUsage). devvm space has a Nix cache row (GC: what's over the cap, FREED BY gc --nix-cache, RETAIN nix-cache.size), devvm images says what it takes of its cap. netpolicy passes -nix-cache and -nix-cache-max only for images with the nix layer (nixCacheArgs; a retention file it can't read warns and uses the default). The guest setup writes /etc/nix/devvm-cache.conf through !include in nix.conf only with the nix layer and policy on, removes it otherwise, and restarts nix-daemon when it changes. VMs without network policy get no shared cache: they fetch from cache.nixos.org directly, and nothing new runs or listens on the host for them. Review (security-audit skill, on nixcache.go, its callers and the setup): a NAR could be kept under another NAR's name, as the URL isn't signed (fixed: the URL must be named by the narinfo's own hashes, and a hit of another size is dropped); files being fetched didn't count against the cap and blocks weren't counted, so one VM's parallel requests could pass it (fixed: reserve, full-size temp files, block counts, fetchOnce); a HEAD downloaded a NAR (fixed). Ruled out: stored VM input, paths out of the folder, another upstream, parser differences, cross-VM visibility beyond timing, a VM's own nix.conf. Open, documented: timing tells a VM whether some VM fetched a public path, and a VM can fill the cache to its cap. Messages: gc_nix_cache_over, gc_nix_cache, deleted_nix_cache, images_nix_cache; retention_deleted gains nix_files. Paths: Dirs.NixCache (structure limit for Dirs to 40). Flags: devvm gc --nix-cache; the CLI reference regenerated. Tests: TestNixPath, TestNix32, TestParseNarinfo, TestNixCacheServes, TestNixCacheRefuses, TestNixCachePolicy, TestNixCacheFetches, TestTrimNixCache, TestNixCacheCap, FuzzNixPath, TestParseSize, TestRetention, TestNixCacheArgs, TestFormatEvent; nix_cache.txtar (the proxy's endpoint and refusals, space, images, gc, gc --nix-cache, retention); e2e nix: the VM's substituters and keys, hello through the cache, fetched by the host (600/700), a VM's writes and other requests refused and nothing kept, a second VM's hits fetching nothing, no cache after devvm network off. Docs: the design note (internals/design.md), internals/network.md's The shared Nix cache, the VM's setup, logs and flags, internals/security.md, internals/images.md, safety/network.md's Nix and Logs, using/toolchains.md's Nix projects, using/images.md, using/space.md, using/settings.md's Retention, internal/proxy/README.md. Co-Authored-By: Claude Opus 5.5 <[email protected]> |