Skip to content

feat(microvm): P4.1 egress transport — vsock 1025 splice, pre-bound jail socket, fd hand-off (#277) - #582

Merged
pdettori merged 12 commits into
mainfrom
feat/277-p41-transport
Oct 22, 2026
Merged

pdettori merged 12 commits into
mainfrom
feat/277-p41-transport

Conversation

@pdettori

@pdettori pdettori commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Summary

P4.1 / #277, part 2 of 3: the transport. A guest's 127.0.0.1:3128 reaches the host over vsock
CID 2:1025, and the host listener is bound and handed to moca-egress before the guest can run.

#581 has merged; this PR is now based on main. Review fixes from the first round are the four commits on top: fc3b05ff (vsock rc.Control), f86404b1 (unbind/rebind serialised), 29d31fce (peer-UID test), f1f2292d (NO_PROXY loopback).

  • Control protocol — proto/egress/v1/control.proto (Register{vm_id, sid, grant},
    Unregister{vm_id}, ControlReply), Go only (TS stubs excluded in buf.gen.yaml).
  • Control channel — remote-worker/internal/egress/control: 4-byte-framed protobuf over a 0600 Unix
    socket, the listening fd passed with SCM_RIGHTS, peers admitted by SO_PEERCRED/LOCAL_PEERCRED
    UID. The client dups the caller's fd and replays every live registration on reconnect; a refused
    replay is evicted, not reported as the current call's verdict.
  • Guest agent — -egress-listen / -egress-vsock-port: brings lo up, listens on
    127.0.0.1:3128, and byte-splices each connection to vsock 1025 (not the framed protocol). A refused
    host side answers a named 502 egress_unreachable; half-close is propagated; transient accept errors
    back off rather than end egress in PID 1.
  • vmpool (Firecracker) — <jail>/run/v.sock_1025 is net.ListenUnix'd before the jailer
    starts (E13's listener-startup race cannot happen), chowned, and registered; a failed Register
    fails the restore, so the VM never becomes a standby. Teardown is SIGKILL → wait → Unregister →
    unlink → jail removal, on both the cleanup and Reap paths. vsockRelPath is now /run/v.sock.
    sun_path length is checked at construction. Egress on Cloud Hypervisor is refused by name.
  • Rootfs — /sbin/init exports HTTPS_PROXY/HTTP_PROXY (both cases) = http://127.0.0.1:3128,
    empty NO_PROXY, and the inert GH_TOKEN/GITHUB_TOKEN=moca-placeholder; a system git credential
    helper returns the placeholder; check_egress_listener fails the build if the guest listener isn't
    up. P4 §5.2 still holds (constants only; nothing matches the snapshot credential scanner).
  • Gates — TestGateEgressStandbyFailsClosed, TestGateEgressTeardownOrdering (CI);
    TestGateNoNetworkDevice (KVM, manual): the guest has only lo, no resolv.conf, a direct
    /dev/tcp dial fails with "Network is unreachable" — T7's property asserted directly.

Fixes to this layer that came out of the whole-branch review (cancelled calls no longer unbind every VM;
the client re-registers in the background after a moca-egress restart) land in the top PR, because
they were reviewed as one wave.

Checklist

  • Commits are signed off (git commit -s).
  • make lint and the tests for the touched packages pass. (go test -race ./... in remote-worker,
    gofmt, vet on darwin and linux, GOOS=windows go build ./..., make test-deploy, shellcheck
    -S warning.) Not yet run on a KVM rig — the vsock dial, loopback bring-up and restore with the
    new path are verified by the manual gates in the live acceptance on the top PR.
  • Docs: changed behavior, flags or environment variables are reflected in the relevant README or
    docs/ page, with the right maturity label (see docs/CONTRIBUTING-DOCS.md). (P4-ON-P6.md in
    the top PR)
  • Docs: make check-links passes if any Markdown changed.
  • A new spec or ADR is registered in docs/specs/README.md or docs/adrs/README.md. (n/a)

🤖 Assisted-By: Claude Code

@pdettori

Copy link
Copy Markdown
Member Author

Live acceptance for the whole stack passed on nested-m8i on 2026-10-22: KVM gates 11/11, plus live egress through the real relay. Details are in #583.

@pdettori
pdettori marked this pull request as ready for review October 22, 2026 11:29
@pdettori
pdettori requested a review from cwiklik as a code owner October 22, 2026 11:29
@pdettori pdettori added the ready-for-ai-review Request automated AI code review from clawgenti label Oct 22, 2026
@pdettori
pdettori force-pushed the feat/277-p41-transport branch from 5d655f6 to 92aae58 Compare October 22, 2026 11:56
Base automatically changed from docs/277-p41-amendment to main October 22, 2026 12:03

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the stack range 07905cd..92aae58 (rebased onto merged #581; git range-diff against the previously listed head 5d655f6 is = for every commit). Two must-fixes, both latent lifecycle bugs that the happy-path gates would not catch; two suggestions on the baked guest env.

Independently re-ran in an isolated sandbox at this head and at the #583 head: go test -race ./... (all packages pass), go vet linux+darwin, GOOS=windows go build, gofmt clean, -count=5 -race on internal/egress/... (no flakes), shellcheck -S warning clean. Generated control.pb.go matches the proto (field numbers, reserved 3, oneof); buf accepts exclude_types (drift itself not checked: BSR unreachable from the sandbox).

Checked and fine: framing limits before allocation, surplus SCM_RIGHTS fds closed, SO_PEERCRED check before any frame, socket pre-bound before cmd.Start, unlink on every error path, SIGKILL→wait→Unregister→unlink on both cleanup and Reap, sun_path bound, failed Register fails the restore, vsock_override keeps pre-P4.1 snapshots restorable, CHV refusal.

Author: pdettori (MEMBER — maintainer)
Areas reviewed: Go (proto/codegen, egress control channel, guest agent, vmpool), Shell (build-snapshot.sh + test)
Agent/IDE config (.claude/.vscode): none
Commits: 8 commits, all signed-off: yes
CI status: passing (DCO, k8s-kind-e2e — stacked base, so the main ci workflow did not run; tests reproduced independently as above)


remote := vsockAddr{cid: cid, port: port}
local := vsockAddr{cid: unix.VMADDR_CID_ANY}
if svm, ok := localSockaddrVM(int(f.Fd())); ok {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

must-fix: f.Fd() puts the file back into blocking mode (os.File.Fd calls pfd.SetBlocking; egress/control/client.go's dupFile avoids Fd() for exactly this reason). After this every vsockConn.Read is a blocking read(2) holding a poll.FD ref, so Close() neither wakes it nor actually closes the fd while it is in progress.

Failure: guest client resets mid-tunnel → copyConn(up, client) errors → closeBoth → the other goroutine stays parked in up.Read, the vsock fd stays open so the host never sees EOF; with an idle upstream (long-poll, stalled CONNECT) that's one leaked goroutine + OS thread + fd in PID 1 per aborted connection.

Fix: do the Getsockname inside rc.Control(func(fd uintptr){ ... }) (you already hold rc), or before os.NewFile. Worth a Linux test that Close unblocks a pending Read on a dialled conn.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in fc3b05f. The local address is now read through rc.Control, so the fd mode can never change.

One correction to the mechanism, which I checked against the Go source and on the rig: at this head Fd() did not flip the fd to blocking. os.NewFile saw the fd already non-blocking (we SetNonblock before NewFile), so with kind == kindNewFile it never set f.nonblock, and fd() had nothing to undo. The hazard was real but latent: it depended on that call order. Swapping the two calls, or a future refactor, would have produced exactly the leak you described.

TestDialedVsockCloseUnblocksAPendingRead (Linux, SH_VSOCK=1) pins the behaviour, not the call: Close must unblock a pending Read, and the peer must see EOF. On nested-m8i it passes at this head. It also passed against the old code, which is consistent with the above. It hangs against a variant of DialVsock that leaves the fd blocking, so it does catch the failure you described.

// dropConn runs when a control connection ends: bindings are owned by the connection that
// registered them, so a vmpool crash or restart cannot leave moca-egress serving VMs
// nobody manages.
func (s *Server) dropConn(sc *serverConn) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

must-fix: dropConn clears s.bindings under s.mu, then releases the lock and calls h.Unregister(vm) afterwards (L225-227). If the client's redialled connection replays Register(vm) in that gap, register sees owner == nil (L173), skips the supersede path, and calls h.Register while the proxy still holds the old binding → Proxy.Register returns duplicate_vm (proxy.go:124 in #583). The client treats a refused replay as final and evicts the VM (connect, "the VM has no egress until it is reaped"). The opposite interleaving is also bad: the late h.Unregister tears down the binding the new connection just made.

This is not exotic — the client redials immediately on any transport error/timeout (do attempt 2, and #583's heal loop within ~1 s), racing the server goroutine that is still processing EOF.

Fix: serialise each VM's unbind/rebind, e.g. hold a server-wide handler mutex across the bindings change and the matching h.Register/h.Unregister, or keep a 'releasing' marker that register waits on/supersedes. A test for the supersede path and this interleaving would pin it (none exists today).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f86404b, using the first option you suggested. A server-wide hmu now covers every bindings change together with its matching Handler.Register/Unregister call. That covers dropConn, the Unregister frame and register, including the supersede path. Lock order is hmu then mu, and handler calls happen only under hmu. Proxy.Unregister closes its listener and conns without waiting on them, so holding hmu across it cannot stall the server.

  • TestReRegisterRacingADroppedConnectionEndsBound parks dropConn's Unregister inside a handler that refuses a duplicate the way Proxy.Register does, then re-registers from a new connection. Against the old server it fails with re-Register completed while the stale Unregister was still in progress (err=… duplicate_vm). With the fix the re-Register waits and the VM ends bound.
  • TestRegisterFromASecondConnectionSupersedes covers the supersede path, and checks that the superseded connection's later disconnect does not unbind the new owner.

Both pass 10/10 under -race, and the whole control package passes 5/5.

}
}

func TestServerRefusesAPeerOutsideAllowedUIDs(t *testing.T) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: this only asserts err != nil, so a dial failure or any unrelated error passes too. Assert that the server closed the connection without a reply (EOF / ErrUnexpectedEOF on the read), so the test fails if the UID check stops being the reason.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 29d31fc. The test now speaks the wire directly and requires EOF (or ECONNRESET) with no reply frame for a disallowed UID. It also has a control case in which an allowed UID does get a reply. With the UID check disabled, the test fails with disallowed peer got a reply frame (2 bytes).

Comment thread deploy/microvm/build-snapshot.sh Outdated
export https_proxy=http://127.0.0.1:3128
export HTTP_PROXY=http://127.0.0.1:3128
export http_proxy=http://127.0.0.1:3128
export NO_PROXY=

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: with NO_PROXY empty, loopback traffic in the guest also goes to 127.0.0.1:3128 → vsock → moca-egress, which refuses loopback destinations (CheckAddr, 403 destination_private). So a test suite that starts a server on localhost:8000 and calls it with requests/urllib/pip/node breaks on this tier, where it worked before. NO_PROXY=localhost,127.0.0.1,::1 (and lowercase) doesn't open any bypass (there's no NIC; T7) and keeps in-guest loopback working. If the spec's 'must be empty' is deliberate, consider a sentence saying why loopback is meant to go through the proxy.

Related, already acknowledged in #583's docs: the exported GH_TOKEN/GITHUB_TOKEN=moca-placeholder turn anonymous gh calls into 401 until S2. Fine as a recorded trade-off; just noting that leaving them unset until S2 ships would avoid the regression without affecting the snapshot scanner.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adopted the NO_PROXY change in f1f2292: it is now localhost,127.0.0.1,::1, in both cases. You are right that it opens no bypass, because there is no NIC (T7). The P4.1 spec line "NO_PROXY must be empty" is amended in the same commit with the reason. The build-snapshot test pins the new value.

On GH_TOKEN/GITHUB_TOKEN: I kept them for now. P4.1 T5 and MI1 §8.4 (D7) put the constant placeholder in the image under those names. The KVM gate asserts it, and #583 records the 401 trade-off. Removing them would also need a snapshot rebuild, and S2's CA work rebuilds the snapshot anyway. If you would rather avoid the anonymous-gh regression until S2 ships, it is a two-line change plus the gate and doc. Say the word and I will make it.

… hand-off (MI1 §8.3)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…D check, replay on reconnect

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…ent call

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…02 on refusal (P4.1 T2)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…n before closing a 502

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…GKILL→Unregister→unlink (P4.1 §6)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
… listener at build, assert no NIC (P4.1 T5/T7)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…c.Control, not Fd()

Review on #582: os.File.Fd() puts a file back into blocking mode, after which a pending Read
holds the fd past Close. Here it did not -- os.NewFile sees the fd already non-blocking and
records nothing to undo -- but only because SetNonblock precedes NewFile. The address is now
read through rc.Control, which cannot change the mode at all.

TestDialedVsockCloseUnblocksAPendingRead pins the behaviour: Close must unblock a pending Read
and the peer must see EOF. On nested-m8i it passes with this change and hangs on a variant of
DialVsock that leaves the fd blocking.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Review on #582: dropConn cleared a VM's binding under the lock, released it, and only then
called Handler.Unregister. A redialled client replaying Register in that gap found no owner,
skipped the supersede path and called Handler.Register while the handler still held the old
binding, so moca-egress refused it as duplicate_vm and the client evicted the VM. The other
interleaving let the late Unregister tear down the binding the new connection had just made.

A server-wide handler mutex now covers every bindings change together with its matching
Handler call (lock order hmu, then mu). TestReRegisterRacingADroppedConnectionEndsBound parks
dropConn's Unregister and re-registers from a new connection: before this change the
re-Register was refused as duplicate_vm; now it waits, and the VM ends bound.
TestRegisterFromASecondConnectionSupersedes covers the supersede path, which had no test.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…hout a reply

Review on #582: it only checked err != nil, so a dial failure or any unrelated error passed.
It now speaks the wire directly and requires EOF with no reply frame for a disallowed UID, plus
a control case where an allowed UID gets a reply. With the UID check disabled the test fails
("disallowed peer got a reply frame").

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Review on #582: with NO_PROXY empty, a request to localhost inside the guest went to
127.0.0.1:3128, over vsock, to moca-egress, which refuses loopback destinations -- so an
in-guest server (a test suite on localhost:8000) broke on this tier. NO_PROXY is now
localhost,127.0.0.1,::1. That opens no bypass: the guest has no network device (T7), so its
loopback is the guest itself. The P4.1 spec's "NO_PROXY must be empty" is amended to match.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
@pdettori
pdettori force-pushed the feat/277-p41-transport branch from 92aae58 to f1f2292 Compare October 22, 2026 13:59

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up to our review at 92aae58. The rebase onto main is content-identical for the original 7 commits (range-diff all =), so I reviewed only the 4 new fix commits. All four prior items are addressed:

  • dial_linux.go Fd(): fixed. Reading the local addr through rc.Control no longer depends on the SetNonblock-before-NewFile ordering. You're right that with that ordering Fd() wouldn't have flipped the fd to blocking (Go 1.26 newFile only sets f.nonblock when os set it), so the original finding overstated the risk. The change and TestDialedVsockCloseUnblocksAPendingRead are still the right guard.
  • server.go dropConn race: fixed. hmu serialises each bindings change with its Handler call, with a consistent hmu→mu order and no Handler call under mu. rebind_test.go covers both the parked-Unregister race and the supersede path, including the superseded conn's later drop.
  • peer-UID test: fixed. It asserts close-without-reply and has an allowed-UID control case.
  • NO_PROXY: fixed. It now uses the guest loopback only, with the test and spec §T5 amendment.

One leftover nit not on a diff line: the spec's file table at docs/specs/2026-09-15-p4-1-microvm-egress-transport-design.md:307 (build-snapshot.sh row) still says "empty NO_PROXY", which contradicts the amended §T5.

CI is green on f1f2292.

if _, err := p.Exec(context.Background(), "gate-secrets", Exec{Command: "env", TimeoutS: 30}, &out); err != nil {
t.Fatalf("Exec env: %v", err)
}
// P4.1: the guest env now carries HTTPS_PROXY/HTTP_PROXY (and lowercase), empty

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: this comment still says "empty NO_PROXY". Since f1f2292 the guest env carries NO_PROXY=localhost,127.0.0.1,::1 (and lowercase).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6bdf9fd. The comment now reads NO_PROXY=localhost,127.0.0.1,::1 (and lowercase). I also brought its credential-pattern note in line with the narrowed scanner ("PEM private-key header").

Re-review on #582. Since f1f2292 the guest carries NO_PROXY=localhost,127.0.0.1,::1, but
the gate comment in TestGateSnapshotHoldsNoSecrets and the P4.1 spec's file table
(build-snapshot.sh row) still described it as empty, contradicting the amended §7. Both now
match. The gate comment's credential-pattern note also now says "PEM private-key header",
the pattern since the nested-m8i run. The rest of the spec diff is prettier re-padding the
table.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
@pdettori

Copy link
Copy Markdown
Member Author

The leftover nit not on a diff line is fixed in 6bdf9fd: the spec file table's build-snapshot.sh row now says NO_PROXY names only the guest's loopback (§7), instead of "empty NO_PROXY". The only remaining "empty NO_PROXY" in the spec is the §7 amendment sentence that explains the old rule. #583 is rebased onto it, with one trivial conflict on the gate comment resolved to this head.

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review at 6bdf9fd. This is a docs/comment-only follow-up to our f1f2292 approval. Both nits are fixed: the gate comment in TestGateSnapshotHoldsNoSecrets and the spec §12.1 build-snapshot.sh row now describe NO_PROXY=localhost,127.0.0.1,::1 correctly. LGTM.

@pdettori
pdettori merged commit 804dc70 into main Oct 22, 2026
15 checks passed
@pdettori
pdettori deleted the feat/277-p41-transport branch October 22, 2026 14:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-ai-review Request automated AI code review from clawgenti

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants