Skip to content

egress: write the host's lane verdict into every NIC-bearing guest - #171

Merged
CMGS merged 1 commit into
mainfrom
feat/egress-lane-file
Sep 14, 2026
Merged

CMGS merged 1 commit into
mainfrom
feat/egress-lane-file

Conversation

@CMGS

@CMGS CMGS commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

Stacked on #170 (base feat/egress-rule-ports); merge order #169 → #170 → this → the review PR that follows. One commit of its own. Closes #167.

The desktop image's guest-proxy-setup decided from NIC presence, so on a guarded bridge lane the GNOME session and osworld-server got neither a route nor the relay; and the boolean marker #165 introduced only said "locked", which left a NIC-bearing guest no way to tell "the host has not decided yet" from "the host says direct".

Change

  • sandboxd/engine/lane.go replaces nicmark.go: Lane (relay | direct) and Engine.MarkLane write /etc/silkd-lane through the existing fs_write path.
  • sandboxd/pool: laneOf(key) is empty on the none lane (no NIC to route through), relay when the lane is locked (bridge), else direct (CNI); markLane writes it at the same three sites the marker used (golden build after the readiness probe, cold provision, the late reconcile lock). The .nic golden sidecar stores the word, so a golden built under another verdict — including one built by the marker version — is rebuilt, not adopted; none-lane goldens keep matching. Engine.MarkLane replaces MarkNICLocked; fake engines follow.
  • silkd/src/net.rs: routes_directly() is true only for a NIC whose lane file does not read relay; an absent or unreadable file routes directly, so an old sandboxd that writes nothing leaves the guest as it was. Unit test covers absent / direct / relay.
  • os-image/desktop/24.04/Dockerfile: guest-proxy-setup still configures the relay at once when there is no NIC; with a NIC it waits for /etc/silkd-lane, follows relay, and exits on direct. The unit already ran After=silkd.service and Before=desktop-session.service osworld-server.service, so the session and osworld-server start after the verdict.
  • e2e/cmd/desktopsmoke gains -net none|egress and -probe: on the egress lane the checkpoint/branch leg (refused on the lane) gives way to a /execute leg that requires http_proxy in the session's environment and a 200 from the allowed origin through the relay; the /execute parsing moved into one execute helper used by both legs.
  • Docs: docs/silkd.md, docs/egress.md (lane paragraph), docs/desktop.md (lane bullet, unit bullet); desktop pools may use the egress lane again.

Decisions

  • A two-word file instead of the boolean marker plus a timeout: "no file after N s" as the direct signal would freeze a wrong verdict into a golden and every clone of it when the host probe is slow; with direct written explicitly, a timeout fires only for an old sandboxd.
  • The none lane gets no file: both consumers already treat no NIC as relay, and a file there would be a third source of the same fact.
  • The reconcile late-lock case (a live claim whose node flipped CNI → bridge) is written but the running desktop session is not re-configured: a re-claim heals it, deploy.md makes draining claims part of upgrading, and silkd's execs follow the file at once.
  • The marker is renamed, not kept alongside: egress: tell the guest when its NIC is locked so the bridge lane gets the proxy variables #165 shipped in no release tag.

Codex's review of this branch raised one MAJOR: a 30 s guest wait is shorter than the host's own worst case (90 s probe plus a 2-minute write timeout), so a late relay could land after the desktop had configured itself and been snapshotted. That is resolved in the review PR stacked on this one, the way the previous batch's round fixes rode #168 on #165: the wait is 300 s (longer than the host's success window, so a guest still waiting belongs to a boot the host already failed), the timeout exits non-zero so a mis-timed build is visible, the NIC test matches silkd's device-backed probe, and desktopsmoke asserts the unit is active. Merge this PR together with the review PR.

Hot path

None on the claim path: the write happens at golden build, cold provision and the late reconcile lock. silkd's per-exec cost on a NIC-bearing guest is one small read (the marker was one stat; measured below noise: 750 vs 745 µs exec RTT); the review PR latches a relay verdict so the bridge lane pays it once. Nothing on the none lane.

Tests and evidence

  • TestLaneVerdictReachesGuestOnColdBoots (locked / unlocked egress lane and none lane, golden and cold), TestGoldenNICSidecarGatesAdoption; silkd lane_file_decides_relay.
  • Gates: make go-lint 10 × 0 issues.; asl -forwarder=false clean on both GOOS; go test engine/pool; go vet ./... e2e; silkd cargo fmt --check, clippy -D warnings, 111 tests on macOS and 111 in a rust:1.98.0 linux/arm64 container.
  • Hardware, cocoon-test1, guest images carrying this silkd (rt-lane4, desktop-lane4 = desktop:24.04 + this silkd + this guest-proxy-setup): scripts/egress-e2e.sh NET=none PASS and NET=egress BRIDGE=sbxbr0 PASS (direct egress blocked by the lock, allowed origin reached with and without -x with the injected credential, denied host 403); scripts/sandboxd-e2e.sh BRIDGE=sbxbr0 PASS including restart re-adoption; desktopsmoke -net egress PASS on a 2xlarge egress-lane desktop pool with a policy (screenshot, AT-SPI tree, PyAutoGUI click, then: the session's environment carries the relay and the allowed origin answers 200 through it, audited as a GET on port 80); desktopsmoke -net none PASS with the checkpoint/branch leg.

@CMGS
CMGS force-pushed the feat/egress-rule-ports branch from 5e163a3 to e8176f8 Compare September 14, 2026 06:54
@CMGS
CMGS changed the base branch from feat/egress-rule-ports to main September 14, 2026 06:55
The desktop image's guest-proxy-setup decided from NIC presence, so on a
guarded bridge lane the GNOME session and osworld-server got neither a
route nor the relay, and silkd's marker only said "locked", which left a
guest with a NIC no way to tell "the host has not decided yet" from "the
host says direct". sandboxd now writes /etc/silkd-lane with the verdict,
relay on a locked bridge lane and direct on a CNI lane, at the same three
sites the marker used (golden build, cold provision, late reconcile
lock); the golden sidecar records the word so a golden built under
another verdict is rebuilt. silkd routes directly only when the file does
not read relay, one 8-byte read per exec on a NIC-bearing guest, nothing
on the none lane. guest-proxy-setup waits up to 30 s for the file on a
NIC-bearing guest, follows relay, and treats direct or a silent host as
routing. desktopsmoke gains -net egress with a fetch through the
session's proxy environment in place of the checkpoint leg, which the
lane refuses. The old marker shipped in no release, so it is renamed
rather than kept.

Closes #167
@CMGS
CMGS force-pushed the feat/egress-lane-file branch from 11e2fcb to fe3416d Compare September 14, 2026 06:56
@CMGS
CMGS merged commit a5a868e into main Sep 14, 2026
2 checks passed
@CMGS
CMGS deleted the feat/egress-lane-file branch September 14, 2026 06:59
CMGS added a commit that referenced this pull request Sep 14, 2026
…te (#173)

Batch-end round on the state with #169, #170 and #171 merged, scoped by the hygiene ledger (0 files due after) plus an ownership pass over all of silkd. Fixed with tests: hostPort defaulted the port it could not parse and serveConnect dialed the raw authority, so a path-form CONNECT with Host: example.com:+22 was judged as 443, allowed by a ports rule and dialed to port 22; every malformed authority (out-of-range port, two ports, stray or unclosed brackets, empty host) is now a deny with a no-port audit line, the dial and the intercept authority come from the parsed pair, and serveSocks refuses port 0. The SOCKS5 door becomes the pool policy's call (the tenant's rules already gate every tunnel), ServesSocks trusts Validate, the desktop unit's wait outlives the host's probe and write timeouts and fails visibly on timeout, silkd latches a relay verdict and serves base_env from a static slice, deploy docs gain the daemon/image lockstep and the strict-config rollback. Round net prod +34 / test +88, comment lines +5 / -8; every gate green on both platforms, hardware suites and the desktop lane PASS on cocoon-test1; Codex converged after five rounds.
CMGS added a commit that referenced this pull request Nov 4, 2026
* silkd: a client hang-up reaps an attached language server

The pump only watched the server's stdout, so a silent server that ignored stdin EOF pinned its memory after the client left. A request frame during the stream ends it the same way, as a pty does.

* silkd: git_branch list names an unborn branch

rev-parse --abbrev-ref fails on an unborn HEAD and printed HEAD, while git_status on the same repo reports the branch. A detached HEAD still reads HEAD.

* review: silkd docs: attach never ends in done, a dropped port_forward can linger

* review: silkd and sandbox-init borrow what they only read

claim_env keeps its one read buffer and parses into borrowed pairs, so an exec, pty or session drops 2N String allocations. BootCfg and IpParam borrow the cmdline, read_manifest returns its text, apply_config sets literals, pty and upload signatures take plain borrows, and scan_serials formats a path only when it reads it. Tests changed only where a literal's type or a temporary's lifetime named the old owned form.

* review: silkd drops code that cannot run

Child::id is Some right after spawn, a session body is never empty, Path::file_name is never empty, abort on a finished task is a no-op, and the exec rebinds did nothing. Table::new and Broker::new only aliased Default; git hand-rolled error_frame; the imds consts and handle, DEFAULT_INIT and PROTO_VERSION had no outside user; the ignored bench asserted nothing.

* review: silkd statics and test helpers follow the file layout

Function-local statics and consts move to the top-of-file block, and the one-caller proxy_vars and silkd_net wrappers go with them; test helpers move above the tests and private below public.

* review: silkd comments shrink to what the code cannot carry

Module narratives go to one line, the imds token fact moves to its const, a history comment goes, make_controlling_tty becomes safe because it has no memory precondition, and find's at_root stops shadowing the root param.

* review: silkd tests use the shared request and assert_error helpers

* sdk/python: ship the PEP 561 py.typed marker

The package is fully annotated and mypy-strict, but the wheel carried no marker, so a
consumer's type checker treated every cocoonsandbox import as untyped (reveal_type gave
Any). Add the marker and the setuptools package-data entry; a scratch wheel now lists
cocoonsandbox/py.typed and mypy on a consumer reveals cocoonsandbox.sandbox.Sandbox.

* review: one-line docstrings where several lines restated the signature or sibling docs

* review: drop duplicate test fixtures and a subset test; share FakeConn through conftest

* review: tests before helpers in test_stream and test_client

* review: adapters floor the SDK at 0.1.13, where the in-guest kill after a timeout cut first shipped

* review: silkdtest's default arm calls serveStateless

The arm re-spelled serveStateless byte for byte.

* review: trim multi-line comments on unexported decls, capitalise own-line comments

Own-line comments start uppercase per /code Comment Style; multi-line godocs on unexported names cut to one line.

* review: guestserver keeps its report utility below the halfCloseSink block

Layout only: /code File Organization puts utility funcs below the type's methods.

* review: volumesmoke rejects non-local probes with filepath.IsLocal

Same verdict as the hand-rolled path test on 15 inputs.

* review: harness owns the guest proxy address, RelayConn and a package-level Request

The proxy address was declared in four drivers. Dial returns RelayConn so portsmoke calls CloseWrite directly. PortRelay.Request never read its receiver. credsmoke's expectPlaceholder locals stop shadowing the entry and header consts.

* docs: deploy's upgrade notes name the release each starts from

At v0.1.21 "this release" read as every upgrade needing a drain, a fresh data dir and an emptied bucket. Releases come from the first tag holding each commit: #81 v0.1.6 (the pool key's engine axis went), #364 v0.1.18, #59 v0.1.5, #69 v0.1.5 and #72 v0.1.6, #171 and #169 v0.1.11.

* docs: deploy and egress samples load and name a pulled image by its full ref

A pulled image is keyed by its whole ref, so template base:24.04 fails the golden build with image not found, as the README already fixed in #425. The deploy sample's cluster_key and the egress sample's missing egress_ca failed config.Load.

* docs: deploy states what the code requires of a failed claim, a golden and a dump

A wake of a failed egress-lane or volume claim answers 409, tenants get 403 on two more root routes, golden dumps queue, an idle default acts on running claims at the next sweep, and an adopted replica always wakes on a read; none of these had a line.

* docs: deploy gives the archive registry's DDL

A role without CREATE could not enable archive_failover from the docs: the other three shared tables have a pre-create DDL and this one had none.

* docs: deploy keeps the S3 layout and the replica bound in one place each

The checkpoint_store row repeated the Reclaiming S3 storage section, which takes the facts only the row carried (lineage scope, marker order, re-stamped manifests); the TTL, replica-loss, tenant-outage and cluster-invariant passages become links to the pages that own them.

* docs: cluster lists registered volumes and the TTL, and says when the digest covers secrets

An operator rebuilding data_dir from config.json lost runtime-volumes.json silently, and gauge 0 read as a check of two secrets a keyless digest never covers.

* docs: security names the TLS edge, the re-admitted prefix and the shared usage table

Stated as hard constraints these ruled out what deploy ships: a TLS edge for SDK clients, egress_internal_allow, and meta_store.usage.

* docs: benchmarks and performance keep each caveat once

* docs: api states redirects, operator tokens, fork env and the checkpoint list as the server does

The mint endpoint never answers the 503 and 429 its paragraph listed: the browser request does. A template another node deleted stays in tplSet, so the cluster page's never-fires claim was false for that entry.

* docs: api lists the errors of a call that reaches a guest once

Wake, agent, ports and exec carried the same four tails. Restore failures, 409s, release, hibernate and the preview listener differ, so they keep their own lines.

* docs: sdk, silkd, langchain and android match what the code does

Go Exec runs the argv given, with no implicit shell; every control-plane verb returns APIError; the checkpoint option refusals and a fork child's env were incomplete.

* docs: the sdk pages link the volume and deadline rules the api page owns

Go-specific and Python-specific names stay. The settled-entry sentence stays on the Go page, its only source.

* sandboxd: a preview listener that cannot bind is fatal

A taken preview_listen was logged and ignored: the node stayed healthy while the preview endpoint kept minting URLs for a dead port. The main listener already exits on the same failure, and systemd Restart= is the retry loop. http.ErrServerClosed stays clean.

* tenants: the contract replaces the set with no tenants

An empty Replace must delete every tenant on both backends: pgx sends a nil slice as NULL, so a Collect-built name list would delete nothing on pg.

* review: one owner for the max fork default, the routable-host test, the s3 store test and the tenant claim mapping

config.DefaultMaxForkCount replaces the second literal in pool, config.RoutableHost replaces the copy in server.New, Config.S3Checkpoints replaces three spellings of the kind test, and forTenant replaces the tenant-to-options mapping written in both claim paths. Behaviour-preserving, net zero lines.

* review: store package docs fit the comment budget, constant errors use errors.New

Package docs of store, s3 and peer shrink to one line (docs/deploy.md owns the key layout); the SweepStaging godoc and the redirectCacheEntry comment restate their names; three message-only fmt.Errorf become errors.New; VolumePatch is decode-only, so its slices follow the omitempty rule.

* pool: a fenced node captures no replicated claim

Fork, Checkpoint and Promote reached captureAllowed with no fence gate, so a node past its lease window could hand out children, a checkpoint or a template from a claim a peer may already own. ErrLeaseLost maps to 503 through the error table and is benign to the archive and replicate sweeps.

* pool: consumeArchive reads the row epoch under the manager lock

An unfence rewrites ArchiveEpoch holding only m.mu, and a release or replica retirement read it holding only Transition, so the two raced. The stale read cost at most a refused Consume and a settle round trip.

* review: pool comments name what the code does now

Two field comments named fields that moved to configView, checkTemplateOwner never deletes, HasPromotedTemplate's cache can go stale, and poolSeedHash's field list drifted against the lines below it.

* review: checkpoint.go keeps const and var above its types

* review: fold pool helpers with one caller

archiveDeleteFor, unpooledTemplates, archiveFetchErr, dropStaleRow, hasRegularFile, deliverGuestEnv and TenantRecords each had one caller. reputArchive's held parameter was dead: its only caller guards a non-zero epoch.

* review: one owner for pool facts stated twice

replicaPools repeated view.poolReplicate, whose key set a reload cannot change and PUT /v1/pools cannot set. The view's map guards bought nothing, since every reader takes the zero value. env and replicable spelled out runningShaped, AgentSocket spelled out isFenced, and the two reader teardowns stripped a cancel that removeVM strips itself. addClaimLocked gains one atomic load on nodes with archives and nothing elsewhere.

* review: pool sweeps and wakes carry what they have

commitWake logged its persist failure at Warn and its caller rebuilt the error with the cause dropped; it now returns the error. idleOnce copied id and token so idleHibernate could look the claim up again, and hibernateLocked's setIfLive already answers ErrUnknownSandbox for a released claim. Fork and Checkpoint no longer wait on Transition for a usage field, since every write of VMName after publication holds m.mu; lockedVMName stays for tests, which read under Transition.

* review: types.go splits into env.go and volume.go

Pure move: the env types, limits and patterns go to env.go and the volume types, modes and mount validation to volume.go, matching the existing env_test.go and volume_test.go. envView and namedVar stay beside the Sandbox that owns them. No line changes beyond imports and gofmt alignment.

* egress: an upstream dying mid-body truncates the guest's response

relay dropped the copy error, so net/http wrote the terminating chunk and the guest read a partial body as complete. Hijack and close the conn on a copy error, which leaves the chunked stream unterminated. Success costs one nil check.

* outbound: ArmProxy closes a displaced door before it binds

The close unlinks the socket path, so a re-arm that bound first left the guest with no door while Route reported relay. A re-arm with no policy left now closes the door too, which makes the Disarm in restartLocked dead. The claim path pays one map delete under a lock it already holds.

* engine: a restore gets the dump budget

A dump may take 15 minutes while an eager-copy restore of the same image had 2, so a slow page cache could fail the wake it had just made possible. cocoon gives vm.restore the same limit as vm.snapshot. Clone and cold boot keep the command budget.

* review: drop checks and fields the code already guarantees

ReadSlice caps a line at the reader's buffer, IsGlobalUnicast already excludes link-local and multicast, UnixListener.Close already unlinks, marshalCA's public key is its PEM key's, and interDER copied interCert.Raw.

* review: DialFunc's Router methods serve only tests

The only production egress.New takes a claim as its router, so the two methods move to the egress test file.

* review: a CA key error names the key its caller parsed

parseECKey said intermediate key while parsing the root, so IssueIntermediate reported root key: intermediate key. validHostName takes the package's maxHostLen for the same DNS limit.

* review: cut a restating godoc and fold the engine package doc to one line

* review: layout: silkd helpers live in silkd.go, tcpAddrPort beside proxy.go's other address helpers

installca.go kept the generic guest write and exec helpers every other engine file uses; installOutputMax becomes guestOutputMax since it caps every guest exec.

* docs: name the capture fence, the restore budget, a preview bind failure and a cut upstream

* review: VolumePatch keeps the SDK's omitzero tags, as the wire parity test requires

* engine: a clone restores memory like a restore, so it gets the dump budget

cocoon's vm clone and vm restore share restoreVM and its 10 minute memory transfer, and an archived wake and a fork go through clone. A hung refill clone now holds its slot for up to 18 minutes, which stays bounded and loud.

* review: silkd's language server feed needs no flag or channel, and one helper sets the claim env

* review: refill.go keeps the refill loop; golden builds go to golden.go, VM provisioning to provision.go, destroyAll and dropSnap beside destroy, runBounded to pool.go with its callers across the package

* review: the reaper leaves claim.go for reap.go, since expiry handling is not claim admission

* review: claim and authed resolve a credential, so they sit in operator.go with resolve and byID

* review: the pool type joins its watermark methods in watermark.go, so its type block is atomic

* review: rewriteArchiveRow writes an archive row, so it sits in failover.go beside refusedReplace

* review: NewManager delegates template and volume seeding to loadTemplates in template.go and seedVolumes in volume_catalog.go, keeping the order

* review: the catalog owns its entries and holders, so catalogVolume, catalogSnapshot and the holder bookkeeping move to volume_catalog.go as volumeCatalog methods

* review: the seven single-flight sweep guards group into one sweeps field on Manager

* review: recordLocks owns the per-record lock maps and their mutex, and recLock's doc says it returns the lock without taking it

* review: healVetoes owns the heal veto maps and their mutex, replacing the three Manager methods and fields

* review: ckMarkers owns the archive delete markers, and the delete and retry chain moves with it to archive_delete.go

* pool: an uncordon during an evacuation's drain stops it

Evacuate waits for the warm VMs to go before it starts its run. A DELETE /v1/drain in that wait found nothing to stop, and the run then moved every claim off an uncordoned node.

* pool: a tier claim woken past its lease before the export gets a fresh lease

The reaper archives a hibernated claim of a tier pool at its lease end, and the same call a moment after the export restores it with a fresh lease. A call in between woke it with the past deadline, so the next reap tick destroyed it.

* pool: a running claim that moved to a peer closes its egress doors

forgetAdopted removes the VM with no sandbox id, so the removal never disarms. The doors, their listeners and their goroutines stayed until the next restart, one set per moved claim, unlogged.

* docs: a moved claim's token, its first wake, and the 503s an evacuation and the tenant store answer

* sdk: Close follows a sandbox that moved off a retired node

Close looked the sandbox up only on a 404 from its old owner. Once that node is retired, the first release fails to connect, so the claim stayed on the adopter until its deadline, and every retry hit the same dead address. A connection failure now looks it up too, and keeps its error when no node answers.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

desktop: guest-proxy-setup should follow the lane the host decides, not NIC presence

1 participant